@punks/cli 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/BASELINE_CHANGELOG.md +33 -1
  2. package/dist/CHANGELOG.md +45 -0
  3. package/dist/baseline/scaffold-baseline/baseline.json +15 -5
  4. package/dist/baseline/scaffold-baseline/data/catalog/packs.json +11 -1
  5. package/dist/baseline/scaffold-baseline/data/catalog/skills.json +16 -0
  6. package/dist/baseline/scaffold-baseline/data/scripts/commit-gate-runner.d.ts +2 -1
  7. package/dist/baseline/scaffold-baseline/data/scripts/commit-gate-runner.mjs +21 -5
  8. package/dist/baseline/scaffold-baseline/data/scripts/commit-gate-runner.test.ts +192 -14
  9. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/commands.md +4 -2
  10. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/post-command-flow.md +10 -4
  11. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/verify-behavior/SKILL.md +1 -1
  12. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/verify-behavior/agents/openai.yaml +2 -0
  13. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/SKILL.md +1 -1
  14. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-backend-structure/SKILL.md +8 -7
  15. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-backend-structure/references/layout.md +32 -6
  16. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-service-design/SKILL.md +2 -0
  17. package/dist/baseline/scaffold-baseline/skills/frameworks/react/react-doctor/SKILL.md +19 -4
  18. package/dist/baseline/scaffold-baseline/skills/frameworks/react/react-doctor/references/explain.md +5 -1
  19. package/dist/baseline/scaffold-baseline.json +5 -5
  20. package/dist/baseline/scaffold-baseline.tgz +0 -0
  21. package/dist/data/scripts/commit-gate-runner.mjs +21 -5
  22. package/dist/index.js +19 -18
  23. package/dist/skills/agnostic/cli/hi-cli/references/commands.md +4 -2
  24. package/dist/skills/agnostic/cli/hi-cli/references/post-command-flow.md +10 -4
  25. package/dist/skills/agnostic/planning/verify-behavior/SKILL.md +1 -1
  26. package/dist/skills/agnostic/planning/verify-behavior/agents/openai.yaml +2 -0
  27. package/dist/skills/agnostic/quality/tdd/SKILL.md +1 -1
  28. package/dist/skills/frameworks/effect/effect-backend-structure/SKILL.md +8 -7
  29. package/dist/skills/frameworks/effect/effect-backend-structure/references/layout.md +32 -6
  30. package/dist/skills/frameworks/effect/effect-service-design/SKILL.md +2 -0
  31. package/dist/skills/frameworks/react/react-doctor/SKILL.md +19 -4
  32. package/dist/skills/frameworks/react/react-doctor/references/explain.md +5 -1
  33. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -153,7 +153,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
153
153
  `)+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf(`
154
154
  `,nl)+1}}yield*this.pop();break;default:yield*this.pop();yield*this.step()}}*blockMap(map12){const it=map12.items[map12.items.length-1];switch(this.type){case"newline":this.onKeyLine=false;if(it.value){const end="end"in it.value?it.value.end:undefined;const last=Array.isArray(end)?end[end.length-1]:undefined;if(last?.type==="comment")end?.push(this.sourceToken);else map12.items.push({start:[this.sourceToken]})}else if(it.sep){it.sep.push(this.sourceToken)}else{it.start.push(this.sourceToken)}return;case"space":case"comment":if(it.value){map12.items.push({start:[this.sourceToken]})}else if(it.sep){it.sep.push(this.sourceToken)}else{if(this.atIndentedComment(it.start,map12.indent)){const prev=map12.items[map12.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it.start);end.push(this.sourceToken);map12.items.pop();return}}it.start.push(this.sourceToken)}return}if(this.indent>=map12.indent){const atMapIndent=!this.onKeyLine&&this.indent===map12.indent;const atNextItem=atMapIndent&&(it.sep||it.explicitKey)&&this.type!=="seq-item-ind";let start=[];if(atNextItem&&it.sep&&!it.value){const nl=[];for(let i=0;i<it.sep.length;++i){const st=it.sep[i];switch(st.type){case"newline":nl.push(i);break;case"space":break;case"comment":if(st.indent>map12.indent)nl.length=0;break;default:nl.length=0}}if(nl.length>=2)start=it.sep.splice(nl[1])}switch(this.type){case"anchor":case"tag":if(atNextItem||it.value){start.push(this.sourceToken);map12.items.push({start});this.onKeyLine=true}else if(it.sep){it.sep.push(this.sourceToken)}else{it.start.push(this.sourceToken)}return;case"explicit-key-ind":if(!it.sep&&!it.explicitKey){it.start.push(this.sourceToken);it.explicitKey=true}else if(atNextItem||it.value){start.push(this.sourceToken);map12.items.push({start,explicitKey:true})}else{this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:true}]})}this.onKeyLine=true;return;case"map-value-ind":if(it.explicitKey){if(!it.sep){if(includesToken(it.start,"newline")){Object.assign(it,{key:null,sep:[this.sourceToken]})}else{const start2=getFirstKeyStartProps(it.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}}else if(it.value){map12.items.push({start:[],key:null,sep:[this.sourceToken]})}else if(includesToken(it.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]})}else if(isFlowToken(it.key)&&!includesToken(it.sep,"newline")){const start2=getFirstKeyStartProps(it.start);const key=it.key;const sep=it.sep;sep.push(this.sourceToken);delete it.key;delete it.sep;this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep}]})}else if(start.length>0){it.sep=it.sep.concat(start,this.sourceToken)}else{it.sep.push(this.sourceToken)}}else{if(!it.sep){Object.assign(it,{key:null,sep:[this.sourceToken]})}else if(it.value||atNextItem){map12.items.push({start,key:null,sep:[this.sourceToken]})}else if(includesToken(it.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]})}else{it.sep.push(this.sourceToken)}}this.onKeyLine=true;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs=this.flowScalar(this.type);if(atNextItem||it.value){map12.items.push({start,key:fs,sep:[]});this.onKeyLine=true}else if(it.sep){this.stack.push(fs)}else{Object.assign(it,{key:fs,sep:[]});this.onKeyLine=true}return}default:{const bv=this.startBlockValue(map12);if(bv){if(bv.type==="block-seq"){if(!it.explicitKey&&it.sep&&!includesToken(it.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(atMapIndent){map12.items.push({start})}this.stack.push(bv);return}}}}yield*this.pop();yield*this.step()}*blockSequence(seq){const it=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it.value){const end="end"in it.value?it.value.end:undefined;const last=Array.isArray(end)?end[end.length-1]:undefined;if(last?.type==="comment")end?.push(this.sourceToken);else seq.items.push({start:[this.sourceToken]})}else it.start.push(this.sourceToken);return;case"space":case"comment":if(it.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it.start,seq.indent)){const prev=seq.items[seq.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it.start);end.push(this.sourceToken);seq.items.pop();return}}it.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it.value||this.indent<=seq.indent)break;it.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;if(it.value||includesToken(it.start,"seq-item-ind"))seq.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return}if(this.indent>seq.indent){const bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop();yield*this.step()}*flowCollection(fc){const it=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do{yield*this.pop();top=this.peek(1)}while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!it||it.sep)fc.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return;case"map-value-ind":if(!it||it.value)fc.items.push({start:[],key:null,sep:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else Object.assign(it,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!it||it.value)fc.items.push({start:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs=this.flowScalar(this.type);if(!it||it.value)fc.items.push({start:[],key:fs,sep:[]});else if(it.sep)this.stack.push(fs);else Object.assign(it,{key:fs,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}const bv=this.startBlockValue(fc);if(bv)this.stack.push(bv);else{yield*this.pop();yield*this.step()}}else{const parent=this.peek(2);if(parent.type==="block-map"&&(this.type==="map-value-ind"&&parent.indent===fc.indent||this.type==="newline"&&!parent.items[parent.items.length-1].sep)){yield*this.pop();yield*this.step()}else if(this.type==="map-value-ind"&&parent.type!=="flow-collection"){const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);const sep=fc.end.splice(1,fc.end.length);sep.push(this.sourceToken);const map12={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep}]};this.onKeyLine=true;this.stack[this.stack.length-1]=map12}else{yield*this.lineEnd(fc)}}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
155
155
  `)+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf(`
156
- `,nl)+1}}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);start.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:true}]}}case"map-value-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){if(this.type!=="comment")return false;if(this.indent<=indent)return false;return start.every((st)=>st.type==="newline"||st.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(token.end)token.end.push(this.sourceToken);else token.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}exports.Parser=Parser});var require_public_api=__commonJS((exports)=>{var composer=require_composer();var Document=require_Document();var errors=require_errors();var log=require_log();var identity2=require_identity();var lineCounter=require_line_counter();var parser=require_parser2();function parseOptions(options){const prettyErrors=options.prettyErrors!==false;const lineCounter$1=options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null;return{lineCounter:lineCounter$1,prettyErrors}}function parseAllDocuments(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);const docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(const doc of docs){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}if(docs.length>0)return docs;return Object.assign([],{empty:true},composer$1.streamInfo())}function parseDocument(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);let doc=null;for(const _doc of composer$1.compose(parser$1.parse(source),true,source.length)){if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(prettyErrors&&lineCounter2){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}return doc}function parse(src,reviver,options){let _reviver=undefined;if(typeof reviver==="function"){_reviver=reviver}else if(options===undefined&&reviver&&typeof reviver==="object"){options=reviver}const doc=parseDocument(src,options);if(!doc)return null;doc.warnings.forEach((warning)=>log.warn(doc.options.logLevel,warning));if(doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value3,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer)){_replacer=replacer}else if(options===undefined&&replacer){options=replacer}if(typeof options==="string")options=options.length;if(typeof options==="number"){const indent=Math.round(options);options=indent<1?undefined:indent>8?{indent:8}:{indent}}if(value3===undefined){const{keepUndefined}=options??replacer??{};if(!keepUndefined)return}if(identity2.isDocument(value3)&&!_replacer)return value3.toString(options);return new Document.Document(value3,_replacer,options).toString(options)}exports.parse=parse;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify});import{spawn as spawn4}from"node:child_process";import{existsSync as existsSync18,mkdirSync as mkdirSync7,readFileSync as readFileSync19,writeFileSync as writeFileSync8}from"node:fs";import{homedir as homedir3}from"node:os";import path39 from"node:path";import{createInterface as createInterface4}from"node:readline/promises";var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++){ret=args[i](ret)}return ret}}};var Prototype={pipe(){return pipeArguments(this,arguments)}};var Class=function(){function PipeableBase(){}PipeableBase.prototype=Prototype;return PipeableBase}();var dual=function(arity,body){if(typeof arity==="function"){return function(){return arity(arguments)?body.apply(this,arguments):(self)=>body(self,...arguments)}}switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2){return body(a,b)}return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3){return body(a,b,c)}return function(self){return body(self,a,b)}};default:return function(){if(arguments.length>=arity){return body.apply(this,arguments)}const args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value;var constTrue=constant(true);var constFalse=constant(false);var constUndefined=constant(undefined);var constVoid=constUndefined;function pipe(a,...args){return pipeArguments(a,args)}function flow(ab,bc,cd,de,ef,fg,gh,hi,ij){switch(arguments.length){case 1:return ab;case 2:return function(){return bc(ab.apply(this,arguments))};case 3:return function(){return cd(bc(ab.apply(this,arguments)))};case 4:return function(){return de(cd(bc(ab.apply(this,arguments))))};case 5:return function(){return ef(de(cd(bc(ab.apply(this,arguments)))))};case 6:return function(){return fg(ef(de(cd(bc(ab.apply(this,arguments))))))};case 7:return function(){return gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))};case 8:return function(){return hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments))))))))};case 9:return function(){return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))))}}return}function memoize(f){const cache=new WeakMap;return(a)=>{if(cache.has(a)){return cache.get(a)}const result=f(a);cache.set(a,result);return result}}var getAllObjectKeys=(obj)=>{const keys=new Set(Reflect.ownKeys(obj));if(obj.constructor===Object)return keys;if(obj instanceof Error){keys.delete("stack")}const proto=Object.getPrototypeOf(obj);let current=proto;while(current!==null&&current!==Object.prototype){const ownKeys=Reflect.ownKeys(current);for(let i=0;i<ownKeys.length;i++){keys.add(ownKeys[i])}current=Object.getPrototypeOf(current)}if(keys.has("constructor")&&typeof obj.constructor==="function"&&proto===obj.constructor.prototype){keys.delete("constructor")}return keys};var byReferenceInstances=new WeakSet;function isString(input){return typeof input==="string"}function isNumber(input){return typeof input==="number"}function isBoolean(input){return typeof input==="boolean"}function isSymbol(input){return typeof input==="symbol"}function isPropertyKey(u){return isString(u)||isNumber(u)||isSymbol(u)}function isFunction(input){return typeof input==="function"}function isUndefined(input){return input===undefined}function isNotUndefined(input){return input!==undefined}function isNotNull(input){return input!==null}function isNullish(input){return input===null||input===undefined}function isNotNullish(input){return input!=null}function isNever(_){return false}function isUnknown(_){return true}function isObject(input){return typeof input==="object"&&input!==null&&!Array.isArray(input)}function isObjectKeyword(input){return typeof input==="object"&&input!==null||isFunction(input)}var hasProperty=dual(2,(self,property)=>isObjectKeyword(self)&&(property in self));var isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self["_tag"]===tag);function isError(input){return input instanceof Error}function isIterable(input){return hasProperty(input,Symbol.iterator)||isString(input)}var or=dual(2,(self,that)=>(a)=>self(a)||that(a));var symbol="~effect/interfaces/Hash";var hash=(self)=>{switch(typeof self){case"number":return number(self);case"bigint":return string(self.toString(10));case"boolean":return string(String(self));case"symbol":return string(String(self));case"string":return string(self);case"undefined":return string("undefined");case"function":case"object":{if(self===null){return string("null")}else if(self instanceof Date){return string(self.toISOString())}else if(self instanceof RegExp){return string(self.toString())}else{if(byReferenceInstances.has(self)){return random(self)}if(hashCache.has(self)){return hashCache.get(self)}const h=withVisitedTracking(self,()=>{if(isHash(self)){return self[symbol]()}else if(typeof self==="function"){return random(self)}else if(Array.isArray(self)||ArrayBuffer.isView(self)){return array(self)}else if(self instanceof Map){return hashMap(self)}else if(self instanceof Set){return hashSet(self)}return structure(self)});hashCache.set(self,h);return h}}default:throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`)}};var random=(self)=>{if(!randomHashCache.has(self)){randomHashCache.set(self,number(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)))}return randomHashCache.get(self)};var combine=dual(2,(self,b)=>self*53^b);var optimize=(n)=>n&3221225471|n>>>1&1073741824;var isHash=(u)=>hasProperty(u,symbol);var number=(n)=>{if(n!==n){return string("NaN")}if(n===Infinity){return string("Infinity")}if(n===-Infinity){return string("-Infinity")}let h=n|0;if(h!==n){h^=n*4294967295}while(n>4294967295){h^=n/=4294967295}return optimize(h)};var string=(str)=>{let h=5381,i=str.length;while(i){h=h*33^str.charCodeAt(--i)}return optimize(h)};var structureKeys=(o,keys)=>{let h=12289;for(const key of keys){h^=combine(hash(key),hash(o[key]))}return optimize(h)};var structure=(o)=>structureKeys(o,getAllObjectKeys(o));var iterableWith=(seed,f)=>(iter)=>{let h=seed;for(const element of iter){h^=f(element)}return optimize(h)};var array=iterableWith(6151,hash);var hashMap=iterableWith(string("Map"),([k,v])=>combine(hash(k),hash(v)));var hashSet=iterableWith(string("Set"),hash);var randomHashCache=new WeakMap;var hashCache=new WeakMap;var visitedObjects=new WeakSet;function withVisitedTracking(obj,fn){if(visitedObjects.has(obj)){return string("[Circular]")}visitedObjects.add(obj);const result=fn();visitedObjects.delete(obj);return result}var symbol2="~effect/interfaces/Equal";function equals(){if(arguments.length===1){return(self)=>compareBoth(self,arguments[0])}return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return true;if(self==null||that==null)return false;const selfType=typeof self;if(selfType!==typeof that){return false}if(selfType==="number"&&self!==self&&that!==that){return true}if(selfType!=="object"&&selfType!=="function"){return false}if(byReferenceInstances.has(self)||byReferenceInstances.has(that)){return false}return withCache(self,that,compareObjects)}function withVisitedTracking2(self,that,fn){const hasLeft=visitedLeft.has(self);const hasRight=visitedRight.has(that);if(hasLeft&&hasRight){return true}if(hasLeft||hasRight){return false}visitedLeft.add(self);visitedRight.add(that);const result=fn();visitedLeft.delete(self);visitedRight.delete(that);return result}var visitedLeft=new WeakSet;var visitedRight=new WeakSet;function compareObjects(self,that){if(hash(self)!==hash(that)){return false}else if(self instanceof Date){if(!(that instanceof Date))return false;return self.toISOString()===that.toISOString()}else if(self instanceof RegExp){if(!(that instanceof RegExp))return false;return self.toString()===that.toString()}const selfIsEqual=isEqual(self);const thatIsEqual=isEqual(that);if(selfIsEqual!==thatIsEqual)return false;const bothEquals=selfIsEqual&&thatIsEqual;if(typeof self==="function"&&!bothEquals){return false}return withVisitedTracking2(self,that,()=>{if(bothEquals){return self[symbol2](that)}else if(Array.isArray(self)){if(!Array.isArray(that)||self.length!==that.length){return false}return compareArrays(self,that)}else if(ArrayBuffer.isView(self)){if(!ArrayBuffer.isView(that)||self.byteLength!==that.byteLength){return false}return compareTypedArrays(self,that)}else if(self instanceof Map){if(!(that instanceof Map)||self.size!==that.size){return false}return compareMaps(self,that)}else if(self instanceof Set){if(!(that instanceof Set)||self.size!==that.size){return false}return compareSets(self,that)}return compareRecords(self,that)})}function withCache(self,that,f){let selfMap=equalityCache.get(self);if(!selfMap){selfMap=new WeakMap;equalityCache.set(self,selfMap)}else if(selfMap.has(that)){return selfMap.get(that)}const result=f(self,that);selfMap.set(that,result);let thatMap=equalityCache.get(that);if(!thatMap){thatMap=new WeakMap;equalityCache.set(that,thatMap)}thatMap.set(self,result);return result}var equalityCache=new WeakMap;function compareArrays(self,that){for(let i=0;i<self.length;i++){if(!compareBoth(self[i],that[i])){return false}}return true}function compareTypedArrays(self,that){if(self.length!==that.length){return false}for(let i=0;i<self.length;i++){if(self[i]!==that[i]){return false}}return true}function compareRecords(self,that){const selfKeys=getAllObjectKeys(self);const thatKeys=getAllObjectKeys(that);if(selfKeys.size!==thatKeys.size){return false}for(const key of selfKeys){if(!thatKeys.has(key)||!compareBoth(self[key],that[key])){return false}}return true}function makeCompareMap(keyEquivalence,valueEquivalence){return function compareMaps(self,that){for(const[selfKey,selfValue]of self){let found=false;for(const[thatKey,thatValue]of that){if(keyEquivalence(selfKey,thatKey)&&valueEquivalence(selfValue,thatValue)){found=true;break}}if(!found){return false}}return true}}var compareMaps=makeCompareMap(compareBoth,compareBoth);function makeCompareSet(equivalence){return function compareSets(self,that){for(const selfValue of self){let found=false;for(const thatValue of that){if(equivalence(selfValue,thatValue)){found=true;break}}if(!found){return false}}return true}}var compareSets=makeCompareSet(compareBoth);var isEqual=(u)=>hasProperty(u,symbol2);var asEquivalence=()=>equals;var symbolRedactable=Symbol.for("~effect/Redactable");var isRedactable=(u)=>hasProperty(u,symbolRedactable);function redact(u){if(isRedactable(u))return getRedacted(u);return u}function getRedacted(redactable){return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context??emptyContext)}var currentFiberTypeId="~effect/Fiber/currentFiber";var emptyContext={"~effect/Context":{},mapUnsafe:new Map,pipe(){return pipeArguments(this,arguments)}};function format(input,options){const space=options?.space??0;const seen=new WeakSet;const gap=!space?"":typeof space==="number"?" ".repeat(space):space;const ind=(d)=>gap.repeat(d);const wrap=(v,body)=>{const ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body};const ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function recur(v,d=0){if(Array.isArray(v)){if(seen.has(v))return CIRCULAR;seen.add(v);if(!gap||v.length<=1)return`[${v.map((x)=>recur(x,d)).join(",")}]`;const inner=v.map((x)=>recur(x,d+1)).join(`,
156
+ `,nl)+1}}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);start.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:true}]}}case"map-value-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){if(this.type!=="comment")return false;if(this.indent<=indent)return false;return start.every((st)=>st.type==="newline"||st.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(token.end)token.end.push(this.sourceToken);else token.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}exports.Parser=Parser});var require_public_api=__commonJS((exports)=>{var composer=require_composer();var Document=require_Document();var errors=require_errors();var log=require_log();var identity2=require_identity();var lineCounter=require_line_counter();var parser=require_parser2();function parseOptions(options){const prettyErrors=options.prettyErrors!==false;const lineCounter$1=options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null;return{lineCounter:lineCounter$1,prettyErrors}}function parseAllDocuments(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);const docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(const doc of docs){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}if(docs.length>0)return docs;return Object.assign([],{empty:true},composer$1.streamInfo())}function parseDocument(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);let doc=null;for(const _doc of composer$1.compose(parser$1.parse(source),true,source.length)){if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(prettyErrors&&lineCounter2){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}return doc}function parse(src,reviver,options){let _reviver=undefined;if(typeof reviver==="function"){_reviver=reviver}else if(options===undefined&&reviver&&typeof reviver==="object"){options=reviver}const doc=parseDocument(src,options);if(!doc)return null;doc.warnings.forEach((warning)=>log.warn(doc.options.logLevel,warning));if(doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value3,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer)){_replacer=replacer}else if(options===undefined&&replacer){options=replacer}if(typeof options==="string")options=options.length;if(typeof options==="number"){const indent=Math.round(options);options=indent<1?undefined:indent>8?{indent:8}:{indent}}if(value3===undefined){const{keepUndefined}=options??replacer??{};if(!keepUndefined)return}if(identity2.isDocument(value3)&&!_replacer)return value3.toString(options);return new Document.Document(value3,_replacer,options).toString(options)}exports.parse=parse;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify});import{spawn as spawn4}from"node:child_process";import{existsSync as existsSync19,mkdirSync as mkdirSync7,readFileSync as readFileSync19,writeFileSync as writeFileSync8}from"node:fs";import{homedir as homedir3}from"node:os";import path39 from"node:path";import{createInterface as createInterface4}from"node:readline/promises";var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++){ret=args[i](ret)}return ret}}};var Prototype={pipe(){return pipeArguments(this,arguments)}};var Class=function(){function PipeableBase(){}PipeableBase.prototype=Prototype;return PipeableBase}();var dual=function(arity,body){if(typeof arity==="function"){return function(){return arity(arguments)?body.apply(this,arguments):(self)=>body(self,...arguments)}}switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2){return body(a,b)}return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3){return body(a,b,c)}return function(self){return body(self,a,b)}};default:return function(){if(arguments.length>=arity){return body.apply(this,arguments)}const args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value;var constTrue=constant(true);var constFalse=constant(false);var constUndefined=constant(undefined);var constVoid=constUndefined;function pipe(a,...args){return pipeArguments(a,args)}function flow(ab,bc,cd,de,ef,fg,gh,hi,ij){switch(arguments.length){case 1:return ab;case 2:return function(){return bc(ab.apply(this,arguments))};case 3:return function(){return cd(bc(ab.apply(this,arguments)))};case 4:return function(){return de(cd(bc(ab.apply(this,arguments))))};case 5:return function(){return ef(de(cd(bc(ab.apply(this,arguments)))))};case 6:return function(){return fg(ef(de(cd(bc(ab.apply(this,arguments))))))};case 7:return function(){return gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))};case 8:return function(){return hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments))))))))};case 9:return function(){return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))))}}return}function memoize(f){const cache=new WeakMap;return(a)=>{if(cache.has(a)){return cache.get(a)}const result=f(a);cache.set(a,result);return result}}var getAllObjectKeys=(obj)=>{const keys=new Set(Reflect.ownKeys(obj));if(obj.constructor===Object)return keys;if(obj instanceof Error){keys.delete("stack")}const proto=Object.getPrototypeOf(obj);let current=proto;while(current!==null&&current!==Object.prototype){const ownKeys=Reflect.ownKeys(current);for(let i=0;i<ownKeys.length;i++){keys.add(ownKeys[i])}current=Object.getPrototypeOf(current)}if(keys.has("constructor")&&typeof obj.constructor==="function"&&proto===obj.constructor.prototype){keys.delete("constructor")}return keys};var byReferenceInstances=new WeakSet;function isString(input){return typeof input==="string"}function isNumber(input){return typeof input==="number"}function isBoolean(input){return typeof input==="boolean"}function isSymbol(input){return typeof input==="symbol"}function isPropertyKey(u){return isString(u)||isNumber(u)||isSymbol(u)}function isFunction(input){return typeof input==="function"}function isUndefined(input){return input===undefined}function isNotUndefined(input){return input!==undefined}function isNotNull(input){return input!==null}function isNullish(input){return input===null||input===undefined}function isNotNullish(input){return input!=null}function isNever(_){return false}function isUnknown(_){return true}function isObject(input){return typeof input==="object"&&input!==null&&!Array.isArray(input)}function isObjectKeyword(input){return typeof input==="object"&&input!==null||isFunction(input)}var hasProperty=dual(2,(self,property)=>isObjectKeyword(self)&&(property in self));var isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self["_tag"]===tag);function isError(input){return input instanceof Error}function isIterable(input){return hasProperty(input,Symbol.iterator)||isString(input)}var or=dual(2,(self,that)=>(a)=>self(a)||that(a));var symbol="~effect/interfaces/Hash";var hash=(self)=>{switch(typeof self){case"number":return number(self);case"bigint":return string(self.toString(10));case"boolean":return string(String(self));case"symbol":return string(String(self));case"string":return string(self);case"undefined":return string("undefined");case"function":case"object":{if(self===null){return string("null")}else if(self instanceof Date){return string(self.toISOString())}else if(self instanceof RegExp){return string(self.toString())}else{if(byReferenceInstances.has(self)){return random(self)}if(hashCache.has(self)){return hashCache.get(self)}const h=withVisitedTracking(self,()=>{if(isHash(self)){return self[symbol]()}else if(typeof self==="function"){return random(self)}else if(Array.isArray(self)||ArrayBuffer.isView(self)){return array(self)}else if(self instanceof Map){return hashMap(self)}else if(self instanceof Set){return hashSet(self)}return structure(self)});hashCache.set(self,h);return h}}default:throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`)}};var random=(self)=>{if(!randomHashCache.has(self)){randomHashCache.set(self,number(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)))}return randomHashCache.get(self)};var combine=dual(2,(self,b)=>self*53^b);var optimize=(n)=>n&3221225471|n>>>1&1073741824;var isHash=(u)=>hasProperty(u,symbol);var number=(n)=>{if(n!==n){return string("NaN")}if(n===Infinity){return string("Infinity")}if(n===-Infinity){return string("-Infinity")}let h=n|0;if(h!==n){h^=n*4294967295}while(n>4294967295){h^=n/=4294967295}return optimize(h)};var string=(str)=>{let h=5381,i=str.length;while(i){h=h*33^str.charCodeAt(--i)}return optimize(h)};var structureKeys=(o,keys)=>{let h=12289;for(const key of keys){h^=combine(hash(key),hash(o[key]))}return optimize(h)};var structure=(o)=>structureKeys(o,getAllObjectKeys(o));var iterableWith=(seed,f)=>(iter)=>{let h=seed;for(const element of iter){h^=f(element)}return optimize(h)};var array=iterableWith(6151,hash);var hashMap=iterableWith(string("Map"),([k,v])=>combine(hash(k),hash(v)));var hashSet=iterableWith(string("Set"),hash);var randomHashCache=new WeakMap;var hashCache=new WeakMap;var visitedObjects=new WeakSet;function withVisitedTracking(obj,fn){if(visitedObjects.has(obj)){return string("[Circular]")}visitedObjects.add(obj);const result=fn();visitedObjects.delete(obj);return result}var symbol2="~effect/interfaces/Equal";function equals(){if(arguments.length===1){return(self)=>compareBoth(self,arguments[0])}return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return true;if(self==null||that==null)return false;const selfType=typeof self;if(selfType!==typeof that){return false}if(selfType==="number"&&self!==self&&that!==that){return true}if(selfType!=="object"&&selfType!=="function"){return false}if(byReferenceInstances.has(self)||byReferenceInstances.has(that)){return false}return withCache(self,that,compareObjects)}function withVisitedTracking2(self,that,fn){const hasLeft=visitedLeft.has(self);const hasRight=visitedRight.has(that);if(hasLeft&&hasRight){return true}if(hasLeft||hasRight){return false}visitedLeft.add(self);visitedRight.add(that);const result=fn();visitedLeft.delete(self);visitedRight.delete(that);return result}var visitedLeft=new WeakSet;var visitedRight=new WeakSet;function compareObjects(self,that){if(hash(self)!==hash(that)){return false}else if(self instanceof Date){if(!(that instanceof Date))return false;return self.toISOString()===that.toISOString()}else if(self instanceof RegExp){if(!(that instanceof RegExp))return false;return self.toString()===that.toString()}const selfIsEqual=isEqual(self);const thatIsEqual=isEqual(that);if(selfIsEqual!==thatIsEqual)return false;const bothEquals=selfIsEqual&&thatIsEqual;if(typeof self==="function"&&!bothEquals){return false}return withVisitedTracking2(self,that,()=>{if(bothEquals){return self[symbol2](that)}else if(Array.isArray(self)){if(!Array.isArray(that)||self.length!==that.length){return false}return compareArrays(self,that)}else if(ArrayBuffer.isView(self)){if(!ArrayBuffer.isView(that)||self.byteLength!==that.byteLength){return false}return compareTypedArrays(self,that)}else if(self instanceof Map){if(!(that instanceof Map)||self.size!==that.size){return false}return compareMaps(self,that)}else if(self instanceof Set){if(!(that instanceof Set)||self.size!==that.size){return false}return compareSets(self,that)}return compareRecords(self,that)})}function withCache(self,that,f){let selfMap=equalityCache.get(self);if(!selfMap){selfMap=new WeakMap;equalityCache.set(self,selfMap)}else if(selfMap.has(that)){return selfMap.get(that)}const result=f(self,that);selfMap.set(that,result);let thatMap=equalityCache.get(that);if(!thatMap){thatMap=new WeakMap;equalityCache.set(that,thatMap)}thatMap.set(self,result);return result}var equalityCache=new WeakMap;function compareArrays(self,that){for(let i=0;i<self.length;i++){if(!compareBoth(self[i],that[i])){return false}}return true}function compareTypedArrays(self,that){if(self.length!==that.length){return false}for(let i=0;i<self.length;i++){if(self[i]!==that[i]){return false}}return true}function compareRecords(self,that){const selfKeys=getAllObjectKeys(self);const thatKeys=getAllObjectKeys(that);if(selfKeys.size!==thatKeys.size){return false}for(const key of selfKeys){if(!thatKeys.has(key)||!compareBoth(self[key],that[key])){return false}}return true}function makeCompareMap(keyEquivalence,valueEquivalence){return function compareMaps(self,that){for(const[selfKey,selfValue]of self){let found=false;for(const[thatKey,thatValue]of that){if(keyEquivalence(selfKey,thatKey)&&valueEquivalence(selfValue,thatValue)){found=true;break}}if(!found){return false}}return true}}var compareMaps=makeCompareMap(compareBoth,compareBoth);function makeCompareSet(equivalence){return function compareSets(self,that){for(const selfValue of self){let found=false;for(const thatValue of that){if(equivalence(selfValue,thatValue)){found=true;break}}if(!found){return false}}return true}}var compareSets=makeCompareSet(compareBoth);var isEqual=(u)=>hasProperty(u,symbol2);var asEquivalence=()=>equals;var symbolRedactable=Symbol.for("~effect/Redactable");var isRedactable=(u)=>hasProperty(u,symbolRedactable);function redact(u){if(isRedactable(u))return getRedacted(u);return u}function getRedacted(redactable){return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context??emptyContext)}var currentFiberTypeId="~effect/Fiber/currentFiber";var emptyContext={"~effect/Context":{},mapUnsafe:new Map,pipe(){return pipeArguments(this,arguments)}};function format(input,options){const space=options?.space??0;const seen=new WeakSet;const gap=!space?"":typeof space==="number"?" ".repeat(space):space;const ind=(d)=>gap.repeat(d);const wrap=(v,body)=>{const ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body};const ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function recur(v,d=0){if(Array.isArray(v)){if(seen.has(v))return CIRCULAR;seen.add(v);if(!gap||v.length<=1)return`[${v.map((x)=>recur(x,d)).join(",")}]`;const inner=v.map((x)=>recur(x,d+1)).join(`,
157
157
  `+ind(d+1));return`[
158
158
  ${ind(d+1)}${inner}
159
159
  ${ind(d)}]`}if(v instanceof Date)return formatDate(v);if(!options?.ignoreToString&&hasProperty(v,"toString")&&typeof v["toString"]==="function"&&v["toString"]!==Object.prototype.toString&&v["toString"]!==Array.prototype.toString){const s=safeToString(v);if(v instanceof Error&&v.cause){return`${s} (cause: ${recur(v.cause,d)})`}return s}if(typeof v==="string")return JSON.stringify(v);if(typeof v==="number"||v==null||typeof v==="boolean"||typeof v==="symbol")return String(v);if(typeof v==="bigint")return String(v)+"n";if(typeof v==="object"||typeof v==="function"){if(seen.has(v))return CIRCULAR;seen.add(v);if(symbolRedactable in v)return format(getRedacted(v));if(Symbol.iterator in v){return`${v.constructor.name}(${recur(Array.from(v),d)})`}const keys=ownKeys(v);if(!gap||keys.length<=1){const body2=`{${keys.map((k)=>`${formatPropertyKey(k)}:${recur(v[k],d)}`).join(",")}}`;return wrap(v,body2)}const body=`{
@@ -176,7 +176,7 @@ ${renderErrorCause(e.cause," ")}
176
176
  `);let stack=`${prefix}[cause]: ${lines[0]}`;for(let i=1,len=lines.length;i<len;i++){stack+=`
177
177
  ${prefix}${lines[i]}`}if(cause.cause){stack+=` {
178
178
  ${renderErrorCause(cause.cause,`${prefix} `)}
179
- ${prefix}}`}return stack};var FiberTypeId=`~effect/Fiber/${version}`;var fiberVariance={_A:identity,_E:identity};var fiberIdStore={id:0};var getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=true){this[FiberTypeId]=fiberVariance;this.setContext(context);this.id=++fiberIdStore.id;this.currentOpCount=0;this.interruptible=interruptible;this._stack=[];this._observers=[];this._exit=undefined;this._children=undefined;this._interruptedCause=undefined;this._yielded=undefined;this._running=false;this._deferredInterrupt=false;this.runtimeMetrics?.recordFiberStart(this.context)}[FiberTypeId];id;interruptible;currentOpCount;_stack;_observers;_exit;_children;_interruptedCause;_yielded;_running;_deferredInterrupt;context;currentScheduler;currentTracerContext;currentSpan;currentLogLevel;minimumLogLevel;currentStackFrame;runtimeMetrics;maxOpsBeforeYield;currentPreventYield;_dispatcher=undefined;get currentDispatcher(){return this._dispatcher??=this.currentScheduler.makeDispatcher()}getRef(ref){return getReferenceUnsafe(this.context,ref)}addObserver(cb){if(this._exit){cb(this._exit);return constVoid}this._observers.push(cb);return()=>{const index=this._observers.indexOf(cb);if(index>=0){this._observers.splice(index,1)}}}interruptUnsafe(fiberId,annotations){if(this._exit){return}let cause=causeInterrupt(fiberId);if(this.currentStackFrame){cause=causeAnnotate(cause,make3(StackTraceKey,this.currentStackFrame))}if(annotations){cause=causeAnnotate(cause,annotations)}this._interruptedCause=this._interruptedCause?causeCombine(this._interruptedCause,cause):cause;if(this.interruptible){if(this._running){this._deferredInterrupt=true}else{this.evaluate(failCause(this._interruptedCause))}}}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit){return}else if(this._yielded!==undefined){const yielded=this._yielded;this._yielded=undefined;yielded()}const exit=this.runLoop(effect);if(exit===Yield){return}const interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==undefined){return this.evaluate(flatMap2(interruptChildren,()=>exit))}this._exit=exit;this.runtimeMetrics?.recordFiberEnd(this.context,this._exit);for(let i=0;i<this._observers.length;i++){this._observers[i](exit)}this._observers.length=0;this._stack.length=0;this._children=undefined;this.context=empty()}runLoop(effect){const prevFiber=globalThis[currentFiberTypeId];globalThis[currentFiberTypeId]=this;const prevRunning=this._running;this._running=true;let yielding=false;let current=effect;this.currentOpCount=0;try{while(true){if(this._deferredInterrupt){this._deferredInterrupt=false;current=failCause(this._interruptedCause)}this.currentOpCount++;if(!yielding&&!this.currentPreventYield&&this.currentScheduler.shouldYield(this)){yielding=true;const prev=current;current=flatMap2(yieldNow,()=>prev)}current=this.currentTracerContext?this.currentTracerContext(current,this):current[evaluate](this);if(current===Yield){const yielded=this._yielded;if(ExitTypeId in yielded){this._deferredInterrupt=false;this._yielded=undefined;return yielded}else if(this._deferredInterrupt){this._yielded=undefined;yielded();continue}return Yield}}}catch(error){if(!hasProperty(current,evaluate)){return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`)}return this.runLoop(exitDie(error))}finally{this._running=prevRunning;globalThis[currentFiberTypeId]=prevFiber}}getCont(symbol3){if(this._deferredInterrupt){this._deferredInterrupt=false;return deferredInterruptCont}while(true){const op=this._stack.pop();if(!op)return;const cont=op[contAll]&&op[contAll](this);if(cont){cont[symbol3]=cont;return cont}if(op[symbol3])return op}}yieldWith(value){this._yielded=value;return Yield}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){this.context=context;const scheduler=this.getRef(Scheduler);if(scheduler!==this.currentScheduler){this.currentScheduler=scheduler;this._dispatcher=undefined}this.currentSpan=context.mapUnsafe.get(ParentSpanKey);this.currentLogLevel=this.getRef(CurrentLogLevel);this.minimumLogLevel=this.getRef(MinimumLogLevel);this.currentStackFrame=context.mapUnsafe.get(CurrentStackFrame.key);this.maxOpsBeforeYield=this.getRef(MaxOpsBeforeYield);this.currentPreventYield=this.getRef(PreventSchedulerYield);this.runtimeMetrics=context.mapUnsafe.get(FiberRuntimeMetricsKey);const currentTracer=context.mapUnsafe.get(TracerKey);this.currentTracerContext=currentTracer?currentTracer["context"]:undefined}get currentSpanLocal(){return this.currentSpan?._tag==="Span"?this.currentSpan:undefined}}var deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}};var fiberMiddleware={interruptChildren:undefined};var fiberStackAnnotations=(fiber)=>{if(!fiber.currentStackFrame)return;const annotations=new Map;annotations.set(InterruptorStackTrace.key,fiber.currentStackFrame);return makeUnsafe(annotations)};var fiberAwait=(self)=>{const impl=self;if(impl._exit)return succeed3(impl._exit);return callback((resume)=>{if(impl._exit)return resume(succeed3(impl._exit));return sync(self.addObserver((exit)=>resume(succeed3(exit))))})};var fiberAwaitAll=(self)=>callback((resume)=>{const iter=self[Symbol.iterator]();const exits=[];let cancel=undefined;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit);result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit);loop()});return}resume(succeed3(exits))}loop();return sync(()=>cancel?.())});var fiberInterrupt=(self)=>withFiber((fiber)=>fiberInterruptAs(self,fiber.id));var fiberInterruptAs=dual((args2)=>hasProperty(args2[0],FiberTypeId),(self,fiberId,annotations)=>withFiber((parent)=>{let ann=fiberStackAnnotations(parent);ann=ann&&annotations?merge(ann,annotations):ann??annotations;self.interruptUnsafe(fiberId,ann);return asVoid(fiberAwait(self))}));var fiberInterruptAll=(fibers)=>withFiber((parent)=>{const annotations=fiberStackAnnotations(parent);let fiberArr=empty3();for(const fiber of fibers){fiber.interruptUnsafe(parent.id,annotations);fiberArr.push(fiber)}return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed;var failCause=exitFailCause;var fail3=exitFail;var sync=makePrimitive({op:"Sync",[evaluate](fiber){const value=this[args]();const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){return this[args]()}});var fromResult=match3({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){let resumed=false;fiber.currentDispatcher.scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid)},this[args]??0);return fiber.yieldWith(()=>{resumed=true})}});var yieldNow=yieldNowWith(0);var succeedSome=(a)=>succeed3(some2(a));var succeedNone=succeed3(none2());var failCauseSync=(evaluate2)=>suspend(()=>failCause(internalCall(evaluate2)));var die=(defect)=>exitDie(defect);var failSync=(error)=>suspend(()=>fail3(internalCall(error)));var void_=succeed3(undefined);var try_2=(options)=>{const evaluate2=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(internalCall(evaluate2))}catch(err){return fail3(internalCall(()=>catcher(err)))}})};var promise=(evaluate2)=>callbackOptions(function(resume,signal){internalCall(()=>evaluate2(signal)).then((a)=>resume(succeed3(a)),(e)=>resume(die(e)))},evaluate2.length!==0);var tryPromise=(options)=>{const f=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){const failWithCatch=(cause)=>{try{resume(fail3(internalCall(()=>catcher(cause))))}catch(err){resume(die(err))}};try{internalCall(()=>f(signal)).then((a)=>resume(succeed3(a)),failWithCatch)}catch(err){failWithCatch(err)}},f.length!==0)};var withFiberId=(f)=>withFiber((fiber)=>f(fiber.id));var callbackOptions=makePrimitive({op:"Async",single:false,[evaluate](fiber){const register=internalCall(()=>this[args][0].bind(fiber.currentScheduler));let resumed=false;let yielded=false;const controller=this[args][1]?new AbortController:undefined;const onCancel=register((effect)=>{if(resumed)return;resumed=true;if(yielded){fiber.evaluate(effect)}else{yielded=effect}},controller?.signal);if(yielded!==false)return yielded;yielded=true;fiber._yielded=()=>{resumed=true};if(controller===undefined&&onCancel===undefined){return Yield}fiber._stack.push(asyncFinalizer(()=>{resumed=true;controller?.abort();return onCancel??exitVoid}));return Yield}});var asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible){fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue)}},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap2(this[args](),()=>failCause(cause)):failCause(cause)}});var callback=(register)=>callbackOptions(register,register.length>=2);var never=callback(constVoid);var gen=(...args2)=>suspend(()=>fromIteratorUnsafe(args2.length===1?args2[0]():args2[1].call(args2[0].self)));var fnUntraced=(body,...pipeables)=>{const fn=pipeables.length===0?function(){return suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)))}:function(){let effect=suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)));for(let i=0;i<pipeables.length;i++){effect=pipeables[i](effect,...arguments)}return effect};return defineFunctionLength(body.length,fn)};var defineFunctionLength=(length,fn)=>Object.defineProperty(fn,"length",{value:length,configurable:true});var fnStackCleaner=makeStackCleaner(2);var fn=function(){const nameFirst=typeof arguments[0]==="string";const name=nameFirst?arguments[0]:"Effect.fn";const spanOptions=nameFirst?arguments[1]:undefined;const prevLimit=getStackTraceLimit();setStackTraceLimit(2);const defError=new globalThis.Error;setStackTraceLimit(prevLimit);if(nameFirst){return(body,...pipeables)=>makeFn(name,body,defError,pipeables,nameFirst,spanOptions)}return makeFn(name,arguments[0],defError,Array.prototype.slice.call(arguments,1),nameFirst,spanOptions)};var makeFn=(name,bodyOrOptions,defError,pipeables,addSpan,spanOptions)=>{const body=typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.pop().bind(bodyOrOptions.self);return defineFunctionLength(body.length,function(...args2){let result=suspend(()=>{const iter=body.apply(this,arguments);return isEffect(iter)?iter:fromIteratorUnsafe(iter)});for(let i=0;i<pipeables.length;i++){result=pipeables[i](result,...args2)}if(!isEffect(result)){return result}const prevLimit=getStackTraceLimit();setStackTraceLimit(2);const callError=new globalThis.Error;setStackTraceLimit(prevLimit);return updateService(addSpan?useSpan(name,spanOptions,(span)=>provideParentSpan(result,span)):result,CurrentStackFrame,(prev)=>({name,stack:fnStackCleaner(()=>callError.stack),parent:{name:`${name} (definition)`,stack:fnStackCleaner(()=>defError.stack),parent:prev}}))})};var fnUntracedEager=(body,...pipeables)=>defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(const pipeable of pipeables){effect=pipeable(effect)}return effect});var fromIteratorEagerUnsafe=(evaluate2)=>{try{const iterator=evaluate2();let value=undefined;while(true){const state=iterator.next(value);if(state.done){return succeed3(state.value)}const primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure"){return state.value}else{let isFirstExecution=true;return suspend(()=>{if(isFirstExecution){isFirstExecution=false;return flatMap2(state.value,(value2)=>fromIteratorUnsafe(iterator,value2))}else{return suspend(()=>fromIteratorUnsafe(evaluate2()))}})}}}catch(error){return die(error)}};var fromIteratorUnsafe=makePrimitive({op:"Iterator",single:false,[contA](value,fiber){const iter=this[args][0];while(true){const state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value)){fiber._stack.push(this);return state.value}else if(state.value._tag==="Failure"){return state.value}value=state.value.value}},[evaluate](fiber){return this[contA](this[args][1],fiber)}});var as=dual(2,(self,value)=>{const b=succeed3(value);return flatMap2(self,(_)=>b)});var asSome=(self)=>map4(self,some2);var andThen=dual(2,(self,f)=>flatMap2(self,(a)=>isEffect(f)?f:internalCall(()=>f(a))));var tap=dual(2,(self,f)=>flatMap2(self,(a)=>as(isEffect(f)?f:internalCall(()=>f(a)),a)));var asVoid=(self)=>flatMap2(self,(_)=>exitVoid);var raceAllFirst=(all,options)=>withFiber((parent)=>callback((resume)=>{let done2=false;const fibers=new Set;const onExit=(exit)=>{done2=true;resume(fibers.size===0?exit:flatMap2(uninterruptible(fiberInterruptAll(fibers)),()=>exit))};let i=0;for(const effect of all){if(done2)break;const index=i++;const fiber=forkUnsafe(parent,effect,true,true,false);fibers.add(fiber);fiber.addObserver((exit)=>{fibers.delete(fiber);const isWinner=!done2;onExit(exit);if(isWinner&&options?.onWinner){options.onWinner({fiber,index,parentFiber:parent})}})}return fiberInterruptAll(fibers)}));var raceFirst=dual((args2)=>isEffect(args2[1]),(self,that,options)=>raceAllFirst([self,that],options));var flatMap2=dual(2,(self,f)=>{const onSuccess=Object.create(OnSuccessProto);onSuccess[args]=self;onSuccess[contA]=f.length!==1?(a)=>f(a):f;return onSuccess});var OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var effectIsExit=(effect)=>(ExitTypeId in effect);var flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self)){return self._tag==="Success"?f(self.value):self}return flatMap2(self,f)});var map4=dual(2,(self,f)=>flatMap2(self,(a)=>succeed3(internalCall(()=>f(a)))));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map4(self,f));var mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError2(self,f));var mapBothEager=dual(2,(self,options)=>effectIsExit(self)?exitMapBoth(self,options):mapBoth(self,options));var exitInterrupt=(fiberId)=>exitFailCause(causeInterrupt(fiberId));var exitIsSuccess=(self)=>self._tag==="Success";var exitFilterCause=(self)=>self._tag==="Failure"?succeed2(self.cause):fail2(self);var exitVoid=exitSucceed(undefined);var exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self);var exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(f(error.success))});var exitMapBoth=dual(2,(self,options)=>{if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(options.onFailure(error.success))});var exitZipRight=dual(2,(self,that)=>exitIsSuccess(self)?that:self);var exitAsVoidAll=(exits)=>{const failures=[];for(const exit of exits){if(exit._tag==="Failure"){failures.push(...exit.cause.reasons)}}return failures.length===0?exitVoid:exitFailCause(causeFromReasons(failures))};var serviceOption=(service)=>withFiber((fiber)=>succeed3(getOption(fiber.context,service)));var updateContext=dual(2,(self,f)=>withFiber((fiber)=>{const prevContext=fiber.context;const nextContext=f(prevContext);if(prevContext===nextContext)return self;fiber.setContext(nextContext);return onExitPrimitive(self,()=>{fiber.setContext(prevContext);return})}));var updateService=dual(3,(self,service,f)=>updateContext(self,(s)=>{const prev=getUnsafe(s,service);const next=f(prev);if(prev===next)return s;return add(s,service,next)}));var context=()=>getContext;var getContext=withFiber((fiber)=>succeed3(fiber.context));var contextWith=(f)=>withFiber((fiber)=>f(fiber.context));var provideContext=dual(2,(self,context2)=>{if(effectIsExit(self))return self;return updateContext(self,merge(context2))});var provideService=function(){if(arguments.length===1){return dual(2,(self,impl)=>provideServiceImpl(self,arguments[0],impl))}return dual(3,(self,service,impl)=>provideServiceImpl(self,service,impl)).apply(this,arguments)};var provideServiceImpl=(self,service,implementation)=>updateContext(self,(s)=>{const prev=s.mapUnsafe.get(service.key);if(prev===implementation)return s;return add(s,service,implementation)});var provideServiceEffect=dual(3,(self,service,acquire)=>flatMap2(acquire,(implementation)=>provideService(self,service,implementation)));var zipWith=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>options?.concurrent?map4(all([self,that],{concurrency:2}),([a,a2])=>internalCall(()=>f(a,a2))):flatMap2(self,(a)=>map4(that,(a2)=>internalCall(()=>f(a,a2)))));var filterOrFail=dual((args2)=>isEffect(args2[0]),(self,predicate,orFailWith)=>filterOrElse(self,predicate,orFailWith?(a)=>fail3(orFailWith(a)):()=>fail3(new NoSuchElementError)));var forever=dual((args2)=>isEffect(args2[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap2(self,(_)=>yieldNow)),step:constVoid}));var catchCause=dual(2,(self,f)=>{const onFailure=Object.create(OnFailureProto);onFailure[args]=self;onFailure[contE]=f.length!==1?(cause)=>f(cause):f;return onFailure});var OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var catchCauseFilter=dual(3,(self,filter4,f)=>catchCause(self,(cause)=>{const eb=filter4(cause);return isFailure2(eb)?failCause(eb.failure):internalCall(()=>f(eb.success,cause))}));var catch_=dual(2,(self,f)=>catchCauseFilter(self,findError,(e)=>f(e)));var tapCause=dual(2,(self,f)=>catchCause(self,(cause)=>andThen(internalCall(()=>f(cause)),failCause(cause))));var tapCauseFilter=dual(3,(self,filter4,f)=>catchCause(self,(cause)=>{const result=filter4(cause);if(isFailure2(result)){return failCause(cause)}return andThen(internalCall(()=>f(result.success,cause)),failCause(cause))}));var tapError=dual(2,(self,f)=>tapCauseFilter(self,findError,(e)=>f(e)));var catchIf=dual((args2)=>isEffect(args2[0]),(self,predicate,f,orElse)=>catchCause(self,(cause)=>{const error=findError(cause);if(isFailure2(error))return failCause(error.failure);if(!predicate(error.success)){return orElse?internalCall(()=>orElse(error.success)):failCause(cause)}return internalCall(()=>f(error.success))}));var catchFilter=dual((args2)=>isEffect(args2[0]),(self,filter4,f,orElse)=>catchCause(self,(cause)=>{const error=findError(cause);if(isFailure2(error))return failCause(error.failure);const result=filter4(error.success);if(isFailure2(result)){return orElse?internalCall(()=>orElse(result.failure)):failCause(cause)}return internalCall(()=>f(result.success))}));var catchTag=dual((args2)=>isEffect(args2[0]),(self,k,f,orElse)=>{const pred=Array.isArray(k)?(e)=>hasProperty(e,"_tag")&&k.includes(e._tag):isTagged(k);return catchIf(self,pred,f,orElse)});var catchTags=dual((args2)=>isEffect(args2[0]),(self,cases,orElse)=>{let keys2;return catchFilter(self,(e)=>{keys2??=Object.keys(cases);return hasProperty(e,"_tag")&&isString(e["_tag"])&&keys2.includes(e["_tag"])?succeed2(e):fail2(e)},(e)=>internalCall(()=>cases[e["_tag"]](e)),orElse)});var mapError2=dual(2,(self,f)=>catch_(self,(error)=>failSync(()=>f(error))));var mapBoth=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>failSync(()=>options.onFailure(e)),onSuccess:(a)=>sync(()=>options.onSuccess(a))}));var orDie=(self)=>catch_(self,die);var ignore=dual((args2)=>isEffect(args2[0]),(self,options)=>{if(!options?.log){return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_})}const logEffect=logWithLevel(options.log===true?undefined:options.log);return matchCauseEffect(self,{onFailure(cause){const failure=findFail(cause);return isFailure2(failure)?failCause(failure.failure):options.message===undefined?logEffect(cause):logEffect(options.message,cause)},onSuccess:(_)=>void_})});var result=(self)=>matchEager(self,{onFailure:fail2,onSuccess:succeed2});var matchCauseEffect=dual(2,(self,options)=>{const primitive=Object.create(OnSuccessAndFailureProto);primitive[args]=self;primitive[contA]=options.onSuccess.length!==1?(a)=>options.onSuccess(a):options.onSuccess;primitive[contE]=options.onFailure.length!==1?(cause)=>options.onFailure(cause):options.onFailure;return primitive});var OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{const fail4=cause.reasons.find(isFailReason);return fail4?internalCall(()=>options.onFailure(fail4.error)):failCause(cause)},onSuccess:options.onSuccess}));var match5=dual(2,(self,options)=>matchEffect(self,{onFailure:(error)=>sync(()=>options.onFailure(error)),onSuccess:(value)=>sync(()=>options.onSuccess(value))}));var matchEager=dual(2,(self,options)=>{if(effectIsExit(self)){if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitSucceed(options.onFailure(error.success))}return match5(self,options)});var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self);var exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){fiber._stack.push(this);return this[args]},[contA](value,_,exit2){return succeed3(exit2??exitSucceed(value))},[contE](cause,_,exit2){return succeed3(exit2??exitFailCause(cause))}});var delay=dual(2,(self,duration)=>andThen(sleep(duration),self));var timeoutOrElse=dual(2,(self,options)=>raceFirst(self,flatMap2(sleep(options.duration),options.orElse)));var timeout=dual(2,(self,duration)=>timeoutOrElse(self,{duration,orElse:()=>fail3(new TimeoutError)}));var ScopeTypeId="~effect/Scope";var ScopeCloseableTypeId="~effect/Scope/Closeable";var scopeTag=Service("effect/Scope");var scopeClose=(self,exit_)=>suspend(()=>scopeCloseUnsafe(self,exit_)??void_);var scopeCloseUnsafe=(self,exit_)=>{if(self.state._tag==="Closed")return;const closed={_tag:"Closed",exit:exit_};if(self.state._tag==="Empty"){self.state=closed;return}const{finalizers}=self.state;self.state=closed;if(finalizers.size===0){return}else if(finalizers.size===1){return finalizers.values().next().value(exit_)}return scopeCloseFinalizers(self,finalizers,exit_)};var scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[];const fibers=[];const arr=Array.from(finalizers.values());const parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){const finalizer=arr[i];if(self.strategy==="sequential"){exits.push(yield*exit(finalizer(exit_)))}else{fibers.push(forkUnsafe(parent,finalizer(exit_),true,true,"inherit"))}}if(fibers.length>0){exits=yield*fiberAwaitAll(fibers)}return yield*exitAsVoidAll(exits)});var scopeForkUnsafe=(scope,finalizerStrategy)=>{const newScope=scopeMakeUnsafe(finalizerStrategy);if(scope.state._tag==="Closed"){newScope.state=scope.state;return newScope}const key={};scopeAddFinalizerUnsafe(scope,key,(exit2)=>scopeClose(newScope,exit2));scopeAddFinalizerUnsafe(newScope,key,(_)=>sync(()=>scopeRemoveFinalizerUnsafe(scope,key)));return newScope};var scopeAddFinalizerExit=(scope,finalizer)=>{return suspend(()=>{if(scope.state._tag==="Closed"){return finalizer(scope.state.exit)}scopeAddFinalizerUnsafe(scope,{},finalizer);return void_})};var scopeAddFinalizer=(scope,finalizer)=>scopeAddFinalizerExit(scope,constant(finalizer));var scopeAddFinalizerUnsafe=(scope,key,finalizer)=>{if(scope.state._tag==="Empty"){scope.state={_tag:"Open",finalizers:new Map([[key,finalizer]])}}else if(scope.state._tag==="Open"){scope.state.finalizers.set(key,finalizer)}};var scopeRemoveFinalizerUnsafe=(scope,key)=>{if(scope.state._tag==="Open"){scope.state.finalizers.delete(key)}};var scopeMakeUnsafe=(finalizerStrategy="sequential")=>({[ScopeCloseableTypeId]:ScopeCloseableTypeId,[ScopeTypeId]:ScopeTypeId,strategy:finalizerStrategy,state:constScopeEmpty});var constScopeEmpty={_tag:"Empty"};var scope=scopeTag;var provideScope=provideService(scopeTag);var scoped=(self)=>withFiber((fiber)=>{const prev=fiber.context;const scope2=scopeMakeUnsafe();fiber.setContext(add(fiber.context,scopeTag,scope2));return onExitPrimitive(self,(exit2)=>{fiber.setContext(prev);return scopeCloseUnsafe(scope2,exit2)})});var scopedWith=(f)=>suspend(()=>{const scope2=scopeMakeUnsafe();return onExit(f(scope2),(exit2)=>suspend(()=>scopeCloseUnsafe(scope2,exit2)??void_))});var acquireRelease=(acquire,release,options)=>contextWith((context2)=>uninterruptibleMask((restore)=>flatMap2(scope,(scope2)=>tap(options?.interruptible?restore(acquire):acquire,(a)=>scopeAddFinalizerExit(scope2,(exit2)=>provideContext(release(a,exit2),context2))))));var addFinalizer=(finalizer)=>flatMap2(scope,(scope2)=>contextWith((context2)=>scopeAddFinalizerExit(scope2,(exit2)=>provideContext(finalizer(exit2),context2))));var onExitPrimitive=makePrimitive({op:"OnExit",single:false,[evaluate](fiber){fiber._stack.push(this);return this[args][0]},[contAll](fiber){if(fiber.interruptible&&this[args][2]!==true){fiber._stack.push(setInterruptibleTrue);fiber.interruptible=false}},[contA](value,_,exit2){exit2??=exitSucceed(value);const eff=this[args][1](exit2);return eff?flatMap2(eff,(_2)=>exit2):exit2},[contE](cause,_,exit2){exit2??=exitFailCause(cause);const eff=this[args][1](exit2);return eff?flatMap2(eff,(_2)=>exit2):exit2}});var onExit=dual(2,onExitPrimitive);var ensuring=dual(2,(self,finalizer)=>onExit(self,(_)=>finalizer));var onExitFilter=dual(3,(self,filter4,f)=>onExit(self,(exit2)=>{const b=filter4(exit2);return isFailure2(b)?void_:f(b.success,exit2)}));var onError=dual(2,(self,f)=>onExitFilter(self,exitFilterCause,f));var onErrorFilter=dual(3,(self,filter4,f)=>onExit(self,(exit2)=>{if(exit2._tag!=="Failure"){return void_}const result2=filter4(exit2.cause);return isFailure2(result2)?void_:f(result2.success,exit2.cause)}));var onInterrupt=dual(2,(self,finalizer)=>onErrorFilter(causeFilterInterruptors,finalizer)(self));var acquireUseRelease=(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap2(acquire,(a)=>onExitPrimitive(restore(use(a)),(exit2)=>release(a,exit2),true)));var cachedInvalidateWithTTL=dual(2,(self,ttl)=>sync(()=>{const ttlMillis=toMillis(fromInputUnsafe(ttl));const isFinite3=Number.isFinite(ttlMillis);const latch=makeLatchUnsafe(false);let expiresAt=0;let running=false;let exit2;const wait=flatMap2(latch.await,()=>exit2);return[withFiber((fiber)=>{const clock=fiber.getRef(ClockRef);const now=isFinite3?clock.currentTimeMillisUnsafe():0;if(running||now<expiresAt)return exit2??wait;running=true;latch.closeUnsafe();exit2=undefined;return onExit(self,(exit_)=>sync(()=>{running=false;expiresAt=clock.currentTimeMillisUnsafe()+ttlMillis;exit2=exit_;latch.openUnsafe()}))}),sync(()=>{expiresAt=0;latch.closeUnsafe();exit2=undefined})]}));var cachedWithTTL=dual(2,(self,timeToLive)=>map4(cachedInvalidateWithTTL(self,timeToLive),(tuple)=>tuple[0]));var cached=(self)=>cachedWithTTL(self,infinity);var interrupt=withFiber((fiber)=>failCause(causeInterrupt(fiber.id)));var uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return self});var setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){fiber.interruptible=this[args];if(fiber._interruptedCause&&fiber.interruptible){return()=>failCause(fiber._interruptedCause)}}});var setInterruptibleTrue=setInterruptible(true);var setInterruptibleFalse=setInterruptible(false);var setFiberInterruptible=(fiber)=>{fiber.interruptible=true;fiber._stack.push(setInterruptibleFalse);if(fiber._interruptedCause)return failCause(fiber._interruptedCause)};var interruptible=(self)=>withFiber((fiber)=>{if(fiber.interruptible)return self;return setFiberInterruptible(fiber)??self});var uninterruptibleMask=(f)=>withFiber((fiber)=>{if(!fiber.interruptible)return f(identity);fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return f(interruptible)});var all=(arg,options)=>{if(isIterable(arg)){return options?.mode==="result"?forEach(arg,result,options):forEach(arg,identity,options)}else if(options?.discard){return options.mode==="result"?forEach(Object.values(arg),result,options):forEach(Object.values(arg),identity,options)}return suspend(()=>{const out={};return as(forEach(Object.entries(arg),([key,effect])=>map4(options?.mode==="result"?result(effect):effect,(value)=>{out[key]=value}),{discard:true,concurrency:options?.concurrency}),out)})};var whileLoop=makePrimitive({op:"While",[contA](value,fiber){this[args].step(value);if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid},[evaluate](fiber){if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid}});var forEach=dual((args2)=>typeof args2[1]==="function",(iterable,f,options)=>withFiber((parent)=>{const concurrencyOption=options?.concurrency==="inherit"?parent.getRef(CurrentConcurrency):options?.concurrency??1;const concurrency=concurrencyOption==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrencyOption);if(concurrency===1){return forEachSequential(iterable,f,options)}const items=fromIterable(iterable);let length=items.length;if(length===0){return options?.discard?void_:succeed3([])}const out=options?.discard?undefined:new Array(length);const eff=forEachConcurrent({f,out},items,{concurrency});return eff?as(eff,out):succeed3(out)}));var forEachSequential=(iterable,f,options)=>suspend(()=>{const out=options?.discard?undefined:[];const iterator=iterable[Symbol.iterator]();let state=iterator.next();let index=0;return as(whileLoop({while:()=>!state.done,body:()=>f(state.value,index++),step:(b)=>{if(out)out.push(b);state=iterator.next()}}),out)});var iterateEagerImpl=(options)=>{const onItem=options.onItem;const step=options.step;return(state,items,opts)=>{let index=opts?.start??0;const end=opts?.end??items.length;const concurrency=opts?.concurrency??1;const orderedStep=opts?.orderedStep===true&&concurrency>1;let done2=false;let parentFiber;let fibers;let resume;let interrupted=false;let terminal;let effect;let nextIndex=index;const exits=orderedStep?new Array(end):undefined;const failDefect=(error)=>{const defect=exitDie(error);terminal=defect;done2=true;interrupted=true;return fibers&&fibers.size>0?flatMap2(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>defect):defect};const runStep=(item,exit2,currentIndex)=>{if(!orderedStep)return step(state,item,exit2,currentIndex);if(terminal)return terminal;exits[currentIndex]=exit2;while(nextIndex<end){const nextExit=exits[nextIndex];if(nextExit===undefined)return;exits[nextIndex]=undefined;const index2=nextIndex++;const result2=step(state,items[index2],nextExit,index2);if(result2)return result2}};const go=()=>{let paused=false;for(;!terminal&&index<end;index++){const item=items[index];const eff=effect??onItem(state,item,index);if(effectIsExit(eff)){terminal=runStep(item,eff,index);if(terminal)break}else if(concurrency===1){return flatMap2(exit(eff),(exit2)=>{terminal=runStep(item,exit2,index);index++;return terminal??go()??void_})}else if(!parentFiber){return callback((cb)=>{parentFiber=getCurrentFiber();fibers=new Set;effect=eff;resume=cb;let result2;try{result2=go()}catch(error){return cb(failDefect(error))}if(result2)return cb(result2);return suspend(()=>{terminal=exitVoid;interrupted=true;return fibers?fiberInterruptAll(fibers):void_})})}else{effect=undefined;const fiber=forkUnsafe(parentFiber,eff,true,true,"inherit");if(fiber._exit){terminal=runStep(item,fiber._exit,index);if(terminal)break;continue}fibers.add(fiber);const currentIndex=index;fiber.addObserver((exit2)=>{fibers.delete(fiber);try{if(terminal){if(!interrupted&&exit2._tag==="Failure"){for(const reason of exit2.cause.reasons){if(reason._tag==="Interrupt")continue;else if(terminal._tag==="Failure"){terminal.cause.reasons.push(reason)}else{terminal=exitFailCause(causeFromReasons([reason]))}}}}else{const result2=runStep(item,exit2,currentIndex);if(result2){terminal=result2._tag==="Failure"?exitFailCause(causeFromReasons(result2.cause.reasons.slice())):result2;go()}}if(paused){const eff2=go();if(eff2)resume(eff2)}else if(done2&&fibers.size===0){resume(terminal??void_)}}catch(error){resume(failDefect(error))}});if(fibers.size<concurrency)continue;paused=true;index++;return}}done2=true;if(terminal){if(fibers&&fibers.size>0){const annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure"){return terminal}}else if(resume){if(!fibers){return exitVoid}else if(fibers.size===0){resume(void_)}}};return go()}};var iterateEager=()=>iterateEagerImpl;var forEachConcurrent=iterateEagerImpl({onItem(state,item,index){return state.f(item,index)},step(state,_,exit2,index){if(exit2._tag==="Failure")return exit2;else if(state.out){state.out[index]=exit2.value}}});var filterOrElse=dual(3,(self,predicate,orElse)=>flatMap2(self,(a)=>predicate(a)?succeed3(a):orElse(a)));var filter4=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>suspend(()=>{const out=[];return as(forEach(elements,(a,i)=>{const result2=predicate(a,i);if(typeof result2==="boolean"){if(result2)out.push(a);return void_}return map4(result2,(keep)=>{if(keep){out.push(a)}})},{discard:true,concurrency:options?.concurrency}),out)}));var forkUnsafe=(parent,effect,immediate=false,daemon=false,uninterruptible2=false)=>{const interruptible2=uninterruptible2==="inherit"?parent.interruptible:!uninterruptible2;const child=new FiberImpl(parent.context,interruptible2);if(immediate){child.evaluate(effect)}else{parent.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0)}if(!daemon&&!child._exit){parent.children().add(child);child.addObserver(()=>parent._children.delete(child))}return child};var forkIn=dual((args2)=>isEffect(args2[0]),(self,scope2,options)=>withFiber((parent)=>{const fiber=forkUnsafe(parent,self,options?.startImmediately,true,options?.uninterruptible);if(!fiber._exit){if(scope2.state._tag!=="Closed"){const key={};const finalizer=()=>withFiberId((interruptor)=>interruptor===fiber.id?void_:fiberInterrupt(fiber));scopeAddFinalizerUnsafe(scope2,key,finalizer);fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope2,key))}else{fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent))}}return succeed3(fiber)}));var forkScoped=dual((args2)=>isEffect(args2[0]),(self,options)=>flatMap2(scope,(scope2)=>forkIn(self,scope2,options)));var runForkWith=(context2)=>(effect,options)=>{const fiber=new FiberImpl(options?.scheduler?add(context2,Scheduler,options.scheduler):context2,options?.uninterruptible!==true);fiber.evaluate(effect);if(fiber._exit)return fiber;if(options?.signal){if(options.signal.aborted){fiber.interruptUnsafe()}else{const abort=()=>fiber.interruptUnsafe();options.signal.addEventListener("abort",abort,{once:true});fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}}if(options?.onFiberStart){options.onFiberStart(fiber)}return fiber};var fiberRunIn=dual(2,(self,scope2)=>{if(self._exit){return self}else if(scope2.state._tag==="Closed"){self.interruptUnsafe(self.id);return self}const key={};scopeAddFinalizerUnsafe(scope2,key,()=>fiberInterrupt(self));self.addObserver(()=>scopeRemoveFinalizerUnsafe(scope2,key));return self});var runFork=runForkWith(empty());var runPromiseExitWith=(context2)=>{const runFork2=runForkWith(context2);return(effect,options)=>{const fiber=runFork2(effect,options);return new Promise((resolve)=>{fiber.addObserver((exit2)=>resolve(exit2))})}};var runPromiseWith=(context2)=>{const runPromiseExit=runPromiseExitWith(context2);return(effect,options)=>runPromiseExit(effect,options).then((exit2)=>{if(exit2._tag==="Failure"){throw causeSquash(exit2.cause)}return exit2.value})};var runPromise=runPromiseWith(empty());var runSyncExitWith=(context2)=>{const runFork2=runForkWith(context2);return(effect)=>{if(effectIsExit(effect))return effect;const scheduler=new MixedScheduler("sync");const fiber=runFork2(effect,{scheduler});fiber._dispatcher?.flush();return fiber._exit??exitDie(new AsyncFiberError(fiber))}};var runSyncExit=runSyncExitWith(empty());var runSyncWith=(context2)=>{const runSyncExit2=runSyncExitWith(context2);return(effect)=>{const exit2=runSyncExit2(effect);if(exit2._tag==="Failure")throw causeSquash(exit2.cause);return exit2.value}};var runSync=runSyncWith(empty());var succeedTrue=succeed3(true);var succeedFalse=succeed3(false);class Latch{waiters=[];scheduled=false;_isOpen;constructor(isOpen){this._isOpen=isOpen}scheduleUnsafe(fiber){if(this.scheduled||this.waiters.length===0){return succeedTrue}this.scheduled=true;fiber.currentDispatcher.scheduleTask(this.flushWaiters,0);return succeedTrue}flushWaiters=()=>{this.scheduled=false;const waiters=this.waiters;this.waiters=[];for(let i=0;i<waiters.length;i++){waiters[i](exitVoid)}};open=withFiber((fiber)=>{if(this._isOpen)return succeedFalse;this._isOpen=true;return this.scheduleUnsafe(fiber)});release=withFiber((fiber)=>this._isOpen?succeedFalse:this.scheduleUnsafe(fiber));openUnsafe(){if(this._isOpen)return false;this._isOpen=true;this.flushWaiters();return true}await=callback((resume)=>{if(this._isOpen){return resume(void_)}this.waiters.push(resume);return sync(()=>{const index=this.waiters.indexOf(resume);if(index!==-1){this.waiters.splice(index,1)}})});closeUnsafe(){if(!this._isOpen)return false;this._isOpen=false;return true}close=sync(()=>this.closeUnsafe());whenOpen=(self)=>flatMap2(this.await,()=>self);isOpen(){return this._isOpen}}var makeLatchUnsafe=(open)=>new Latch(open??false);var bigint02=BigInt(0);var NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:false,status:{_tag:"Ended",startTime:bigint02,endTime:bigint02,exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}};var noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var filterDisablePropagation=(span)=>{if(!span)return none2();return get(span.annotations,DisablePropagation)?span._tag==="Span"?filterDisablePropagation(getOrUndefined(span.parent)):none2():some2(span)};var makeSpanUnsafe=(fiber,name,options)=>{const disablePropagation=!fiber.getRef(TracerEnabled)||options?.annotations&&get(options.annotations,DisablePropagation);const parent=options?.parent!==undefined?some2(options.parent):options?.root?none2():filterDisablePropagation(fiber.currentSpan);let span;if(disablePropagation){span=noopSpan({name,parent,annotations:add(options?.annotations??empty(),DisablePropagation,true)})}else{const tracer=fiber.getRef(Tracer);const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);const annotationsFromEnv=fiber.getRef(TracerSpanAnnotations);const linksFromEnv=fiber.getRef(TracerSpanLinks);const level=options?.level??fiber.getRef(CurrentTraceLevel);const links=options?.links!==undefined?[...linksFromEnv,...options.links]:linksFromEnv.slice();span=tracer.span({name,parent,annotations:options?.annotations??empty(),links,startTime:timingEnabled?clock.currentTimeNanosUnsafe():BigInt(0),kind:options?.kind??"internal",root:options?.root??isNone2(parent),sampled:options?.sampled??(isSome2(parent)&&parent.value.sampled===false?false:!isLogLevelGreaterThan(fiber.getRef(MinimumTraceLevel),level))});for(const[key,value]of Object.entries(annotationsFromEnv)){span.attribute(key,value)}if(options?.attributes!==undefined){for(const[key,value]of Object.entries(options.attributes)){span.attribute(key,value)}}}return span};var provideSpanStackFrame=(name,stack)=>{stack=typeof stack==="function"?stack:constUndefined;return updateService(CurrentStackFrame,(parent)=>({name,stack,parent}))};var useSpan=(name,...args2)=>{const options=args2.length===1?undefined:args2[0];const evaluate2=args2[args2.length-1];return withFiber((fiber)=>{const span=makeSpanUnsafe(fiber,name,options);const clock=fiber.getRef(ClockRef);return onExit(internalCall(()=>evaluate2(span)),(exit2)=>sync(()=>{if(span.status._tag==="Ended")return;span.end(clock.currentTimeNanosUnsafe(),exit2)}))})};var provideParentSpan=provideService(ParentSpan);var withParentSpan=function(){const dataFirst=isEffect(arguments[0]);const span=dataFirst?arguments[1]:arguments[0];let options=dataFirst?arguments[2]:arguments[1];let provideStackFrame=identity;if(span._tag==="Span"){options=addSpanStackTrace(options);provideStackFrame=provideSpanStackFrame(span.name,options?.captureStackTrace)}if(dataFirst){return provideParentSpan(provideStackFrame(arguments[0]),span)}return(self)=>provideParentSpan(provideStackFrame(self),span)};var ClockRef=Reference("effect/Clock",{defaultValue:()=>new ClockImpl});var MAX_TIMER_MILLIS=2**31-1;class ClockImpl{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=sync(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return processOrPerformanceNow()}currentTimeNanos=sync(()=>this.currentTimeNanosUnsafe());sleep(duration){return this.sleepMillis(toMillis(duration))}sleepMillis(millis2){if(millis2<=0)return yieldNow;else if(!Number.isFinite(millis2))return never;return callback((resume)=>{const continuation=millis2>MAX_TIMER_MILLIS?this.sleepMillis(millis2-MAX_TIMER_MILLIS):void_;const handle=setTimeout(()=>resume(continuation),Math.min(millis2,MAX_TIMER_MILLIS));return sync(()=>clearTimeout(handle))})}}var performanceNowNanos=function(){const bigint1e6=BigInt(1e6);if(typeof performance==="undefined"||typeof performance.now==="undefined"){return()=>BigInt(Date.now())*bigint1e6}let origin;return()=>{origin??=BigInt(Date.now())*bigint1e6-BigInt(Math.round(performance.now()*1e6));return origin+BigInt(Math.round(performance.now()*1e6))}}();var processOrPerformanceNow=function(){const processHrtime=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:undefined;if(!processHrtime){return performanceNowNanos}const origin=BigInt(Date.now())*BigInt(1e6)-processHrtime.bigint();return()=>origin+processHrtime.bigint()}();var clockWith=(f)=>withFiber((fiber)=>f(fiber.getRef(ClockRef)));var sleep=(duration)=>clockWith((clock)=>clock.sleep(fromInputUnsafe(duration)));var currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis);var TimeoutErrorTypeId="~effect/Cause/TimeoutError";var isTimeoutError=(u)=>hasProperty(u,TimeoutErrorTypeId);class TimeoutError extends TaggedError("TimeoutError"){[TimeoutErrorTypeId]=TimeoutErrorTypeId;constructor(message){super({message})}}var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var ConsoleRef=Reference("effect/Console/CurrentConsole",{defaultValue:()=>globalThis.console});var logLevelToOrder=(level)=>{switch(level){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}};var LogLevelOrder=mapInput(Number2,logLevelToOrder);var isLogLevelGreaterThan=isGreaterThan(LogLevelOrder);var CurrentLoggers=Reference("effect/Loggers/CurrentLoggers",{defaultValue:()=>new Set([defaultLogger,tracerLogger])});var LogToStderr=Reference("effect/Logger/LogToStderr",{defaultValue:constFalse});var LoggerTypeId="~effect/Logger";var LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}};var loggerMake=(log)=>{const self=Object.create(LoggerProto);self.log=log;return self};var formatLabel=(key)=>key.replace(/[\s="]/g,"_");var formatLogSpan=(self,now)=>{const label=formatLabel(self[0]);return`${label}=${now-self[1]}ms`};var logWithLevel=(level)=>(...message)=>{let cause=undefined;for(let i=0,len=message.length;i<len;i++){const msg=message[i];if(isCause(msg)){if(cause){message.splice(i,1)}else{message=message.slice(0,i).concat(message.slice(i+1))}cause=cause?causeFromReasons(cause.reasons.concat(msg.reasons)):msg;i--}}if(cause===undefined){cause=causeEmpty}return withFiber((fiber)=>{const logLevel=level??fiber.currentLogLevel;if(isLogLevelGreaterThan(fiber.minimumLogLevel,logLevel)){return void_}const clock=fiber.getRef(ClockRef);const loggers=fiber.getRef(CurrentLoggers);if(loggers.size>0){const date=new Date(clock.currentTimeMillisUnsafe());for(const logger of loggers){logger.log({cause,fiber,date,logLevel,message})}}return void_})};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"};var logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`;var defaultLogger=loggerMake(({cause,date,fiber,logLevel,message})=>{const message_=Array.isArray(message)?message.slice():[message];if(cause.reasons.length>0){message_.push(causePretty(cause))}const now=date.getTime();const spans=fiber.getRef(CurrentLogSpans);let spanString="";for(const span of spans){spanString+=` ${formatLogSpan(span,now)}`}const annotations=fiber.getRef(CurrentLogAnnotations);if(Object.keys(annotations).length>0){message_.push(annotations)}const console2=fiber.getRef(ConsoleRef);const log=fiber.getRef(LogToStderr)?console2.error:console2.log;log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`,...message_)});var tracerLogger=loggerMake(({cause,fiber,logLevel,message})=>{const clock=fiber.getRef(ClockRef);const annotations=fiber.getRef(CurrentLogAnnotations);const span=fiber.currentSpan;if(span===undefined||span._tag==="ExternalSpan")return;const attributes={};for(const[key,value]of Object.entries(annotations)){attributes[key]=value}attributes["effect.fiberId"]=fiber.id;attributes["effect.logLevel"]=logLevel.toUpperCase();if(cause.reasons.length>0){attributes["effect.cause"]=causePretty(cause)}span.event(toStringUnknown(Array.isArray(message)&&message.length===1?message[0]:message),clock.currentTimeNanosUnsafe(),attributes)});var succeed4=exitSucceed;var failCause2=exitFailCause;var fail4=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess;var TypeId5="~effect/Deferred";var DeferredProto={[TypeId5]:{_A:identity,_E:identity},pipe(){return pipeArguments(this,arguments)}};var makeUnsafe2=()=>{const self=Object.create(DeferredProto);self.resumes=undefined;self.effect=undefined;return self};var _await=(self)=>callback((resume)=>{if(self.effect)return resume(self.effect);self.resumes??=[];self.resumes.push(resume);return sync(()=>{const index=self.resumes.indexOf(resume);self.resumes.splice(index,1)})});var completeWith=dual(2,(self,effect)=>sync(()=>doneUnsafe(self,effect)));var done2=completeWith;var isDone2=(self)=>sync(()=>isDoneUnsafe(self));var isDoneUnsafe=(self)=>self.effect!==undefined;var doneUnsafe=(self,effect)=>{if(self.effect)return false;self.effect=effect;if(self.resumes){for(let i=0;i<self.resumes.length;i++){self.resumes[i](effect)}self.resumes=undefined}return true};var MinimumLogLevel2=MinimumLogLevel;var Scope=scopeTag;var makeUnsafe3=scopeMakeUnsafe;var provide=provideScope;var addFinalizerExit=scopeAddFinalizerExit;var addFinalizer2=scopeAddFinalizer;var forkUnsafe2=scopeForkUnsafe;var close=scopeClose;var TypeId6="~effect/Layer";var MemoMapTypeId="~effect/Layer/MemoMap";var memoMapReuse=(entry,scope2)=>{entry.observers++;return andThen(scopeAddFinalizerExit(scope2,(exit2)=>entry.finalizer(exit2)),entry.effect)};var LayerProto={[TypeId6]:{_ROut:identity,_E:identity,_RIn:identity},pipe(){return pipeArguments(this,arguments)}};var fromBuildUnsafe=(build)=>{const self=Object.create(LayerProto);self.build=build;return self};var fromBuild=(build)=>fromBuildUnsafe((memoMap,scope2)=>{const layerScope=forkUnsafe2(scope2);return onExit(build(memoMap,layerScope),(exit2)=>exit2._tag==="Failure"?close(layerScope,exit2):void_)});var fromBuildMemo=(build)=>{const self=fromBuild((memoMap,scope2)=>memoMap.getOrElseMemoize(self,scope2,build));return self};var memoMapBuild=(memoMap,layer,scope2,build)=>{const layerScope=makeUnsafe3();const deferred=makeUnsafe2();const entry={observers:1,effect:_await(deferred),finalizer:(exit2)=>suspend(()=>{entry.observers--;if(entry.observers===0){memoMap.map.delete(layer);return close(layerScope,exit2)}return void_})};memoMap.map.set(layer,entry);return scopeAddFinalizerExit(scope2,entry.finalizer).pipe(flatMap2(()=>build(memoMap,layerScope)),onExit((exit2)=>{entry.effect=exit2;return done2(deferred,exit2)}))};class MemoMapImpl{get[MemoMapTypeId](){return MemoMapTypeId}parent;constructor(parent){this.parent=parent}map=new Map;get(layer,scope2){const local=this.map.get(layer);if(local){return memoMapReuse(local,scope2)}return this.parent?.get(layer,scope2)}getOrElseMemoize(layer,scope2,build){const existing=this.get(layer,scope2);if(existing){return existing}return memoMapBuild(this,layer,scope2,build)}}var makeMemoMapUnsafe=()=>new MemoMapImpl;var forkMemoMapUnsafe=(parent)=>new MemoMapImpl(parent);class CurrentMemoMap extends Service()("effect/Layer/CurrentMemoMap"){static forkOrCreate(self){const current=getOrUndefined2(self,CurrentMemoMap);return current?forkMemoMapUnsafe(current):makeMemoMapUnsafe()}}var buildWithMemoMap=dual(3,(self,memoMap,scope2)=>provideService(map4(self.build(memoMap,scope2),add(CurrentMemoMap,memoMap)),CurrentMemoMap,memoMap));var buildWithScope=dual(2,(self,scope2)=>withFiber((fiber)=>buildWithMemoMap(self,CurrentMemoMap.forkOrCreate(fiber.context),scope2)));var succeed5=function(){if(arguments.length===1){return(resource)=>succeedContext(make3(arguments[0],resource))}return succeedContext(make3(arguments[0],arguments[1]))};var succeedContext=(context2)=>fromBuildUnsafe(constant(succeed3(context2)));var effect=function(){if(arguments.length===1){return(effect2)=>effectImpl(arguments[0],effect2)}return effectImpl(arguments[0],arguments[1])};var effectImpl=(service,effect2)=>effectContext(map4(effect2,(value)=>make3(service,value)));var effectContext=(effect2)=>fromBuildMemo((_,scope2)=>provide(effect2,scope2));var effectDiscard=(effect2)=>effectContext(as(effect2,empty()));var mergeAllEffect=(layers,memoMap,scope2)=>{const parentScope=forkUnsafe2(scope2,"parallel");return forEach(layers,(layer)=>layer.build(memoMap,forkUnsafe2(parentScope,"sequential")),{concurrency:layers.length}).pipe(map4((context2)=>mergeAll(...context2)))};var mergeAll2=(...layers)=>fromBuild((memoMap,scope2)=>mergeAllEffect(layers,memoMap,scope2));var merge2=dual(2,(self,that)=>mergeAll2(self,...Array.isArray(that)?that:[that]));var provideWith=(self,that,f)=>fromBuild((memoMap,scope2)=>flatMap2(Array.isArray(that)?mergeAllEffect(that,memoMap,scope2):that.build(memoMap,scope2),(context2)=>self.build(memoMap,scope2).pipe(provideContext(context2),map4((merged)=>f(merged,context2)))));var provide2=dual(2,(self,that)=>provideWith(self,that,identity));var provideMerge=dual(2,(self,that)=>provideWith(self,that,(self2,that2)=>merge(that2,self2)));var isCause2=isCause;var isReason=isCauseReason;var isFailReason2=isFailReason;var fromReasons=causeFromReasons;var empty4=causeEmpty;var fail5=causeFail;var die2=causeDie;var interrupt2=causeInterrupt;var makeFailReason=(error)=>new Fail(error);var makeDieReason=(defect)=>new Die(defect);var makeInterruptReason2=makeInterruptReason;var hasInterruptsOnly2=hasInterruptsOnly;var map5=causeMap;var combine2=causeCombine;var squash=causeSquash;var findError2=findError;var hasInterrupts2=hasInterrupts;var isDone3=isDone;var Done2=Done;var done3=done;var isTimeoutError2=isTimeoutError;var UnknownError2=UnknownError;var Clock=ClockRef;var currentTimeMillis2=currentTimeMillis;var TypeId7="~effect/time/DateTime";var TimeZoneTypeId="~effect/time/DateTime/TimeZone";var Proto2={[TypeId7]:TypeId7,pipe(){return pipeArguments(this,arguments)},[NodeInspectSymbol](){return this.toString()},toJSON(){return toDateUtc(this).toJSON()}};var ProtoUtc={...Proto2,_tag:"Utc",[symbol](){return number(this.epochMilliseconds)},[symbol2](that){return isDateTime(that)&&that._tag==="Utc"&&this.epochMilliseconds===that.epochMilliseconds},toString(){return`DateTime.Utc(${toDateUtc(this).toJSON()})`}};var ProtoZoned={...Proto2,_tag:"Zoned",[symbol](){return combine(number(this.epochMilliseconds))(hash(this.zone))},[symbol2](that){return isDateTime(that)&&that._tag==="Zoned"&&this.epochMilliseconds===that.epochMilliseconds&&equals(this.zone,that.zone)},toString(){return`DateTime.Zoned(${formatIsoZoned(this)})`}};var ProtoTimeZone={[TimeZoneTypeId]:TimeZoneTypeId,[NodeInspectSymbol](){return this.toString()}};var ProtoTimeZoneNamed={...ProtoTimeZone,_tag:"Named",[symbol](){return string(`Named:${this.id}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Named"&&this.id===that.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:"TimeZone",_tag:"Named",id:this.id}}};var ProtoTimeZoneOffset={...ProtoTimeZone,_tag:"Offset",[symbol](){return string(`Offset:${this.offset}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Offset"&&this.offset===that.offset},toString(){return`TimeZone.Offset(${offsetToString(this.offset)})`},toJSON(){return{_id:"TimeZone",_tag:"Offset",offset:this.offset}}};var isDateTime=(u)=>hasProperty(u,TypeId7);var isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var makeUtc=(epochMillis)=>{const self=Object.create(ProtoUtc);self.epochMilliseconds=epochMillis;Object.defineProperty(self,"partsUtc",{value:undefined,enumerable:false,writable:true});return self};var minEpochMillis=-8640000000000000+12*60*60*1000;var maxEpochMillis=8640000000000000-14*60*60*1000;var now=map4(currentTimeMillis2,makeUtc);var toDateUtc=(self)=>new Date(self.epochMilliseconds);var toDate=(self)=>{if(self._tag==="Utc"){return new Date(self.epochMilliseconds)}else if(self.zone._tag==="Offset"){return new Date(self.epochMilliseconds+self.zone.offset)}else if(self.adjustedEpochMilliseconds!==undefined){return new Date(self.adjustedEpochMilliseconds)}const parts=self.zone.format.formatToParts(self.epochMilliseconds).filter((_)=>_.type!=="literal");const date=new Date(0);date.setUTCFullYear(Number(parts[2].value),Number(parts[0].value)-1,Number(parts[1].value));date.setUTCHours(Number(parts[3].value),Number(parts[4].value),Number(parts[5].value),Number(parts[6].value));self.adjustedEpochMilliseconds=date.getTime();return date};var zonedOffset=(self)=>{const date=toDate(self);return date.getTime()-toEpochMillis(self)};var offsetToString=(offset)=>{const abs=Math.abs(offset);let hours2=Math.floor(abs/(60*60*1000));let minutes2=Math.round(abs%(60*60*1000)/(60*1000));if(minutes2===60){hours2+=1;minutes2=0}return`${offset<0?"-":"+"}${String(hours2).padStart(2,"0")}:${String(minutes2).padStart(2,"0")}`};var zonedOffsetIso=(self)=>offsetToString(zonedOffset(self));var toEpochMillis=(self)=>self.epochMilliseconds;var constDayMillis=24*60*60*1000;var formatIso=(self)=>toDateUtc(self).toISOString();var formatIsoOffset=(self)=>{const date=toDate(self);return self._tag==="Utc"?date.toISOString():`${date.toISOString().slice(0,-1)}${zonedOffsetIso(self)}`};var formatIsoZoned=(self)=>self.zone._tag==="Offset"?formatIsoOffset(self):`${formatIsoOffset(self)}[${self.zone.id}]`;var Number3=globalThis.Number;var Order2=Number2;var round=dual(2,(self,precision)=>{const factor=Math.pow(10,precision);return Math.round(self*factor)/factor});var catchDone=dual(2,(effect2,f)=>catchCauseFilter(effect2,filterDoneLeftover,(l)=>f(l)));var isDoneCause=(cause)=>cause.reasons.some(isDoneFailure);var isDoneFailure=(failure)=>failure._tag==="Fail"&&isDone3(failure.error);var filterDone=composePassthrough(findError2,(e)=>isDone3(e)?succeed2(e):fail2(e));var filterDoneLeftover=composePassthrough(findError2,(e)=>isDone3(e)?succeed2(e.value):fail2(e));var doneExitFromCause=(cause)=>{const halt=filterDone(cause);return!isFailure2(halt)?succeed4(halt.success.value):failCause2(halt.failure)};var matchEffect2=dual(2,(self,options)=>matchCauseEffect(self,{onSuccess:options.onSuccess,onFailure:(cause)=>{const halt=filterDone(cause);return!isFailure2(halt)?options.onDone(halt.success.value):options.onFailure(halt.failure)}}));var TypeId8="~effect/Schedule";var CurrentMetadata=Reference("effect/Schedule/CurrentMetadata",{defaultValue:constant({input:undefined,output:undefined,duration:zero,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})});var ScheduleProto={[TypeId8]:{_Out:identity,_In:identity,_Env:identity},pipe(){return pipeArguments(this,arguments)}};var isSchedule=(u)=>hasProperty(u,TypeId8);var fromStep=(step)=>{const self=Object.create(ScheduleProto);self.step=step;return self};var metadataFn=()=>{let n=0;let previous;let start;return(now2,input)=>{if(start===undefined)start=now2;const elapsed=now2-start;const elapsedSincePrevious=previous===undefined?0:now2-previous;previous=now2;return{input,attempt:++n,start,now:now2,elapsed,elapsedSincePrevious}}};var fromStepWithMetadata=(step)=>fromStep(map4(step,(f)=>{const meta=metadataFn();return(now2,input)=>f(meta(now2,input))}));var toStep=(schedule)=>catchCause(schedule.step,(cause)=>succeed3(()=>failCause(cause)));var toStepWithMetadata=(schedule)=>clockWith((clock)=>map4(toStep(schedule),(step)=>{const metaFn=metadataFn();return(input)=>suspend(()=>{const now2=clock.currentTimeMillisUnsafe();return flatMap2(step(now2,input),([output,duration])=>{const meta=metaFn(now2,input);meta.output=output;meta.duration=duration;return as(sleep(duration),meta)})})}));var passthrough=(self)=>fromStep(map4(toStep(self),(step)=>(now2,input)=>matchEffect2(step(now2,input),{onSuccess:(result2)=>succeed3([input,result2[1]]),onFailure:failCause,onDone:()=>done3(input)})));var spaced=(duration)=>{const decoded=fromInputUnsafe(duration);return fromStepWithMetadata(succeed3((meta)=>succeed3([meta.attempt-1,decoded])))};var while_=dual(2,(self,predicate)=>fromStep(map4(toStep(self),(step)=>{const meta=metadataFn();return(now2,input)=>flatMap2(step(now2,input),(result2)=>{const[output,duration]=result2;const eff=predicate({...meta(now2,input),output,duration});return flatMap2(isEffect(eff)?eff:succeed3(eff),(check)=>check?succeed3(result2):done3(output))})})));var forever2=spaced(zero);var provideLayer=(self,layer,options)=>scopedWith((scope2)=>flatMap2(options?.local?buildWithMemoMap(layer,makeMemoMapUnsafe(),scope2):buildWithScope(layer,scope2),(context2)=>provideContext(self,context2)));var provide3=dual((args2)=>isEffect(args2[0]),(self,source,options)=>isContext(source)?provideContext(self,source):provideLayer(self,Array.isArray(source)?mergeAll2(...source):source,options));var repeatOrElse=dual(3,(self,schedule,orElse)=>flatMap2(toStepWithMetadata(schedule),(step)=>{let meta=CurrentMetadata.defaultValue();return catch_(forever(tap(flatMap2(suspend(()=>provideService(self,CurrentMetadata,meta)),step),(meta_)=>sync(()=>{meta=meta_})),{disableYield:true}),(error)=>isDone(error)?succeed3(error.value):orElse(error,meta.attempt===0?none2():some2(meta)))}));var retryOrElse=dual(3,(self,policy,orElse)=>flatMap2(toStepWithMetadata(policy),(step)=>{let meta=CurrentMetadata.defaultValue();let lastError;const loop=catch_(suspend(()=>provideService(self,CurrentMetadata,meta)),(error)=>{lastError=error;return flatMap2(step(error),(meta_)=>{meta=meta_;return loop})});return catchDone(loop,(out)=>internalCall(()=>orElse(lastError,out)))}));var repeat=dual(2,(self,options)=>{const schedule=typeof options==="function"?options(identity):isSchedule(options)?options:buildFromOptions(options);return repeatOrElse(self,schedule,fail3)});var retry=dual(2,(self,options)=>{const schedule=typeof options==="function"?options(identity):isSchedule(options)?options:buildFromOptions(options);return retryOrElse(self,schedule,fail3)});var passthroughForever=passthrough(forever2);var buildFromOptions=(options)=>{let schedule=options.schedule?passthrough(options.schedule):passthroughForever;if(options.while){schedule=while_(schedule,({input})=>{const applied=options.while(input);return isEffect(applied)?applied:succeed3(applied)})}if(options.until){schedule=while_(schedule,({input})=>{const applied=options.until(input);return isEffect(applied)?map4(applied,(b)=>!b):succeed3(!applied)})}if(options.times!==undefined){schedule=while_(schedule,({attempt})=>succeed3(attempt<=options.times))}return schedule};var isEffect2=isEffect;var all2=all;var forEach2=forEach;var whileLoop2=whileLoop;var promise2=promise;var tryPromise2=tryPromise;var succeed6=succeed3;var succeedNone2=succeedNone;var succeedSome2=succeedSome;var suspend2=suspend;var sync2=sync;var void_3=void_;var callback2=callback;var gen2=gen;var fail6=fail3;var failCause3=failCause;var failCauseSync2=failCauseSync;var die3=die;var try_3=try_2;var withFiber2=withFiber;var fromResult2=fromResult;var flatMap3=flatMap2;var andThen2=andThen;var tap2=tap;var result2=result;var exit2=exit;var map6=map4;var as2=as;var asVoid2=asVoid;var zipWith2=zipWith;var catch_2=catch_;var catchTag2=catchTag;var catchTags2=catchTags;var catchCause2=catchCause;var catchIf2=catchIf;var catchFilter2=catchFilter;var mapError3=mapError2;var orDie2=orDie;var tapError2=tapError;var tapCause2=tapCause;var retry2=retry;var ignore2=ignore;var timeout2=timeout;var timeoutOrElse2=timeoutOrElse;var delay2=delay;var sleep2=sleep;var raceFirst2=raceFirst;var filter5=filter4;var filterOrElse2=filterOrElse;var filterOrFail2=filterOrFail;var match6=match5;var matchCauseEffect2=matchCauseEffect;var matchEffect3=matchEffect;var context2=context;var contextWith2=contextWith;var provide4=provide3;var provideContext2=provideContext;var serviceOption2=serviceOption;var updateContext2=updateContext;var provideService2=provideService;var provideServiceEffect2=provideServiceEffect;var scope2=scope;var scoped2=scoped;var scopedWith2=scopedWith;var acquireRelease2=acquireRelease;var acquireUseRelease2=acquireUseRelease;var addFinalizer3=addFinalizer;var ensuring2=ensuring;var onError2=onError;var onExit2=onExit;var cached2=cached;var interrupt3=interrupt;var onInterrupt2=onInterrupt;var uninterruptible2=uninterruptible;var uninterruptibleMask2=uninterruptibleMask;var forever3=forever;var repeat2=repeat;var useSpan2=useSpan;var withParentSpan2=withParentSpan;var forkIn2=forkIn;var forkScoped2=forkScoped;var runFork2=runFork;var runForkWith2=runForkWith;var runPromise2=runPromise;var runSync2=runSync;var runSyncExit2=runSyncExit;var fnUntraced2=fnUntraced;var fn2=fn;var clockWith2=clockWith;var logError=logWithLevel("Error");var effectify=(fn3,onError3,onSyncError)=>(...args2)=>callback2((resume)=>{try{fn3(...args2,(err,result3)=>{if(err){resume(fail6(onError3?onError3(err,args2):err))}else{resume(succeed6(result3))}})}catch(err){resume(onSyncError?fail6(onSyncError(err,args2)):die3(err))}});var mapEager2=mapEager;var mapErrorEager2=mapErrorEager;var mapBothEager2=mapBothEager;var flatMapEager2=flatMapEager;var fnUntracedEager2=fnUntracedEager;function set(self,key,value){if(key==="__proto__"){Object.defineProperty(self,key,{value,writable:true,enumerable:true,configurable:true})}else{self[key]=value}return self}function resolve(ast){return ast.checks?ast.checks[ast.checks.length-1].annotations:ast.annotations}function resolveAt(key){return(ast)=>resolve(ast)?.[key]}var resolveIdentifier=resolveAt("identifier");var resolveDescription=resolveAt("description");var resolveBrands=resolveAt("brands");var getExpected=memoize((ast)=>{const identifier2=resolveIdentifier(ast);if(typeof identifier2==="string")return identifier2;return ast.getExpected(getExpected)});var redactedRegistry=new WeakMap;var value=(self)=>{if(redactedRegistry.has(self)){return redactedRegistry.get(self)}else{throw new Error("Unable to get redacted value"+(self.label?` with label: "${self.label}"`:""))}};var stringOrRedacted=(val)=>typeof val==="string"?val:value(val);var TypeId9="~effect/data/Redacted";var isRedacted=(u)=>hasProperty(u,TypeId9);var make6=(value2,options)=>{const self=Object.create(Proto3);if(options?.label){self.label=options.label}redactedRegistry.set(self,value2);return self};var Proto3={[TypeId9]:{_A:(_)=>_},label:undefined,...PipeInspectableProto,toJSON(){return this.toString()},toString(){return`<redacted${isString(this.label)?":"+this.label:""}>`},[symbol](){return hash(redactedRegistry.get(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}};var value2=value;var makeEquivalence4=(isEquivalent)=>make((x,y)=>isEquivalent(value2(x),value2(y)));var TypeId10="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId10)}class Base{[TypeId10]=TypeId10;toString(){return defaultFormatter(this)}}class Filter extends Base{_tag="Filter";actual;filter;issue;constructor(actual,filter6,issue){super();this.actual=actual;this.filter=filter6;this.issue=issue}}class Encoding extends Base{_tag="Encoding";ast;actual;issue;constructor(ast,actual,issue){super();this.ast=ast;this.actual=actual;this.issue=issue}}class Pointer extends Base{_tag="Pointer";path;issue;constructor(path,issue){super();this.path=path;this.issue=issue}}class MissingKey extends Base{_tag="MissingKey";annotations;constructor(annotations){super();this.annotations=annotations}}class UnexpectedKey extends Base{_tag="UnexpectedKey";ast;actual;constructor(ast,actual){super();this.ast=ast;this.actual=actual}}class Composite extends Base{_tag="Composite";ast;actual;issues;constructor(ast,actual,issues){super();this.ast=ast;this.actual=actual;this.issues=issues}}class InvalidType extends Base{_tag="InvalidType";ast;actual;constructor(ast,actual){super();this.ast=ast;this.actual=actual}}class InvalidValue extends Base{_tag="InvalidValue";actual;annotations;constructor(actual,annotations){super();this.actual=actual;this.annotations=annotations}}class Forbidden extends Base{_tag="Forbidden";actual;annotations;constructor(actual,annotations){super();this.actual=actual;this.annotations=annotations}}class AnyOf extends Base{_tag="AnyOf";ast;actual;issues;constructor(ast,actual,issues){super();this.ast=ast;this.actual=actual;this.issues=issues}}class OneOf extends Base{_tag="OneOf";ast;actual;successes;constructor(ast,actual,successes){super();this.ast=ast;this.actual=actual;this.successes=successes}}function makeFilterIssue(input,entry){if(isIssue(entry)){return entry}if(typeof entry==="string"){return new InvalidValue(some2(input),{message:entry})}const inner=typeof entry.issue==="string"?new InvalidValue(some2(input),{message:entry.issue}):entry.issue;return new Pointer(entry.path,inner)}function makeSingle(input,out){if(out===undefined){return}if(typeof out==="boolean"){return out?undefined:new InvalidValue(some2(input))}return makeFilterIssue(input,out)}function make7(input,ast,out){if(Array.isArray(out)){if(isReadonlyArrayNonEmpty(out)){if(out.length===1){return makeFilterIssue(input,out[0])}return new Composite(ast,some2(input),map3(out,(entry)=>makeFilterIssue(input,entry)))}return}return makeSingle(input,out)}var defaultLeafHook=(issue)=>{const message=findMessage(issue);if(message!==undefined)return message;switch(issue._tag){case"InvalidType":return getExpectedMessage(getExpected(issue.ast),formatOption(issue.actual));case"InvalidValue":return`Invalid data ${formatOption(issue.actual)}`;case"MissingKey":return"Missing key";case"UnexpectedKey":return`Unexpected key with value ${format(issue.actual)}`;case"Forbidden":return"Forbidden operation";case"OneOf":return`Expected exactly one member to match the input ${format(issue.actual)}`}};var defaultCheckHook=(issue)=>{return findMessage(issue.issue)??findMessage(issue)};function getExpectedMessage(expected,actual){return`Expected ${expected}, got ${actual}`}function toDefaultIssues(issue,path,leafHook,checkHook){switch(issue._tag){case"Filter":{const message=checkHook(issue);if(message!==undefined){return[{path,message}]}switch(issue.issue._tag){case"InvalidValue":return[{path,message:getExpectedMessage(formatCheck(issue.filter),format(issue.actual))}];default:return toDefaultIssues(issue.issue,path,leafHook,checkHook)}}case"Encoding":return toDefaultIssues(issue.issue,path,leafHook,checkHook);case"Pointer":return toDefaultIssues(issue.issue,[...path,...issue.path],leafHook,checkHook);case"Composite":return issue.issues.flatMap((issue2)=>toDefaultIssues(issue2,path,leafHook,checkHook));case"AnyOf":{const message=findMessage(issue);if(issue.issues.length===0){if(message!==undefined)return[{path,message}];const expected=getExpectedMessage(getExpected(issue.ast),format(issue.actual));return[{path,message:expected}]}return issue.issues.flatMap((issue2)=>toDefaultIssues(issue2,path,leafHook,checkHook))}default:return[{path,message:leafHook(issue)}]}}function formatCheck(check){const expected=check.annotations?.expected;if(typeof expected==="string")return expected;switch(check._tag){case"Filter":return"<filter>";case"FilterGroup":return check.checks.map((check2)=>formatCheck(check2)).join(" & ")}}function makeFormatterDefault(){return(issue)=>toDefaultIssues(issue,[],defaultLeafHook,defaultCheckHook).map(formatDefaultIssue).join(`
179
+ ${prefix}}`}return stack};var FiberTypeId=`~effect/Fiber/${version}`;var fiberVariance={_A:identity,_E:identity};var fiberIdStore={id:0};var getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=true){this[FiberTypeId]=fiberVariance;this.setContext(context);this.id=++fiberIdStore.id;this.currentOpCount=0;this.interruptible=interruptible;this._stack=[];this._observers=[];this._exit=undefined;this._children=undefined;this._interruptedCause=undefined;this._yielded=undefined;this._running=false;this._deferredInterrupt=false;this.runtimeMetrics?.recordFiberStart(this.context)}[FiberTypeId];id;interruptible;currentOpCount;_stack;_observers;_exit;_children;_interruptedCause;_yielded;_running;_deferredInterrupt;context;currentScheduler;currentTracerContext;currentSpan;currentLogLevel;minimumLogLevel;currentStackFrame;runtimeMetrics;maxOpsBeforeYield;currentPreventYield;_dispatcher=undefined;get currentDispatcher(){return this._dispatcher??=this.currentScheduler.makeDispatcher()}getRef(ref){return getReferenceUnsafe(this.context,ref)}addObserver(cb){if(this._exit){cb(this._exit);return constVoid}this._observers.push(cb);return()=>{const index=this._observers.indexOf(cb);if(index>=0){this._observers.splice(index,1)}}}interruptUnsafe(fiberId,annotations){if(this._exit){return}let cause=causeInterrupt(fiberId);if(this.currentStackFrame){cause=causeAnnotate(cause,make3(StackTraceKey,this.currentStackFrame))}if(annotations){cause=causeAnnotate(cause,annotations)}this._interruptedCause=this._interruptedCause?causeCombine(this._interruptedCause,cause):cause;if(this.interruptible){if(this._running){this._deferredInterrupt=true}else{this.evaluate(failCause(this._interruptedCause))}}}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit){return}else if(this._yielded!==undefined){const yielded=this._yielded;this._yielded=undefined;yielded()}const exit=this.runLoop(effect);if(exit===Yield){return}const interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==undefined){return this.evaluate(flatMap2(interruptChildren,()=>exit))}this._exit=exit;this.runtimeMetrics?.recordFiberEnd(this.context,this._exit);for(let i=0;i<this._observers.length;i++){this._observers[i](exit)}this._observers.length=0;this._stack.length=0;this._children=undefined;this.context=empty()}runLoop(effect){const prevFiber=globalThis[currentFiberTypeId];globalThis[currentFiberTypeId]=this;const prevRunning=this._running;this._running=true;let yielding=false;let current=effect;this.currentOpCount=0;try{while(true){if(this._deferredInterrupt){this._deferredInterrupt=false;current=failCause(this._interruptedCause)}this.currentOpCount++;if(!yielding&&!this.currentPreventYield&&this.currentScheduler.shouldYield(this)){yielding=true;const prev=current;current=flatMap2(yieldNow,()=>prev)}current=this.currentTracerContext?this.currentTracerContext(current,this):current[evaluate](this);if(current===Yield){const yielded=this._yielded;if(ExitTypeId in yielded){this._deferredInterrupt=false;this._yielded=undefined;return yielded}else if(this._deferredInterrupt){this._yielded=undefined;yielded();continue}return Yield}}}catch(error){if(!hasProperty(current,evaluate)){return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`)}return this.runLoop(exitDie(error))}finally{this._running=prevRunning;globalThis[currentFiberTypeId]=prevFiber}}getCont(symbol3){if(this._deferredInterrupt){this._deferredInterrupt=false;return deferredInterruptCont}while(true){const op=this._stack.pop();if(!op)return;const cont=op[contAll]&&op[contAll](this);if(cont){cont[symbol3]=cont;return cont}if(op[symbol3])return op}}yieldWith(value){this._yielded=value;return Yield}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){this.context=context;const scheduler=this.getRef(Scheduler);if(scheduler!==this.currentScheduler){this.currentScheduler=scheduler;this._dispatcher=undefined}this.currentSpan=context.mapUnsafe.get(ParentSpanKey);this.currentLogLevel=this.getRef(CurrentLogLevel);this.minimumLogLevel=this.getRef(MinimumLogLevel);this.currentStackFrame=context.mapUnsafe.get(CurrentStackFrame.key);this.maxOpsBeforeYield=this.getRef(MaxOpsBeforeYield);this.currentPreventYield=this.getRef(PreventSchedulerYield);this.runtimeMetrics=context.mapUnsafe.get(FiberRuntimeMetricsKey);const currentTracer=context.mapUnsafe.get(TracerKey);this.currentTracerContext=currentTracer?currentTracer["context"]:undefined}get currentSpanLocal(){return this.currentSpan?._tag==="Span"?this.currentSpan:undefined}}var deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}};var fiberMiddleware={interruptChildren:undefined};var fiberStackAnnotations=(fiber)=>{if(!fiber.currentStackFrame)return;const annotations=new Map;annotations.set(InterruptorStackTrace.key,fiber.currentStackFrame);return makeUnsafe(annotations)};var fiberAwait=(self)=>{const impl=self;if(impl._exit)return succeed3(impl._exit);return callback((resume)=>{if(impl._exit)return resume(succeed3(impl._exit));return sync(self.addObserver((exit)=>resume(succeed3(exit))))})};var fiberAwaitAll=(self)=>callback((resume)=>{const iter=self[Symbol.iterator]();const exits=[];let cancel=undefined;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit);result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit);loop()});return}resume(succeed3(exits))}loop();return sync(()=>cancel?.())});var fiberInterrupt=(self)=>withFiber((fiber)=>fiberInterruptAs(self,fiber.id));var fiberInterruptAs=dual((args2)=>hasProperty(args2[0],FiberTypeId),(self,fiberId,annotations)=>withFiber((parent)=>{let ann=fiberStackAnnotations(parent);ann=ann&&annotations?merge(ann,annotations):ann??annotations;self.interruptUnsafe(fiberId,ann);return asVoid(fiberAwait(self))}));var fiberInterruptAll=(fibers)=>withFiber((parent)=>{const annotations=fiberStackAnnotations(parent);let fiberArr=empty3();for(const fiber of fibers){fiber.interruptUnsafe(parent.id,annotations);fiberArr.push(fiber)}return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed;var failCause=exitFailCause;var fail3=exitFail;var sync=makePrimitive({op:"Sync",[evaluate](fiber){const value=this[args]();const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){return this[args]()}});var fromResult=match3({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){let resumed=false;fiber.currentDispatcher.scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid)},this[args]??0);return fiber.yieldWith(()=>{resumed=true})}});var yieldNow=yieldNowWith(0);var succeedSome=(a)=>succeed3(some2(a));var succeedNone=succeed3(none2());var failCauseSync=(evaluate2)=>suspend(()=>failCause(internalCall(evaluate2)));var die=(defect)=>exitDie(defect);var failSync=(error)=>suspend(()=>fail3(internalCall(error)));var void_=succeed3(undefined);var try_2=(options)=>{const evaluate2=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(internalCall(evaluate2))}catch(err){return fail3(internalCall(()=>catcher(err)))}})};var promise=(evaluate2)=>callbackOptions(function(resume,signal){internalCall(()=>evaluate2(signal)).then((a)=>resume(succeed3(a)),(e)=>resume(die(e)))},evaluate2.length!==0);var tryPromise=(options)=>{const f=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){const failWithCatch=(cause)=>{try{resume(fail3(internalCall(()=>catcher(cause))))}catch(err){resume(die(err))}};try{internalCall(()=>f(signal)).then((a)=>resume(succeed3(a)),failWithCatch)}catch(err){failWithCatch(err)}},f.length!==0)};var withFiberId=(f)=>withFiber((fiber)=>f(fiber.id));var callbackOptions=makePrimitive({op:"Async",single:false,[evaluate](fiber){const register=internalCall(()=>this[args][0].bind(fiber.currentScheduler));let resumed=false;let yielded=false;const controller=this[args][1]?new AbortController:undefined;const onCancel=register((effect)=>{if(resumed)return;resumed=true;if(yielded){fiber.evaluate(effect)}else{yielded=effect}},controller?.signal);if(yielded!==false)return yielded;yielded=true;fiber._yielded=()=>{resumed=true};if(controller===undefined&&onCancel===undefined){return Yield}fiber._stack.push(asyncFinalizer(()=>{resumed=true;controller?.abort();return onCancel??exitVoid}));return Yield}});var asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible){fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue)}},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap2(this[args](),()=>failCause(cause)):failCause(cause)}});var callback=(register)=>callbackOptions(register,register.length>=2);var never=callback(constVoid);var gen=(...args2)=>suspend(()=>fromIteratorUnsafe(args2.length===1?args2[0]():args2[1].call(args2[0].self)));var fnUntraced=(body,...pipeables)=>{const fn=pipeables.length===0?function(){return suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)))}:function(){let effect=suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)));for(let i=0;i<pipeables.length;i++){effect=pipeables[i](effect,...arguments)}return effect};return defineFunctionLength(body.length,fn)};var defineFunctionLength=(length,fn)=>Object.defineProperty(fn,"length",{value:length,configurable:true});var fnStackCleaner=makeStackCleaner(2);var fn=function(){const nameFirst=typeof arguments[0]==="string";const name=nameFirst?arguments[0]:"Effect.fn";const spanOptions=nameFirst?arguments[1]:undefined;const prevLimit=getStackTraceLimit();setStackTraceLimit(2);const defError=new globalThis.Error;setStackTraceLimit(prevLimit);if(nameFirst){return(body,...pipeables)=>makeFn(name,body,defError,pipeables,nameFirst,spanOptions)}return makeFn(name,arguments[0],defError,Array.prototype.slice.call(arguments,1),nameFirst,spanOptions)};var makeFn=(name,bodyOrOptions,defError,pipeables,addSpan,spanOptions)=>{const body=typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.pop().bind(bodyOrOptions.self);return defineFunctionLength(body.length,function(...args2){let result=suspend(()=>{const iter=body.apply(this,arguments);return isEffect(iter)?iter:fromIteratorUnsafe(iter)});for(let i=0;i<pipeables.length;i++){result=pipeables[i](result,...args2)}if(!isEffect(result)){return result}const prevLimit=getStackTraceLimit();setStackTraceLimit(2);const callError=new globalThis.Error;setStackTraceLimit(prevLimit);return updateService(addSpan?useSpan(name,spanOptions,(span)=>provideParentSpan(result,span)):result,CurrentStackFrame,(prev)=>({name,stack:fnStackCleaner(()=>callError.stack),parent:{name:`${name} (definition)`,stack:fnStackCleaner(()=>defError.stack),parent:prev}}))})};var fnUntracedEager=(body,...pipeables)=>defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(const pipeable of pipeables){effect=pipeable(effect)}return effect});var fromIteratorEagerUnsafe=(evaluate2)=>{try{const iterator=evaluate2();let value=undefined;while(true){const state=iterator.next(value);if(state.done){return succeed3(state.value)}const primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure"){return state.value}else{let isFirstExecution=true;return suspend(()=>{if(isFirstExecution){isFirstExecution=false;return flatMap2(state.value,(value2)=>fromIteratorUnsafe(iterator,value2))}else{return suspend(()=>fromIteratorUnsafe(evaluate2()))}})}}}catch(error){return die(error)}};var fromIteratorUnsafe=makePrimitive({op:"Iterator",single:false,[contA](value,fiber){const iter=this[args][0];while(true){const state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value)){fiber._stack.push(this);return state.value}else if(state.value._tag==="Failure"){return state.value}value=state.value.value}},[evaluate](fiber){return this[contA](this[args][1],fiber)}});var as=dual(2,(self,value)=>{const b=succeed3(value);return flatMap2(self,(_)=>b)});var asSome=(self)=>map4(self,some2);var andThen=dual(2,(self,f)=>flatMap2(self,(a)=>isEffect(f)?f:internalCall(()=>f(a))));var tap=dual(2,(self,f)=>flatMap2(self,(a)=>as(isEffect(f)?f:internalCall(()=>f(a)),a)));var asVoid=(self)=>flatMap2(self,(_)=>exitVoid);var raceAllFirst=(all,options)=>withFiber((parent)=>callback((resume)=>{let done2=false;const fibers=new Set;const onExit=(exit)=>{done2=true;resume(fibers.size===0?exit:flatMap2(uninterruptible(fiberInterruptAll(fibers)),()=>exit))};let i=0;for(const effect of all){if(done2)break;const index=i++;const fiber=forkUnsafe(parent,effect,true,true,false);fibers.add(fiber);fiber.addObserver((exit)=>{fibers.delete(fiber);const isWinner=!done2;onExit(exit);if(isWinner&&options?.onWinner){options.onWinner({fiber,index,parentFiber:parent})}})}return fiberInterruptAll(fibers)}));var raceFirst=dual((args2)=>isEffect(args2[1]),(self,that,options)=>raceAllFirst([self,that],options));var flatMap2=dual(2,(self,f)=>{const onSuccess=Object.create(OnSuccessProto);onSuccess[args]=self;onSuccess[contA]=f.length!==1?(a)=>f(a):f;return onSuccess});var OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var effectIsExit=(effect)=>(ExitTypeId in effect);var flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self)){return self._tag==="Success"?f(self.value):self}return flatMap2(self,f)});var map4=dual(2,(self,f)=>flatMap2(self,(a)=>succeed3(internalCall(()=>f(a)))));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map4(self,f));var mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError2(self,f));var mapBothEager=dual(2,(self,options)=>effectIsExit(self)?exitMapBoth(self,options):mapBoth(self,options));var exitInterrupt=(fiberId)=>exitFailCause(causeInterrupt(fiberId));var exitIsSuccess=(self)=>self._tag==="Success";var exitFilterCause=(self)=>self._tag==="Failure"?succeed2(self.cause):fail2(self);var exitVoid=exitSucceed(undefined);var exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self);var exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(f(error.success))});var exitMapBoth=dual(2,(self,options)=>{if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(options.onFailure(error.success))});var exitZipRight=dual(2,(self,that)=>exitIsSuccess(self)?that:self);var exitAsVoidAll=(exits)=>{const failures=[];for(const exit of exits){if(exit._tag==="Failure"){failures.push(...exit.cause.reasons)}}return failures.length===0?exitVoid:exitFailCause(causeFromReasons(failures))};var serviceOption=(service)=>withFiber((fiber)=>succeed3(getOption(fiber.context,service)));var updateContext=dual(2,(self,f)=>withFiber((fiber)=>{const prevContext=fiber.context;const nextContext=f(prevContext);if(prevContext===nextContext)return self;fiber.setContext(nextContext);return onExitPrimitive(self,()=>{fiber.setContext(prevContext);return})}));var updateService=dual(3,(self,service,f)=>updateContext(self,(s)=>{const prev=getUnsafe(s,service);const next=f(prev);if(prev===next)return s;return add(s,service,next)}));var context=()=>getContext;var getContext=withFiber((fiber)=>succeed3(fiber.context));var contextWith=(f)=>withFiber((fiber)=>f(fiber.context));var provideContext=dual(2,(self,context2)=>{if(effectIsExit(self))return self;return updateContext(self,merge(context2))});var provideService=function(){if(arguments.length===1){return dual(2,(self,impl)=>provideServiceImpl(self,arguments[0],impl))}return dual(3,(self,service,impl)=>provideServiceImpl(self,service,impl)).apply(this,arguments)};var provideServiceImpl=(self,service,implementation)=>updateContext(self,(s)=>{const prev=s.mapUnsafe.get(service.key);if(prev===implementation)return s;return add(s,service,implementation)});var provideServiceEffect=dual(3,(self,service,acquire)=>flatMap2(acquire,(implementation)=>provideService(self,service,implementation)));var zipWith=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>options?.concurrent?map4(all([self,that],{concurrency:2}),([a,a2])=>internalCall(()=>f(a,a2))):flatMap2(self,(a)=>map4(that,(a2)=>internalCall(()=>f(a,a2)))));var filterOrFail=dual((args2)=>isEffect(args2[0]),(self,predicate,orFailWith)=>filterOrElse(self,predicate,orFailWith?(a)=>fail3(orFailWith(a)):()=>fail3(new NoSuchElementError)));var forever=dual((args2)=>isEffect(args2[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap2(self,(_)=>yieldNow)),step:constVoid}));var catchCause=dual(2,(self,f)=>{const onFailure=Object.create(OnFailureProto);onFailure[args]=self;onFailure[contE]=f.length!==1?(cause)=>f(cause):f;return onFailure});var OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var catchCauseFilter=dual(3,(self,filter4,f)=>catchCause(self,(cause)=>{const eb=filter4(cause);return isFailure2(eb)?failCause(eb.failure):internalCall(()=>f(eb.success,cause))}));var catch_=dual(2,(self,f)=>catchCauseFilter(self,findError,(e)=>f(e)));var tapCause=dual(2,(self,f)=>catchCause(self,(cause)=>andThen(internalCall(()=>f(cause)),failCause(cause))));var tapCauseFilter=dual(3,(self,filter4,f)=>catchCause(self,(cause)=>{const result=filter4(cause);if(isFailure2(result)){return failCause(cause)}return andThen(internalCall(()=>f(result.success,cause)),failCause(cause))}));var tapError=dual(2,(self,f)=>tapCauseFilter(self,findError,(e)=>f(e)));var catchIf=dual((args2)=>isEffect(args2[0]),(self,predicate,f,orElse)=>catchCause(self,(cause)=>{const error=findError(cause);if(isFailure2(error))return failCause(error.failure);if(!predicate(error.success)){return orElse?internalCall(()=>orElse(error.success)):failCause(cause)}return internalCall(()=>f(error.success))}));var catchFilter=dual((args2)=>isEffect(args2[0]),(self,filter4,f,orElse)=>catchCause(self,(cause)=>{const error=findError(cause);if(isFailure2(error))return failCause(error.failure);const result=filter4(error.success);if(isFailure2(result)){return orElse?internalCall(()=>orElse(result.failure)):failCause(cause)}return internalCall(()=>f(result.success))}));var catchTag=dual((args2)=>isEffect(args2[0]),(self,k,f,orElse)=>{const pred=Array.isArray(k)?(e)=>hasProperty(e,"_tag")&&k.includes(e._tag):isTagged(k);return catchIf(self,pred,f,orElse)});var catchTags=dual((args2)=>isEffect(args2[0]),(self,cases,orElse)=>{let keys2;return catchFilter(self,(e)=>{keys2??=Object.keys(cases);return hasProperty(e,"_tag")&&isString(e["_tag"])&&keys2.includes(e["_tag"])?succeed2(e):fail2(e)},(e)=>internalCall(()=>cases[e["_tag"]](e)),orElse)});var mapError2=dual(2,(self,f)=>catch_(self,(error)=>failSync(()=>f(error))));var mapBoth=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>failSync(()=>options.onFailure(e)),onSuccess:(a)=>sync(()=>options.onSuccess(a))}));var orDie=(self)=>catch_(self,die);var ignore=dual((args2)=>isEffect(args2[0]),(self,options)=>{if(!options?.log){return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_})}const logEffect=logWithLevel(options.log===true?undefined:options.log);return matchCauseEffect(self,{onFailure(cause){const failure=findFail(cause);return isFailure2(failure)?failCause(failure.failure):options.message===undefined?logEffect(cause):logEffect(options.message,cause)},onSuccess:(_)=>void_})});var result=(self)=>matchEager(self,{onFailure:fail2,onSuccess:succeed2});var matchCauseEffect=dual(2,(self,options)=>{const primitive=Object.create(OnSuccessAndFailureProto);primitive[args]=self;primitive[contA]=options.onSuccess.length!==1?(a)=>options.onSuccess(a):options.onSuccess;primitive[contE]=options.onFailure.length!==1?(cause)=>options.onFailure(cause):options.onFailure;return primitive});var OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate](fiber){fiber._stack.push(this);return this[args]}});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{const fail4=cause.reasons.find(isFailReason);return fail4?internalCall(()=>options.onFailure(fail4.error)):failCause(cause)},onSuccess:options.onSuccess}));var match5=dual(2,(self,options)=>matchEffect(self,{onFailure:(error)=>sync(()=>options.onFailure(error)),onSuccess:(value)=>sync(()=>options.onSuccess(value))}));var matchEager=dual(2,(self,options)=>{if(effectIsExit(self)){if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitSucceed(options.onFailure(error.success))}return match5(self,options)});var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self);var exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){fiber._stack.push(this);return this[args]},[contA](value,_,exit2){return succeed3(exit2??exitSucceed(value))},[contE](cause,_,exit2){return succeed3(exit2??exitFailCause(cause))}});var delay=dual(2,(self,duration)=>andThen(sleep(duration),self));var timeoutOrElse=dual(2,(self,options)=>raceFirst(self,flatMap2(sleep(options.duration),options.orElse)));var timeout=dual(2,(self,duration)=>timeoutOrElse(self,{duration,orElse:()=>fail3(new TimeoutError)}));var ScopeTypeId="~effect/Scope";var ScopeCloseableTypeId="~effect/Scope/Closeable";var scopeTag=Service("effect/Scope");var scopeClose=(self,exit_)=>suspend(()=>scopeCloseUnsafe(self,exit_)??void_);var scopeCloseUnsafe=(self,exit_)=>{if(self.state._tag==="Closed")return;const closed={_tag:"Closed",exit:exit_};if(self.state._tag==="Empty"){self.state=closed;return}const{finalizers}=self.state;self.state=closed;if(finalizers.size===0){return}else if(finalizers.size===1){return finalizers.values().next().value(exit_)}return scopeCloseFinalizers(self,finalizers,exit_)};var scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[];const fibers=[];const arr=Array.from(finalizers.values());const parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){const finalizer=arr[i];if(self.strategy==="sequential"){exits.push(yield*exit(finalizer(exit_)))}else{fibers.push(forkUnsafe(parent,finalizer(exit_),true,true,"inherit"))}}if(fibers.length>0){exits=yield*fiberAwaitAll(fibers)}return yield*exitAsVoidAll(exits)});var scopeForkUnsafe=(scope,finalizerStrategy)=>{const newScope=scopeMakeUnsafe(finalizerStrategy);if(scope.state._tag==="Closed"){newScope.state=scope.state;return newScope}const key={};scopeAddFinalizerUnsafe(scope,key,(exit2)=>scopeClose(newScope,exit2));scopeAddFinalizerUnsafe(newScope,key,(_)=>sync(()=>scopeRemoveFinalizerUnsafe(scope,key)));return newScope};var scopeAddFinalizerExit=(scope,finalizer)=>{return suspend(()=>{if(scope.state._tag==="Closed"){return finalizer(scope.state.exit)}scopeAddFinalizerUnsafe(scope,{},finalizer);return void_})};var scopeAddFinalizer=(scope,finalizer)=>scopeAddFinalizerExit(scope,constant(finalizer));var scopeAddFinalizerUnsafe=(scope,key,finalizer)=>{if(scope.state._tag==="Empty"){scope.state={_tag:"Open",finalizers:new Map([[key,finalizer]])}}else if(scope.state._tag==="Open"){scope.state.finalizers.set(key,finalizer)}};var scopeRemoveFinalizerUnsafe=(scope,key)=>{if(scope.state._tag==="Open"){scope.state.finalizers.delete(key)}};var scopeMakeUnsafe=(finalizerStrategy="sequential")=>({[ScopeCloseableTypeId]:ScopeCloseableTypeId,[ScopeTypeId]:ScopeTypeId,strategy:finalizerStrategy,state:constScopeEmpty});var constScopeEmpty={_tag:"Empty"};var scope=scopeTag;var provideScope=provideService(scopeTag);var scoped=(self)=>withFiber((fiber)=>{const prev=fiber.context;const scope2=scopeMakeUnsafe();fiber.setContext(add(fiber.context,scopeTag,scope2));return onExitPrimitive(self,(exit2)=>{fiber.setContext(prev);return scopeCloseUnsafe(scope2,exit2)})});var scopedWith=(f)=>suspend(()=>{const scope2=scopeMakeUnsafe();return onExit(f(scope2),(exit2)=>suspend(()=>scopeCloseUnsafe(scope2,exit2)??void_))});var acquireRelease=(acquire,release,options)=>contextWith((context2)=>uninterruptibleMask((restore)=>flatMap2(scope,(scope2)=>tap(options?.interruptible?restore(acquire):acquire,(a)=>scopeAddFinalizerExit(scope2,(exit2)=>provideContext(release(a,exit2),context2))))));var addFinalizer=(finalizer)=>flatMap2(scope,(scope2)=>contextWith((context2)=>scopeAddFinalizerExit(scope2,(exit2)=>provideContext(finalizer(exit2),context2))));var onExitPrimitive=makePrimitive({op:"OnExit",single:false,[evaluate](fiber){fiber._stack.push(this);return this[args][0]},[contAll](fiber){if(fiber.interruptible&&this[args][2]!==true){fiber._stack.push(setInterruptibleTrue);fiber.interruptible=false}},[contA](value,_,exit2){exit2??=exitSucceed(value);const eff=this[args][1](exit2);return eff?flatMap2(eff,(_2)=>exit2):exit2},[contE](cause,_,exit2){exit2??=exitFailCause(cause);const eff=this[args][1](exit2);return eff?flatMap2(eff,(_2)=>exit2):exit2}});var onExit=dual(2,onExitPrimitive);var ensuring=dual(2,(self,finalizer)=>onExit(self,(_)=>finalizer));var onExitFilter=dual(3,(self,filter4,f)=>onExit(self,(exit2)=>{const b=filter4(exit2);return isFailure2(b)?void_:f(b.success,exit2)}));var onError=dual(2,(self,f)=>onExitFilter(self,exitFilterCause,f));var onErrorFilter=dual(3,(self,filter4,f)=>onExit(self,(exit2)=>{if(exit2._tag!=="Failure"){return void_}const result2=filter4(exit2.cause);return isFailure2(result2)?void_:f(result2.success,exit2.cause)}));var onInterrupt=dual(2,(self,finalizer)=>onErrorFilter(causeFilterInterruptors,finalizer)(self));var cachedInvalidateWithTTL=dual(2,(self,ttl)=>sync(()=>{const ttlMillis=toMillis(fromInputUnsafe(ttl));const isFinite3=Number.isFinite(ttlMillis);const latch=makeLatchUnsafe(false);let expiresAt=0;let running=false;let exit2;const wait=flatMap2(latch.await,()=>exit2);return[withFiber((fiber)=>{const clock=fiber.getRef(ClockRef);const now=isFinite3?clock.currentTimeMillisUnsafe():0;if(running||now<expiresAt)return exit2??wait;running=true;latch.closeUnsafe();exit2=undefined;return onExit(self,(exit_)=>sync(()=>{running=false;expiresAt=clock.currentTimeMillisUnsafe()+ttlMillis;exit2=exit_;latch.openUnsafe()}))}),sync(()=>{expiresAt=0;latch.closeUnsafe();exit2=undefined})]}));var cachedWithTTL=dual(2,(self,timeToLive)=>map4(cachedInvalidateWithTTL(self,timeToLive),(tuple)=>tuple[0]));var cached=(self)=>cachedWithTTL(self,infinity);var interrupt=withFiber((fiber)=>failCause(causeInterrupt(fiber.id)));var uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return self});var setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){fiber.interruptible=this[args];if(fiber._interruptedCause&&fiber.interruptible){return()=>failCause(fiber._interruptedCause)}}});var setInterruptibleTrue=setInterruptible(true);var setInterruptibleFalse=setInterruptible(false);var setFiberInterruptible=(fiber)=>{fiber.interruptible=true;fiber._stack.push(setInterruptibleFalse);if(fiber._interruptedCause)return failCause(fiber._interruptedCause)};var interruptible=(self)=>withFiber((fiber)=>{if(fiber.interruptible)return self;return setFiberInterruptible(fiber)??self});var uninterruptibleMask=(f)=>withFiber((fiber)=>{if(!fiber.interruptible)return f(identity);fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return f(interruptible)});var all=(arg,options)=>{if(isIterable(arg)){return options?.mode==="result"?forEach(arg,result,options):forEach(arg,identity,options)}else if(options?.discard){return options.mode==="result"?forEach(Object.values(arg),result,options):forEach(Object.values(arg),identity,options)}return suspend(()=>{const out={};return as(forEach(Object.entries(arg),([key,effect])=>map4(options?.mode==="result"?result(effect):effect,(value)=>{out[key]=value}),{discard:true,concurrency:options?.concurrency}),out)})};var whileLoop=makePrimitive({op:"While",[contA](value,fiber){this[args].step(value);if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid},[evaluate](fiber){if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid}});var forEach=dual((args2)=>typeof args2[1]==="function",(iterable,f,options)=>withFiber((parent)=>{const concurrencyOption=options?.concurrency==="inherit"?parent.getRef(CurrentConcurrency):options?.concurrency??1;const concurrency=concurrencyOption==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrencyOption);if(concurrency===1){return forEachSequential(iterable,f,options)}const items=fromIterable(iterable);let length=items.length;if(length===0){return options?.discard?void_:succeed3([])}const out=options?.discard?undefined:new Array(length);const eff=forEachConcurrent({f,out},items,{concurrency});return eff?as(eff,out):succeed3(out)}));var forEachSequential=(iterable,f,options)=>suspend(()=>{const out=options?.discard?undefined:[];const iterator=iterable[Symbol.iterator]();let state=iterator.next();let index=0;return as(whileLoop({while:()=>!state.done,body:()=>f(state.value,index++),step:(b)=>{if(out)out.push(b);state=iterator.next()}}),out)});var iterateEagerImpl=(options)=>{const onItem=options.onItem;const step=options.step;return(state,items,opts)=>{let index=opts?.start??0;const end=opts?.end??items.length;const concurrency=opts?.concurrency??1;const orderedStep=opts?.orderedStep===true&&concurrency>1;let done2=false;let parentFiber;let fibers;let resume;let interrupted=false;let terminal;let effect;let nextIndex=index;const exits=orderedStep?new Array(end):undefined;const failDefect=(error)=>{const defect=exitDie(error);terminal=defect;done2=true;interrupted=true;return fibers&&fibers.size>0?flatMap2(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>defect):defect};const runStep=(item,exit2,currentIndex)=>{if(!orderedStep)return step(state,item,exit2,currentIndex);if(terminal)return terminal;exits[currentIndex]=exit2;while(nextIndex<end){const nextExit=exits[nextIndex];if(nextExit===undefined)return;exits[nextIndex]=undefined;const index2=nextIndex++;const result2=step(state,items[index2],nextExit,index2);if(result2)return result2}};const go=()=>{let paused=false;for(;!terminal&&index<end;index++){const item=items[index];const eff=effect??onItem(state,item,index);if(effectIsExit(eff)){terminal=runStep(item,eff,index);if(terminal)break}else if(concurrency===1){return flatMap2(exit(eff),(exit2)=>{terminal=runStep(item,exit2,index);index++;return terminal??go()??void_})}else if(!parentFiber){return callback((cb)=>{parentFiber=getCurrentFiber();fibers=new Set;effect=eff;resume=cb;let result2;try{result2=go()}catch(error){return cb(failDefect(error))}if(result2)return cb(result2);return suspend(()=>{terminal=exitVoid;interrupted=true;return fibers?fiberInterruptAll(fibers):void_})})}else{effect=undefined;const fiber=forkUnsafe(parentFiber,eff,true,true,"inherit");if(fiber._exit){terminal=runStep(item,fiber._exit,index);if(terminal)break;continue}fibers.add(fiber);const currentIndex=index;fiber.addObserver((exit2)=>{fibers.delete(fiber);try{if(terminal){if(!interrupted&&exit2._tag==="Failure"){for(const reason of exit2.cause.reasons){if(reason._tag==="Interrupt")continue;else if(terminal._tag==="Failure"){terminal.cause.reasons.push(reason)}else{terminal=exitFailCause(causeFromReasons([reason]))}}}}else{const result2=runStep(item,exit2,currentIndex);if(result2){terminal=result2._tag==="Failure"?exitFailCause(causeFromReasons(result2.cause.reasons.slice())):result2;go()}}if(paused){const eff2=go();if(eff2)resume(eff2)}else if(done2&&fibers.size===0){resume(terminal??void_)}}catch(error){resume(failDefect(error))}});if(fibers.size<concurrency)continue;paused=true;index++;return}}done2=true;if(terminal){if(fibers&&fibers.size>0){const annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure"){return terminal}}else if(resume){if(!fibers){return exitVoid}else if(fibers.size===0){resume(void_)}}};return go()}};var iterateEager=()=>iterateEagerImpl;var forEachConcurrent=iterateEagerImpl({onItem(state,item,index){return state.f(item,index)},step(state,_,exit2,index){if(exit2._tag==="Failure")return exit2;else if(state.out){state.out[index]=exit2.value}}});var filterOrElse=dual(3,(self,predicate,orElse)=>flatMap2(self,(a)=>predicate(a)?succeed3(a):orElse(a)));var filter4=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>suspend(()=>{const out=[];return as(forEach(elements,(a,i)=>{const result2=predicate(a,i);if(typeof result2==="boolean"){if(result2)out.push(a);return void_}return map4(result2,(keep)=>{if(keep){out.push(a)}})},{discard:true,concurrency:options?.concurrency}),out)}));var forkUnsafe=(parent,effect,immediate=false,daemon=false,uninterruptible2=false)=>{const interruptible2=uninterruptible2==="inherit"?parent.interruptible:!uninterruptible2;const child=new FiberImpl(parent.context,interruptible2);if(immediate){child.evaluate(effect)}else{parent.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0)}if(!daemon&&!child._exit){parent.children().add(child);child.addObserver(()=>parent._children.delete(child))}return child};var forkIn=dual((args2)=>isEffect(args2[0]),(self,scope2,options)=>withFiber((parent)=>{const fiber=forkUnsafe(parent,self,options?.startImmediately,true,options?.uninterruptible);if(!fiber._exit){if(scope2.state._tag!=="Closed"){const key={};const finalizer=()=>withFiberId((interruptor)=>interruptor===fiber.id?void_:fiberInterrupt(fiber));scopeAddFinalizerUnsafe(scope2,key,finalizer);fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope2,key))}else{fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent))}}return succeed3(fiber)}));var forkScoped=dual((args2)=>isEffect(args2[0]),(self,options)=>flatMap2(scope,(scope2)=>forkIn(self,scope2,options)));var runForkWith=(context2)=>(effect,options)=>{const fiber=new FiberImpl(options?.scheduler?add(context2,Scheduler,options.scheduler):context2,options?.uninterruptible!==true);fiber.evaluate(effect);if(fiber._exit)return fiber;if(options?.signal){if(options.signal.aborted){fiber.interruptUnsafe()}else{const abort=()=>fiber.interruptUnsafe();options.signal.addEventListener("abort",abort,{once:true});fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}}if(options?.onFiberStart){options.onFiberStart(fiber)}return fiber};var fiberRunIn=dual(2,(self,scope2)=>{if(self._exit){return self}else if(scope2.state._tag==="Closed"){self.interruptUnsafe(self.id);return self}const key={};scopeAddFinalizerUnsafe(scope2,key,()=>fiberInterrupt(self));self.addObserver(()=>scopeRemoveFinalizerUnsafe(scope2,key));return self});var runFork=runForkWith(empty());var runPromiseExitWith=(context2)=>{const runFork2=runForkWith(context2);return(effect,options)=>{const fiber=runFork2(effect,options);return new Promise((resolve)=>{fiber.addObserver((exit2)=>resolve(exit2))})}};var runPromiseWith=(context2)=>{const runPromiseExit=runPromiseExitWith(context2);return(effect,options)=>runPromiseExit(effect,options).then((exit2)=>{if(exit2._tag==="Failure"){throw causeSquash(exit2.cause)}return exit2.value})};var runPromise=runPromiseWith(empty());var runSyncExitWith=(context2)=>{const runFork2=runForkWith(context2);return(effect)=>{if(effectIsExit(effect))return effect;const scheduler=new MixedScheduler("sync");const fiber=runFork2(effect,{scheduler});fiber._dispatcher?.flush();return fiber._exit??exitDie(new AsyncFiberError(fiber))}};var runSyncExit=runSyncExitWith(empty());var runSyncWith=(context2)=>{const runSyncExit2=runSyncExitWith(context2);return(effect)=>{const exit2=runSyncExit2(effect);if(exit2._tag==="Failure")throw causeSquash(exit2.cause);return exit2.value}};var runSync=runSyncWith(empty());var succeedTrue=succeed3(true);var succeedFalse=succeed3(false);class Latch{waiters=[];scheduled=false;_isOpen;constructor(isOpen){this._isOpen=isOpen}scheduleUnsafe(fiber){if(this.scheduled||this.waiters.length===0){return succeedTrue}this.scheduled=true;fiber.currentDispatcher.scheduleTask(this.flushWaiters,0);return succeedTrue}flushWaiters=()=>{this.scheduled=false;const waiters=this.waiters;this.waiters=[];for(let i=0;i<waiters.length;i++){waiters[i](exitVoid)}};open=withFiber((fiber)=>{if(this._isOpen)return succeedFalse;this._isOpen=true;return this.scheduleUnsafe(fiber)});release=withFiber((fiber)=>this._isOpen?succeedFalse:this.scheduleUnsafe(fiber));openUnsafe(){if(this._isOpen)return false;this._isOpen=true;this.flushWaiters();return true}await=callback((resume)=>{if(this._isOpen){return resume(void_)}this.waiters.push(resume);return sync(()=>{const index=this.waiters.indexOf(resume);if(index!==-1){this.waiters.splice(index,1)}})});closeUnsafe(){if(!this._isOpen)return false;this._isOpen=false;return true}close=sync(()=>this.closeUnsafe());whenOpen=(self)=>flatMap2(this.await,()=>self);isOpen(){return this._isOpen}}var makeLatchUnsafe=(open)=>new Latch(open??false);var bigint02=BigInt(0);var NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:false,status:{_tag:"Ended",startTime:bigint02,endTime:bigint02,exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}};var noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var filterDisablePropagation=(span)=>{if(!span)return none2();return get(span.annotations,DisablePropagation)?span._tag==="Span"?filterDisablePropagation(getOrUndefined(span.parent)):none2():some2(span)};var makeSpanUnsafe=(fiber,name,options)=>{const disablePropagation=!fiber.getRef(TracerEnabled)||options?.annotations&&get(options.annotations,DisablePropagation);const parent=options?.parent!==undefined?some2(options.parent):options?.root?none2():filterDisablePropagation(fiber.currentSpan);let span;if(disablePropagation){span=noopSpan({name,parent,annotations:add(options?.annotations??empty(),DisablePropagation,true)})}else{const tracer=fiber.getRef(Tracer);const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);const annotationsFromEnv=fiber.getRef(TracerSpanAnnotations);const linksFromEnv=fiber.getRef(TracerSpanLinks);const level=options?.level??fiber.getRef(CurrentTraceLevel);const links=options?.links!==undefined?[...linksFromEnv,...options.links]:linksFromEnv.slice();span=tracer.span({name,parent,annotations:options?.annotations??empty(),links,startTime:timingEnabled?clock.currentTimeNanosUnsafe():BigInt(0),kind:options?.kind??"internal",root:options?.root??isNone2(parent),sampled:options?.sampled??(isSome2(parent)&&parent.value.sampled===false?false:!isLogLevelGreaterThan(fiber.getRef(MinimumTraceLevel),level))});for(const[key,value]of Object.entries(annotationsFromEnv)){span.attribute(key,value)}if(options?.attributes!==undefined){for(const[key,value]of Object.entries(options.attributes)){span.attribute(key,value)}}}return span};var provideSpanStackFrame=(name,stack)=>{stack=typeof stack==="function"?stack:constUndefined;return updateService(CurrentStackFrame,(parent)=>({name,stack,parent}))};var useSpan=(name,...args2)=>{const options=args2.length===1?undefined:args2[0];const evaluate2=args2[args2.length-1];return withFiber((fiber)=>{const span=makeSpanUnsafe(fiber,name,options);const clock=fiber.getRef(ClockRef);return onExit(internalCall(()=>evaluate2(span)),(exit2)=>sync(()=>{if(span.status._tag==="Ended")return;span.end(clock.currentTimeNanosUnsafe(),exit2)}))})};var provideParentSpan=provideService(ParentSpan);var withParentSpan=function(){const dataFirst=isEffect(arguments[0]);const span=dataFirst?arguments[1]:arguments[0];let options=dataFirst?arguments[2]:arguments[1];let provideStackFrame=identity;if(span._tag==="Span"){options=addSpanStackTrace(options);provideStackFrame=provideSpanStackFrame(span.name,options?.captureStackTrace)}if(dataFirst){return provideParentSpan(provideStackFrame(arguments[0]),span)}return(self)=>provideParentSpan(provideStackFrame(self),span)};var ClockRef=Reference("effect/Clock",{defaultValue:()=>new ClockImpl});var MAX_TIMER_MILLIS=2**31-1;class ClockImpl{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=sync(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return processOrPerformanceNow()}currentTimeNanos=sync(()=>this.currentTimeNanosUnsafe());sleep(duration){return this.sleepMillis(toMillis(duration))}sleepMillis(millis2){if(millis2<=0)return yieldNow;else if(!Number.isFinite(millis2))return never;return callback((resume)=>{const continuation=millis2>MAX_TIMER_MILLIS?this.sleepMillis(millis2-MAX_TIMER_MILLIS):void_;const handle=setTimeout(()=>resume(continuation),Math.min(millis2,MAX_TIMER_MILLIS));return sync(()=>clearTimeout(handle))})}}var performanceNowNanos=function(){const bigint1e6=BigInt(1e6);if(typeof performance==="undefined"||typeof performance.now==="undefined"){return()=>BigInt(Date.now())*bigint1e6}let origin;return()=>{origin??=BigInt(Date.now())*bigint1e6-BigInt(Math.round(performance.now()*1e6));return origin+BigInt(Math.round(performance.now()*1e6))}}();var processOrPerformanceNow=function(){const processHrtime=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:undefined;if(!processHrtime){return performanceNowNanos}const origin=BigInt(Date.now())*BigInt(1e6)-processHrtime.bigint();return()=>origin+processHrtime.bigint()}();var clockWith=(f)=>withFiber((fiber)=>f(fiber.getRef(ClockRef)));var sleep=(duration)=>clockWith((clock)=>clock.sleep(fromInputUnsafe(duration)));var currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis);var TimeoutErrorTypeId="~effect/Cause/TimeoutError";var isTimeoutError=(u)=>hasProperty(u,TimeoutErrorTypeId);class TimeoutError extends TaggedError("TimeoutError"){[TimeoutErrorTypeId]=TimeoutErrorTypeId;constructor(message){super({message})}}var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var ConsoleRef=Reference("effect/Console/CurrentConsole",{defaultValue:()=>globalThis.console});var logLevelToOrder=(level)=>{switch(level){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}};var LogLevelOrder=mapInput(Number2,logLevelToOrder);var isLogLevelGreaterThan=isGreaterThan(LogLevelOrder);var CurrentLoggers=Reference("effect/Loggers/CurrentLoggers",{defaultValue:()=>new Set([defaultLogger,tracerLogger])});var LogToStderr=Reference("effect/Logger/LogToStderr",{defaultValue:constFalse});var LoggerTypeId="~effect/Logger";var LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}};var loggerMake=(log)=>{const self=Object.create(LoggerProto);self.log=log;return self};var formatLabel=(key)=>key.replace(/[\s="]/g,"_");var formatLogSpan=(self,now)=>{const label=formatLabel(self[0]);return`${label}=${now-self[1]}ms`};var logWithLevel=(level)=>(...message)=>{let cause=undefined;for(let i=0,len=message.length;i<len;i++){const msg=message[i];if(isCause(msg)){if(cause){message.splice(i,1)}else{message=message.slice(0,i).concat(message.slice(i+1))}cause=cause?causeFromReasons(cause.reasons.concat(msg.reasons)):msg;i--}}if(cause===undefined){cause=causeEmpty}return withFiber((fiber)=>{const logLevel=level??fiber.currentLogLevel;if(isLogLevelGreaterThan(fiber.minimumLogLevel,logLevel)){return void_}const clock=fiber.getRef(ClockRef);const loggers=fiber.getRef(CurrentLoggers);if(loggers.size>0){const date=new Date(clock.currentTimeMillisUnsafe());for(const logger of loggers){logger.log({cause,fiber,date,logLevel,message})}}return void_})};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"};var logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`;var defaultLogger=loggerMake(({cause,date,fiber,logLevel,message})=>{const message_=Array.isArray(message)?message.slice():[message];if(cause.reasons.length>0){message_.push(causePretty(cause))}const now=date.getTime();const spans=fiber.getRef(CurrentLogSpans);let spanString="";for(const span of spans){spanString+=` ${formatLogSpan(span,now)}`}const annotations=fiber.getRef(CurrentLogAnnotations);if(Object.keys(annotations).length>0){message_.push(annotations)}const console2=fiber.getRef(ConsoleRef);const log=fiber.getRef(LogToStderr)?console2.error:console2.log;log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`,...message_)});var tracerLogger=loggerMake(({cause,fiber,logLevel,message})=>{const clock=fiber.getRef(ClockRef);const annotations=fiber.getRef(CurrentLogAnnotations);const span=fiber.currentSpan;if(span===undefined||span._tag==="ExternalSpan")return;const attributes={};for(const[key,value]of Object.entries(annotations)){attributes[key]=value}attributes["effect.fiberId"]=fiber.id;attributes["effect.logLevel"]=logLevel.toUpperCase();if(cause.reasons.length>0){attributes["effect.cause"]=causePretty(cause)}span.event(toStringUnknown(Array.isArray(message)&&message.length===1?message[0]:message),clock.currentTimeNanosUnsafe(),attributes)});var succeed4=exitSucceed;var failCause2=exitFailCause;var fail4=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess;var TypeId5="~effect/Deferred";var DeferredProto={[TypeId5]:{_A:identity,_E:identity},pipe(){return pipeArguments(this,arguments)}};var makeUnsafe2=()=>{const self=Object.create(DeferredProto);self.resumes=undefined;self.effect=undefined;return self};var _await=(self)=>callback((resume)=>{if(self.effect)return resume(self.effect);self.resumes??=[];self.resumes.push(resume);return sync(()=>{const index=self.resumes.indexOf(resume);self.resumes.splice(index,1)})});var completeWith=dual(2,(self,effect)=>sync(()=>doneUnsafe(self,effect)));var done2=completeWith;var isDone2=(self)=>sync(()=>isDoneUnsafe(self));var isDoneUnsafe=(self)=>self.effect!==undefined;var doneUnsafe=(self,effect)=>{if(self.effect)return false;self.effect=effect;if(self.resumes){for(let i=0;i<self.resumes.length;i++){self.resumes[i](effect)}self.resumes=undefined}return true};var MinimumLogLevel2=MinimumLogLevel;var Scope=scopeTag;var makeUnsafe3=scopeMakeUnsafe;var provide=provideScope;var addFinalizerExit=scopeAddFinalizerExit;var addFinalizer2=scopeAddFinalizer;var forkUnsafe2=scopeForkUnsafe;var close=scopeClose;var TypeId6="~effect/Layer";var MemoMapTypeId="~effect/Layer/MemoMap";var memoMapReuse=(entry,scope2)=>{entry.observers++;return andThen(scopeAddFinalizerExit(scope2,(exit2)=>entry.finalizer(exit2)),entry.effect)};var LayerProto={[TypeId6]:{_ROut:identity,_E:identity,_RIn:identity},pipe(){return pipeArguments(this,arguments)}};var fromBuildUnsafe=(build)=>{const self=Object.create(LayerProto);self.build=build;return self};var fromBuild=(build)=>fromBuildUnsafe((memoMap,scope2)=>{const layerScope=forkUnsafe2(scope2);return onExit(build(memoMap,layerScope),(exit2)=>exit2._tag==="Failure"?close(layerScope,exit2):void_)});var fromBuildMemo=(build)=>{const self=fromBuild((memoMap,scope2)=>memoMap.getOrElseMemoize(self,scope2,build));return self};var memoMapBuild=(memoMap,layer,scope2,build)=>{const layerScope=makeUnsafe3();const deferred=makeUnsafe2();const entry={observers:1,effect:_await(deferred),finalizer:(exit2)=>suspend(()=>{entry.observers--;if(entry.observers===0){memoMap.map.delete(layer);return close(layerScope,exit2)}return void_})};memoMap.map.set(layer,entry);return scopeAddFinalizerExit(scope2,entry.finalizer).pipe(flatMap2(()=>build(memoMap,layerScope)),onExit((exit2)=>{entry.effect=exit2;return done2(deferred,exit2)}))};class MemoMapImpl{get[MemoMapTypeId](){return MemoMapTypeId}parent;constructor(parent){this.parent=parent}map=new Map;get(layer,scope2){const local=this.map.get(layer);if(local){return memoMapReuse(local,scope2)}return this.parent?.get(layer,scope2)}getOrElseMemoize(layer,scope2,build){const existing=this.get(layer,scope2);if(existing){return existing}return memoMapBuild(this,layer,scope2,build)}}var makeMemoMapUnsafe=()=>new MemoMapImpl;var forkMemoMapUnsafe=(parent)=>new MemoMapImpl(parent);class CurrentMemoMap extends Service()("effect/Layer/CurrentMemoMap"){static forkOrCreate(self){const current=getOrUndefined2(self,CurrentMemoMap);return current?forkMemoMapUnsafe(current):makeMemoMapUnsafe()}}var buildWithMemoMap=dual(3,(self,memoMap,scope2)=>provideService(map4(self.build(memoMap,scope2),add(CurrentMemoMap,memoMap)),CurrentMemoMap,memoMap));var buildWithScope=dual(2,(self,scope2)=>withFiber((fiber)=>buildWithMemoMap(self,CurrentMemoMap.forkOrCreate(fiber.context),scope2)));var succeed5=function(){if(arguments.length===1){return(resource)=>succeedContext(make3(arguments[0],resource))}return succeedContext(make3(arguments[0],arguments[1]))};var succeedContext=(context2)=>fromBuildUnsafe(constant(succeed3(context2)));var effect=function(){if(arguments.length===1){return(effect2)=>effectImpl(arguments[0],effect2)}return effectImpl(arguments[0],arguments[1])};var effectImpl=(service,effect2)=>effectContext(map4(effect2,(value)=>make3(service,value)));var effectContext=(effect2)=>fromBuildMemo((_,scope2)=>provide(effect2,scope2));var effectDiscard=(effect2)=>effectContext(as(effect2,empty()));var mergeAllEffect=(layers,memoMap,scope2)=>{const parentScope=forkUnsafe2(scope2,"parallel");return forEach(layers,(layer)=>layer.build(memoMap,forkUnsafe2(parentScope,"sequential")),{concurrency:layers.length}).pipe(map4((context2)=>mergeAll(...context2)))};var mergeAll2=(...layers)=>fromBuild((memoMap,scope2)=>mergeAllEffect(layers,memoMap,scope2));var merge2=dual(2,(self,that)=>mergeAll2(self,...Array.isArray(that)?that:[that]));var provideWith=(self,that,f)=>fromBuild((memoMap,scope2)=>flatMap2(Array.isArray(that)?mergeAllEffect(that,memoMap,scope2):that.build(memoMap,scope2),(context2)=>self.build(memoMap,scope2).pipe(provideContext(context2),map4((merged)=>f(merged,context2)))));var provide2=dual(2,(self,that)=>provideWith(self,that,identity));var provideMerge=dual(2,(self,that)=>provideWith(self,that,(self2,that2)=>merge(that2,self2)));var isCause2=isCause;var isReason=isCauseReason;var isFailReason2=isFailReason;var fromReasons=causeFromReasons;var empty4=causeEmpty;var fail5=causeFail;var die2=causeDie;var interrupt2=causeInterrupt;var makeFailReason=(error)=>new Fail(error);var makeDieReason=(defect)=>new Die(defect);var makeInterruptReason2=makeInterruptReason;var hasInterruptsOnly2=hasInterruptsOnly;var map5=causeMap;var combine2=causeCombine;var squash=causeSquash;var findError2=findError;var hasInterrupts2=hasInterrupts;var isDone3=isDone;var Done2=Done;var done3=done;var isTimeoutError2=isTimeoutError;var UnknownError2=UnknownError;var Clock=ClockRef;var currentTimeMillis2=currentTimeMillis;var TypeId7="~effect/time/DateTime";var TimeZoneTypeId="~effect/time/DateTime/TimeZone";var Proto2={[TypeId7]:TypeId7,pipe(){return pipeArguments(this,arguments)},[NodeInspectSymbol](){return this.toString()},toJSON(){return toDateUtc(this).toJSON()}};var ProtoUtc={...Proto2,_tag:"Utc",[symbol](){return number(this.epochMilliseconds)},[symbol2](that){return isDateTime(that)&&that._tag==="Utc"&&this.epochMilliseconds===that.epochMilliseconds},toString(){return`DateTime.Utc(${toDateUtc(this).toJSON()})`}};var ProtoZoned={...Proto2,_tag:"Zoned",[symbol](){return combine(number(this.epochMilliseconds))(hash(this.zone))},[symbol2](that){return isDateTime(that)&&that._tag==="Zoned"&&this.epochMilliseconds===that.epochMilliseconds&&equals(this.zone,that.zone)},toString(){return`DateTime.Zoned(${formatIsoZoned(this)})`}};var ProtoTimeZone={[TimeZoneTypeId]:TimeZoneTypeId,[NodeInspectSymbol](){return this.toString()}};var ProtoTimeZoneNamed={...ProtoTimeZone,_tag:"Named",[symbol](){return string(`Named:${this.id}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Named"&&this.id===that.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:"TimeZone",_tag:"Named",id:this.id}}};var ProtoTimeZoneOffset={...ProtoTimeZone,_tag:"Offset",[symbol](){return string(`Offset:${this.offset}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Offset"&&this.offset===that.offset},toString(){return`TimeZone.Offset(${offsetToString(this.offset)})`},toJSON(){return{_id:"TimeZone",_tag:"Offset",offset:this.offset}}};var isDateTime=(u)=>hasProperty(u,TypeId7);var isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var makeUtc=(epochMillis)=>{const self=Object.create(ProtoUtc);self.epochMilliseconds=epochMillis;Object.defineProperty(self,"partsUtc",{value:undefined,enumerable:false,writable:true});return self};var minEpochMillis=-8640000000000000+12*60*60*1000;var maxEpochMillis=8640000000000000-14*60*60*1000;var now=map4(currentTimeMillis2,makeUtc);var toDateUtc=(self)=>new Date(self.epochMilliseconds);var toDate=(self)=>{if(self._tag==="Utc"){return new Date(self.epochMilliseconds)}else if(self.zone._tag==="Offset"){return new Date(self.epochMilliseconds+self.zone.offset)}else if(self.adjustedEpochMilliseconds!==undefined){return new Date(self.adjustedEpochMilliseconds)}const parts=self.zone.format.formatToParts(self.epochMilliseconds).filter((_)=>_.type!=="literal");const date=new Date(0);date.setUTCFullYear(Number(parts[2].value),Number(parts[0].value)-1,Number(parts[1].value));date.setUTCHours(Number(parts[3].value),Number(parts[4].value),Number(parts[5].value),Number(parts[6].value));self.adjustedEpochMilliseconds=date.getTime();return date};var zonedOffset=(self)=>{const date=toDate(self);return date.getTime()-toEpochMillis(self)};var offsetToString=(offset)=>{const abs=Math.abs(offset);let hours2=Math.floor(abs/(60*60*1000));let minutes2=Math.round(abs%(60*60*1000)/(60*1000));if(minutes2===60){hours2+=1;minutes2=0}return`${offset<0?"-":"+"}${String(hours2).padStart(2,"0")}:${String(minutes2).padStart(2,"0")}`};var zonedOffsetIso=(self)=>offsetToString(zonedOffset(self));var toEpochMillis=(self)=>self.epochMilliseconds;var constDayMillis=24*60*60*1000;var formatIso=(self)=>toDateUtc(self).toISOString();var formatIsoOffset=(self)=>{const date=toDate(self);return self._tag==="Utc"?date.toISOString():`${date.toISOString().slice(0,-1)}${zonedOffsetIso(self)}`};var formatIsoZoned=(self)=>self.zone._tag==="Offset"?formatIsoOffset(self):`${formatIsoOffset(self)}[${self.zone.id}]`;var Number3=globalThis.Number;var Order2=Number2;var round=dual(2,(self,precision)=>{const factor=Math.pow(10,precision);return Math.round(self*factor)/factor});var catchDone=dual(2,(effect2,f)=>catchCauseFilter(effect2,filterDoneLeftover,(l)=>f(l)));var isDoneCause=(cause)=>cause.reasons.some(isDoneFailure);var isDoneFailure=(failure)=>failure._tag==="Fail"&&isDone3(failure.error);var filterDone=composePassthrough(findError2,(e)=>isDone3(e)?succeed2(e):fail2(e));var filterDoneLeftover=composePassthrough(findError2,(e)=>isDone3(e)?succeed2(e.value):fail2(e));var doneExitFromCause=(cause)=>{const halt=filterDone(cause);return!isFailure2(halt)?succeed4(halt.success.value):failCause2(halt.failure)};var matchEffect2=dual(2,(self,options)=>matchCauseEffect(self,{onSuccess:options.onSuccess,onFailure:(cause)=>{const halt=filterDone(cause);return!isFailure2(halt)?options.onDone(halt.success.value):options.onFailure(halt.failure)}}));var TypeId8="~effect/Schedule";var CurrentMetadata=Reference("effect/Schedule/CurrentMetadata",{defaultValue:constant({input:undefined,output:undefined,duration:zero,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})});var ScheduleProto={[TypeId8]:{_Out:identity,_In:identity,_Env:identity},pipe(){return pipeArguments(this,arguments)}};var isSchedule=(u)=>hasProperty(u,TypeId8);var fromStep=(step)=>{const self=Object.create(ScheduleProto);self.step=step;return self};var metadataFn=()=>{let n=0;let previous;let start;return(now2,input)=>{if(start===undefined)start=now2;const elapsed=now2-start;const elapsedSincePrevious=previous===undefined?0:now2-previous;previous=now2;return{input,attempt:++n,start,now:now2,elapsed,elapsedSincePrevious}}};var fromStepWithMetadata=(step)=>fromStep(map4(step,(f)=>{const meta=metadataFn();return(now2,input)=>f(meta(now2,input))}));var toStep=(schedule)=>catchCause(schedule.step,(cause)=>succeed3(()=>failCause(cause)));var toStepWithMetadata=(schedule)=>clockWith((clock)=>map4(toStep(schedule),(step)=>{const metaFn=metadataFn();return(input)=>suspend(()=>{const now2=clock.currentTimeMillisUnsafe();return flatMap2(step(now2,input),([output,duration])=>{const meta=metaFn(now2,input);meta.output=output;meta.duration=duration;return as(sleep(duration),meta)})})}));var passthrough=(self)=>fromStep(map4(toStep(self),(step)=>(now2,input)=>matchEffect2(step(now2,input),{onSuccess:(result2)=>succeed3([input,result2[1]]),onFailure:failCause,onDone:()=>done3(input)})));var spaced=(duration)=>{const decoded=fromInputUnsafe(duration);return fromStepWithMetadata(succeed3((meta)=>succeed3([meta.attempt-1,decoded])))};var while_=dual(2,(self,predicate)=>fromStep(map4(toStep(self),(step)=>{const meta=metadataFn();return(now2,input)=>flatMap2(step(now2,input),(result2)=>{const[output,duration]=result2;const eff=predicate({...meta(now2,input),output,duration});return flatMap2(isEffect(eff)?eff:succeed3(eff),(check)=>check?succeed3(result2):done3(output))})})));var forever2=spaced(zero);var provideLayer=(self,layer,options)=>scopedWith((scope2)=>flatMap2(options?.local?buildWithMemoMap(layer,makeMemoMapUnsafe(),scope2):buildWithScope(layer,scope2),(context2)=>provideContext(self,context2)));var provide3=dual((args2)=>isEffect(args2[0]),(self,source,options)=>isContext(source)?provideContext(self,source):provideLayer(self,Array.isArray(source)?mergeAll2(...source):source,options));var repeatOrElse=dual(3,(self,schedule,orElse)=>flatMap2(toStepWithMetadata(schedule),(step)=>{let meta=CurrentMetadata.defaultValue();return catch_(forever(tap(flatMap2(suspend(()=>provideService(self,CurrentMetadata,meta)),step),(meta_)=>sync(()=>{meta=meta_})),{disableYield:true}),(error)=>isDone(error)?succeed3(error.value):orElse(error,meta.attempt===0?none2():some2(meta)))}));var retryOrElse=dual(3,(self,policy,orElse)=>flatMap2(toStepWithMetadata(policy),(step)=>{let meta=CurrentMetadata.defaultValue();let lastError;const loop=catch_(suspend(()=>provideService(self,CurrentMetadata,meta)),(error)=>{lastError=error;return flatMap2(step(error),(meta_)=>{meta=meta_;return loop})});return catchDone(loop,(out)=>internalCall(()=>orElse(lastError,out)))}));var repeat=dual(2,(self,options)=>{const schedule=typeof options==="function"?options(identity):isSchedule(options)?options:buildFromOptions(options);return repeatOrElse(self,schedule,fail3)});var retry=dual(2,(self,options)=>{const schedule=typeof options==="function"?options(identity):isSchedule(options)?options:buildFromOptions(options);return retryOrElse(self,schedule,fail3)});var passthroughForever=passthrough(forever2);var buildFromOptions=(options)=>{let schedule=options.schedule?passthrough(options.schedule):passthroughForever;if(options.while){schedule=while_(schedule,({input})=>{const applied=options.while(input);return isEffect(applied)?applied:succeed3(applied)})}if(options.until){schedule=while_(schedule,({input})=>{const applied=options.until(input);return isEffect(applied)?map4(applied,(b)=>!b):succeed3(!applied)})}if(options.times!==undefined){schedule=while_(schedule,({attempt})=>succeed3(attempt<=options.times))}return schedule};var isEffect2=isEffect;var all2=all;var forEach2=forEach;var whileLoop2=whileLoop;var promise2=promise;var tryPromise2=tryPromise;var succeed6=succeed3;var succeedNone2=succeedNone;var succeedSome2=succeedSome;var suspend2=suspend;var sync2=sync;var void_3=void_;var callback2=callback;var gen2=gen;var fail6=fail3;var failCause3=failCause;var failCauseSync2=failCauseSync;var die3=die;var try_3=try_2;var withFiber2=withFiber;var fromResult2=fromResult;var flatMap3=flatMap2;var andThen2=andThen;var tap2=tap;var result2=result;var exit2=exit;var map6=map4;var as2=as;var asVoid2=asVoid;var zipWith2=zipWith;var catch_2=catch_;var catchTag2=catchTag;var catchTags2=catchTags;var catchCause2=catchCause;var catchIf2=catchIf;var catchFilter2=catchFilter;var mapError3=mapError2;var orDie2=orDie;var tapError2=tapError;var tapCause2=tapCause;var retry2=retry;var ignore2=ignore;var timeout2=timeout;var timeoutOrElse2=timeoutOrElse;var delay2=delay;var sleep2=sleep;var raceFirst2=raceFirst;var filter5=filter4;var filterOrElse2=filterOrElse;var filterOrFail2=filterOrFail;var match6=match5;var matchCauseEffect2=matchCauseEffect;var matchEffect3=matchEffect;var context2=context;var contextWith2=contextWith;var provide4=provide3;var provideContext2=provideContext;var serviceOption2=serviceOption;var updateContext2=updateContext;var provideService2=provideService;var provideServiceEffect2=provideServiceEffect;var scope2=scope;var scoped2=scoped;var scopedWith2=scopedWith;var acquireRelease2=acquireRelease;var addFinalizer3=addFinalizer;var ensuring2=ensuring;var onError2=onError;var onExit2=onExit;var cached2=cached;var interrupt3=interrupt;var onInterrupt2=onInterrupt;var uninterruptible2=uninterruptible;var uninterruptibleMask2=uninterruptibleMask;var forever3=forever;var repeat2=repeat;var useSpan2=useSpan;var withParentSpan2=withParentSpan;var forkIn2=forkIn;var forkScoped2=forkScoped;var runFork2=runFork;var runForkWith2=runForkWith;var runPromise2=runPromise;var runSync2=runSync;var runSyncExit2=runSyncExit;var fnUntraced2=fnUntraced;var fn2=fn;var clockWith2=clockWith;var logError=logWithLevel("Error");var effectify=(fn3,onError3,onSyncError)=>(...args2)=>callback2((resume)=>{try{fn3(...args2,(err,result3)=>{if(err){resume(fail6(onError3?onError3(err,args2):err))}else{resume(succeed6(result3))}})}catch(err){resume(onSyncError?fail6(onSyncError(err,args2)):die3(err))}});var mapEager2=mapEager;var mapErrorEager2=mapErrorEager;var mapBothEager2=mapBothEager;var flatMapEager2=flatMapEager;var fnUntracedEager2=fnUntracedEager;function set(self,key,value){if(key==="__proto__"){Object.defineProperty(self,key,{value,writable:true,enumerable:true,configurable:true})}else{self[key]=value}return self}function resolve(ast){return ast.checks?ast.checks[ast.checks.length-1].annotations:ast.annotations}function resolveAt(key){return(ast)=>resolve(ast)?.[key]}var resolveIdentifier=resolveAt("identifier");var resolveDescription=resolveAt("description");var resolveBrands=resolveAt("brands");var getExpected=memoize((ast)=>{const identifier2=resolveIdentifier(ast);if(typeof identifier2==="string")return identifier2;return ast.getExpected(getExpected)});var redactedRegistry=new WeakMap;var value=(self)=>{if(redactedRegistry.has(self)){return redactedRegistry.get(self)}else{throw new Error("Unable to get redacted value"+(self.label?` with label: "${self.label}"`:""))}};var stringOrRedacted=(val)=>typeof val==="string"?val:value(val);var TypeId9="~effect/data/Redacted";var isRedacted=(u)=>hasProperty(u,TypeId9);var make6=(value2,options)=>{const self=Object.create(Proto3);if(options?.label){self.label=options.label}redactedRegistry.set(self,value2);return self};var Proto3={[TypeId9]:{_A:(_)=>_},label:undefined,...PipeInspectableProto,toJSON(){return this.toString()},toString(){return`<redacted${isString(this.label)?":"+this.label:""}>`},[symbol](){return hash(redactedRegistry.get(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}};var value2=value;var makeEquivalence4=(isEquivalent)=>make((x,y)=>isEquivalent(value2(x),value2(y)));var TypeId10="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId10)}class Base{[TypeId10]=TypeId10;toString(){return defaultFormatter(this)}}class Filter extends Base{_tag="Filter";actual;filter;issue;constructor(actual,filter6,issue){super();this.actual=actual;this.filter=filter6;this.issue=issue}}class Encoding extends Base{_tag="Encoding";ast;actual;issue;constructor(ast,actual,issue){super();this.ast=ast;this.actual=actual;this.issue=issue}}class Pointer extends Base{_tag="Pointer";path;issue;constructor(path,issue){super();this.path=path;this.issue=issue}}class MissingKey extends Base{_tag="MissingKey";annotations;constructor(annotations){super();this.annotations=annotations}}class UnexpectedKey extends Base{_tag="UnexpectedKey";ast;actual;constructor(ast,actual){super();this.ast=ast;this.actual=actual}}class Composite extends Base{_tag="Composite";ast;actual;issues;constructor(ast,actual,issues){super();this.ast=ast;this.actual=actual;this.issues=issues}}class InvalidType extends Base{_tag="InvalidType";ast;actual;constructor(ast,actual){super();this.ast=ast;this.actual=actual}}class InvalidValue extends Base{_tag="InvalidValue";actual;annotations;constructor(actual,annotations){super();this.actual=actual;this.annotations=annotations}}class Forbidden extends Base{_tag="Forbidden";actual;annotations;constructor(actual,annotations){super();this.actual=actual;this.annotations=annotations}}class AnyOf extends Base{_tag="AnyOf";ast;actual;issues;constructor(ast,actual,issues){super();this.ast=ast;this.actual=actual;this.issues=issues}}class OneOf extends Base{_tag="OneOf";ast;actual;successes;constructor(ast,actual,successes){super();this.ast=ast;this.actual=actual;this.successes=successes}}function makeFilterIssue(input,entry){if(isIssue(entry)){return entry}if(typeof entry==="string"){return new InvalidValue(some2(input),{message:entry})}const inner=typeof entry.issue==="string"?new InvalidValue(some2(input),{message:entry.issue}):entry.issue;return new Pointer(entry.path,inner)}function makeSingle(input,out){if(out===undefined){return}if(typeof out==="boolean"){return out?undefined:new InvalidValue(some2(input))}return makeFilterIssue(input,out)}function make7(input,ast,out){if(Array.isArray(out)){if(isReadonlyArrayNonEmpty(out)){if(out.length===1){return makeFilterIssue(input,out[0])}return new Composite(ast,some2(input),map3(out,(entry)=>makeFilterIssue(input,entry)))}return}return makeSingle(input,out)}var defaultLeafHook=(issue)=>{const message=findMessage(issue);if(message!==undefined)return message;switch(issue._tag){case"InvalidType":return getExpectedMessage(getExpected(issue.ast),formatOption(issue.actual));case"InvalidValue":return`Invalid data ${formatOption(issue.actual)}`;case"MissingKey":return"Missing key";case"UnexpectedKey":return`Unexpected key with value ${format(issue.actual)}`;case"Forbidden":return"Forbidden operation";case"OneOf":return`Expected exactly one member to match the input ${format(issue.actual)}`}};var defaultCheckHook=(issue)=>{return findMessage(issue.issue)??findMessage(issue)};function getExpectedMessage(expected,actual){return`Expected ${expected}, got ${actual}`}function toDefaultIssues(issue,path,leafHook,checkHook){switch(issue._tag){case"Filter":{const message=checkHook(issue);if(message!==undefined){return[{path,message}]}switch(issue.issue._tag){case"InvalidValue":return[{path,message:getExpectedMessage(formatCheck(issue.filter),format(issue.actual))}];default:return toDefaultIssues(issue.issue,path,leafHook,checkHook)}}case"Encoding":return toDefaultIssues(issue.issue,path,leafHook,checkHook);case"Pointer":return toDefaultIssues(issue.issue,[...path,...issue.path],leafHook,checkHook);case"Composite":return issue.issues.flatMap((issue2)=>toDefaultIssues(issue2,path,leafHook,checkHook));case"AnyOf":{const message=findMessage(issue);if(issue.issues.length===0){if(message!==undefined)return[{path,message}];const expected=getExpectedMessage(getExpected(issue.ast),format(issue.actual));return[{path,message:expected}]}return issue.issues.flatMap((issue2)=>toDefaultIssues(issue2,path,leafHook,checkHook))}default:return[{path,message:leafHook(issue)}]}}function formatCheck(check){const expected=check.annotations?.expected;if(typeof expected==="string")return expected;switch(check._tag){case"Filter":return"<filter>";case"FilterGroup":return check.checks.map((check2)=>formatCheck(check2)).join(" & ")}}function makeFormatterDefault(){return(issue)=>toDefaultIssues(issue,[],defaultLeafHook,defaultCheckHook).map(formatDefaultIssue).join(`
180
180
  `)}var defaultFormatter=makeFormatterDefault();function formatDefaultIssue(issue){let out=issue.message;if(issue.path&&issue.path.length>0){const path=formatPath(issue.path);out+=`
181
181
  at ${path}`}return out}function findMessage(issue){switch(issue._tag){case"InvalidType":case"OneOf":case"Composite":case"AnyOf":return getMessageAnnotation(issue.ast.annotations);case"InvalidValue":case"Forbidden":return getMessageAnnotation(issue.annotations);case"MissingKey":return getMessageAnnotation(issue.annotations,"messageMissingKey");case"UnexpectedKey":return getMessageAnnotation(issue.ast.annotations,"messageUnexpectedKey");case"Filter":return getMessageAnnotation(issue.filter.annotations);case"Encoding":return findMessage(issue.issue)}}function getMessageAnnotation(annotations,type="message"){const message=annotations?.[type];if(typeof message==="string")return message}function formatOption(actual){if(isNone2(actual))return"no value provided";return format(actual.value)}function redact2(issue){switch(issue._tag){case"MissingKey":return issue;case"Forbidden":return new Forbidden(map(issue.actual,make6),issue.annotations);case"Filter":return new Filter(make6(issue.actual),issue.filter,redact2(issue.issue));case"Pointer":return new Pointer(issue.path,redact2(issue.issue));case"Encoding":case"InvalidType":case"InvalidValue":case"Composite":return new InvalidValue(map(issue.actual,make6));case"AnyOf":case"OneOf":case"UnexpectedKey":return new InvalidValue(some2(make6(issue.actual)))}}function getSchemaIssue(cause){let issue;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error)){return}issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){const issue=getSchemaIssue(cause);if(issue===undefined){throw new Error(message,{cause})}return issue}var now2=now;var formatIso2=formatIso;var EncodingErrorTypeId="~effect/encoding/EncodingError";class EncodingError extends TaggedError2("EncodingError"){[EncodingErrorTypeId]=EncodingErrorTypeId}var encodeBase64=(input)=>typeof input==="string"?base64EncodeUint8Array(encoder.encode(input)):base64EncodeUint8Array(input);var decodeBase64=(str)=>{const stripped=stripCrlf(str);const length=stripped.length;if(length%4!==0){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Length must be a multiple of 4, but is ${length}`}))}const index=stripped.indexOf("=");if(index!==-1&&(index<length-2||index===length-2&&stripped[length-1]!=="=")){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Found a '=' character, but it is not at the end`}))}try{const missingOctets=stripped.endsWith("==")?2:stripped.endsWith("=")?1:0;const result3=new Uint8Array(3*(length/4)-missingOctets);for(let i=0,j=0;i<length;i+=4,j+=3){const buffer=getBase64Code(stripped.charCodeAt(i))<<18|getBase64Code(stripped.charCodeAt(i+1))<<12|getBase64Code(stripped.charCodeAt(i+2))<<6|getBase64Code(stripped.charCodeAt(i+3));result3[j]=buffer>>16;result3[j+1]=buffer>>8&255;result3[j+2]=buffer&255}return succeed2(result3)}catch(e){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:e instanceof Error?e.message:"Invalid input"}))}};var encoder=new TextEncoder;var stripCrlf=(str)=>str.replace(/[\n\r]/g,"");var base64EncodeUint8Array=(bytes)=>{const length=bytes.length;let result3="";let i;for(i=2;i<length;i+=3){result3+=base64abc[bytes[i-2]>>2];result3+=base64abc[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result3+=base64abc[(bytes[i-1]&15)<<2|bytes[i]>>6];result3+=base64abc[bytes[i]&63]}if(i===length+1){result3+=base64abc[bytes[i-2]>>2];result3+=base64abc[(bytes[i-2]&3)<<4];result3+="=="}if(i===length){result3+=base64abc[bytes[i-2]>>2];result3+=base64abc[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result3+=base64abc[(bytes[i-1]&15)<<2];result3+="="}return result3};function getBase64Code(charCode){if(charCode>=base64codes.length){throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)}const code=base64codes[charCode];if(code===255){throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)}return code}var base64abc=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"];var base64codes=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];class Getter extends Class{run;constructor(run){super();this.run=run}map(f){return new Getter((oe,options)=>this.run(oe,options).pipe(mapEager2(map(f))))}compose(other){if(isPassthrough(this)){return other}if(isPassthrough(other)){return this}return new Getter((oe,options)=>this.run(oe,options).pipe(flatMapEager2((ot)=>other.run(ot,options))))}}function fail7(f){return new Getter((oe)=>fail6(f(oe)))}function forbidden(message){return fail7((oe)=>new Forbidden(oe,{message:message(oe)}))}var passthrough_=new Getter(succeed6);function isPassthrough(getter){return getter.run===passthrough_.run}function passthrough2(){return passthrough_}function onSome(f){return new Getter((oe,options)=>isNone2(oe)?succeedNone2:f(oe.value,options))}function transform(f){return transformOptional(map(f))}function transformOrFail(f){return onSome((e,options)=>f(e,options).pipe(mapEager2(some2)))}function transformOptional(f){return new Getter((oe)=>succeed6(f(oe)))}function withDefault(defaultValue){return new Getter((o)=>{const filtered=filter(o,isNotUndefined);return isSome2(filtered)?succeed6(filtered):mapEager2(defaultValue,some2)})}function String2(){return transform(globalThis.String)}function Number4(){return transform(globalThis.Number)}function Date3(){return transform((u)=>new globalThis.Date(u))}function parseJson(options){return onSome((input)=>try_3({try:()=>some2(JSON.parse(input,options?.reviver)),catch:(e)=>new InvalidValue(some2(input),{message:globalThis.String(e)})}))}function stringifyJson(options){return onSome((input)=>try_3({try:()=>some2(JSON.stringify(input,options?.replacer,options?.space)),catch:(e)=>new InvalidValue(some2(input),{message:globalThis.String(e)})}))}function encodeBase642(){return transform(encodeBase64)}function decodeBase642(){return transformOrFail((input)=>mapErrorEager2(fromResult2(decodeBase64(input)),(e)=>new InvalidValue(some2(input),{message:e.message})))}class Middleware{_tag="Middleware";decode;encode;constructor(decode,encode){this.decode=decode;this.encode=encode}flip(){return new Middleware(this.encode,this.decode)}}var TypeId11="~effect/SchemaTransformation/Transformation";class Transformation{[TypeId11]=TypeId11;_tag="Transformation";decode;encode;constructor(decode,encode){this.decode=decode;this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}compose(other){return new Transformation(this.decode.compose(other.decode),other.encode.compose(this.encode))}}function isTransformation(u){return hasProperty(u,TypeId11)}var make9=(options)=>{if(isTransformation(options)){return options}return new Transformation(options.decode,options.encode)};function transformOrFail2(options){return new Transformation(transformOrFail(options.decode),transformOrFail(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough2(),passthrough2());function passthrough3(){return passthrough_2}var numberFromString=new Transformation(Number4(),String2());var dateFromString=new Transformation(Date3(),transform(formatDate));var isJsonError=(input)=>isObject(input)&&typeof input["message"]==="string";var decodeJsonError=(input)=>{const hasCause=Object.hasOwn(input,"cause");const err=hasCause?new Error(input.message,{cause:decodeDefect(input.cause)}):new Error(input.message);if(typeof input.name==="string"&&input.name!=="Error")err.name=input.name;if(typeof input.stack==="string")err.stack=input.stack;return err};var encodeUnknownAsJson=(input)=>{try{const json=formatJson(input);return json===undefined?format(input):JSON.parse(json)}catch{return format(input)}};var encodeJsonError=(input,options,encodeDefect)=>{const encoded={name:input.name,message:typeof input.message==="string"?input.message:""};if(options?.includeStack&&typeof input.stack==="string"){encoded.stack=input.stack}if(!options?.excludeCause&&input.cause!==undefined){encoded.cause=encodeDefect(input.cause)}return encoded};var makeEncodeDefect=(options)=>{const seen=new WeakSet;const encode=(input)=>{if(isError(input)){if(seen.has(input)){return"[Circular]"}seen.add(input);const encoded=encodeJsonError(input,options,encode);seen.delete(input);return encoded}return encodeUnknownAsJson(input)};return encode};var decodeDefect=(input)=>isJsonError(input)?decodeJsonError(input):input;var defectFromJson=(options)=>transform2({decode:decodeDefect,encode:makeEncodeDefect(options)});var urlFromString=transformOrFail2({decode:(s)=>URL.canParse(s)?succeed6(new URL(s)):fail6(new InvalidValue(some2(s),{message:`Invalid URL string: ${s}`})),encode:(url)=>succeed6(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase642(),encodeBase642());var fromJsonString=new Transformation(parseJson(),stringifyJson());function makeGuard(tag){return(ast)=>ast._tag===tag}function isAST(u){return hasProperty(u,TypeId12)&&u[TypeId12]===TypeId12}var isDeclaration=makeGuard("Declaration");var isNull=makeGuard("Null");var isVoid=makeGuard("Void");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal");var isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays");var isObjects=makeGuard("Objects");var isUnion=makeGuard("Union");var isSuspend=makeGuard("Suspend");class Link{to;transformation;constructor(to,transformation){this.to=to;this.transformation=transformation}}var defaultParseOptions={};class Context{isOptional;isMutable;defaultValue;annotations;constructor(isOptional,isMutable,defaultValue=undefined,annotations=undefined){this.isOptional=isOptional;this.isMutable=isMutable;this.defaultValue=defaultValue;this.annotations=annotations}}var TypeId12="~effect/Schema";class Base2{[TypeId12]=TypeId12;annotations;checks;encoding;context;constructor(annotations=undefined,checks=undefined,encoding=undefined,context3=undefined){this.annotations=annotations;this.checks=checks;this.encoding=encoding;this.context=context3}toString(){return`<${this._tag}>`}}class Declaration extends Base2{_tag="Declaration";typeParameters;run;encodingChecks;constructor(typeParameters,run,annotations,checks,encoding,context3,encodingChecks){super(annotations,checks,encoding,context3);this.typeParameters=typeParameters;this.run=run;this.encodingChecks=encodingChecks}getParser(){const run=this.run(this.typeParameters);return(oinput,options)=>{if(isNone2(oinput))return succeedNone2;return mapEager2(run(oinput.value,this,options),some2)}}_rebuild(recur,checks,encodingChecks){const tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Declaration(tps,this.run,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}}class Null extends Base2{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}}var null_=new Null;class Undefined extends Base2{_tag="Undefined";getParser(){return fromConst(this,undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}}var undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null)));var undefined_2=new Undefined;class Void extends Base2{_tag="Void";getParser(){return fromAnyToConst(undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"void"}}var void_4=new Void;class Never extends Base2{_tag="Never";getParser(){return fromRefinement(this,isNever)}getExpected(){return"never"}}var never2=new Never;class Unknown extends Base2{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}}var unknown=new Unknown;class Literal extends Base2{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context3){super(annotations,checks,encoding,context3);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal)){throw new Error(`A numeric literal must be finite, got ${format(literal)}`)}this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:undefined}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}}function literalToString(ast){const literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}class String3 extends Base2{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){return applyTemplateLiteralPartChecks(this,s,options)}getExpected(){return"string"}}var string2=new String3;class Number5 extends Base2{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){return regexp.test(s)?applyTemplateLiteralPartChecks(this,globalThis.Number(s),options):undefined}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"isFinite")||hasCheck(this.checks,"isInt"))){return this}return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.checks&&(hasCheck(this.checks,"isFinite")||hasCheck(this.checks,"isInt"))){return replaceEncoding(this,[finiteToString])}return replaceEncoding(this,[numberToString])}getExpected(){return"number"}}function hasCheck(checks,tag){return checks.some((c)=>{switch(c._tag){case"Filter":return c.annotations?.meta?._tag===tag;case"FilterGroup":return hasCheck(c.checks,tag)}})}var number2=new Number5;class Boolean2 extends Base2{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}}var boolean=new Boolean2;class Arrays extends Base2{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context3,encodingChecks){super(annotations,checks,encoding,context3);this.isMutable=isMutable;this.elements=elements;this.rest=rest;this.encodingChecks=encodingChecks;const i=elements.findIndex(isOptional);if(i!==-1&&(elements.slice(i+1).some((e)=>!isOptional(e))||rest.length>1)){throw new Error("A required element cannot follow an optional element. ts(1257)")}if(rest.length>1&&rest.slice(1).some(isOptional)){throw new Error("An optional element cannot follow a rest element. ts(1266)")}}getParser(recur){const ast=this;const elements=ast.elements.map((ast2)=>({ast:ast2,parser:recur(ast2)}));const rest=ast.rest.map((ast2)=>({ast:ast2,parser:recur(ast2)}));const elementLen=elements.length;const[head,...tail]=rest;const tailLen=tail.length;function getParser(tailThreshold,index){if(index<elementLen){return elements[index]}else if(index>=tailThreshold){return tail[index-tailThreshold]}return head}return fnUntracedEager2(function*(oinput,options){if(oinput._tag==="None"){return oinput}const input=oinput.value;if(!Array.isArray(input)){return yield*fail6(new InvalidType(ast,oinput))}const len=input.length;const state={ast,getParser,oinput,len,tailThreshold:resolveTailThreshold(len,elementLen,tailLen),output:new globalThis.Array(len),issues:undefined,options};const concurrency=resolveConcurrency(options?.concurrency);const eff=parseArray(state,input,{concurrency:concurrency?.concurrency,end:ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen)});if(eff)yield*eff;if(ast.rest.length===0&&len>elementLen){for(let i=elementLen;i<=len-1;i++){const issue=new Pointer([i],new UnexpectedKey(ast,input[i]));if(options.errors==="all"){if(state.issues)state.issues.push(issue);else state.issues=[issue]}else{return yield*fail6(new Composite(ast,oinput,[issue]))}}}if(state.issues){return yield*fail6(new Composite(ast,oinput,state.issues))}return some2(state.output)})}_rebuild(recur,checks,encodingChecks){const elements=mapOrSame(this.elements,recur);const rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}}var parseArray=iterateEager()({onItem(s,item,i){const value3=i<s.len?some2(item):none2();return s.getParser(s.tailThreshold,i).parser(value3,s.options)},step(s,_,exit3,i){if(exit3._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,i,exit3)}else if(exit3.value._tag==="Some"){s.output[i]=exit3.value.value}else{const p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;const issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{return fail4(new Composite(s.ast,s.oinput,[issue]))}}}});function resolveTailThreshold(inputLen,elementLen,tailLen){return Math.max(elementLen,inputLen-tailLen)}var resolveConcurrency=(value3)=>{value3=value3==="unbounded"?Infinity:value3??1;return value3>1?{concurrency:value3}:undefined};var wrapPropertyKeyIssue=(s,ast,key,exit3)=>{if(exit3.cause.reasons.length===0){return exit3}const issue=getSchemaIssue(exit3.cause);if(issue===undefined){return failCause2(map5(exit3.cause,(issue2)=>new Composite(ast,s.oinput,[new Pointer([key],issue2)])))}const pointer=new Pointer([key],issue);if(s.options.errors==="all"){if(s.issues)s.issues.push(pointer);else s.issues=[pointer]}else{return fail4(new Composite(ast,s.oinput,[pointer]))}};var FINITE_PATTERN="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys;let symbolKeys;function go(parameter2){switch(parameter2._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter2.matchPart(k,options)!==undefined);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter2.matchKey(k,options)!==undefined);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>parameter2.matchKey(k,options)!==undefined);case"Union":return[...new Set(parameter2.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}class PropertySignature{name;type;constructor(name,type){this.name=name;this.type=type}}class KeyValueCombiner{decode;encode;constructor(decode,encode){this.decode=decode;this.encode=encode}flip(){return new KeyValueCombiner(this.encode,this.decode)}}function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return false}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterSide(toEncoded(ast))}class IndexSignature{parameter;type;merge;constructor(parameter,type,merge3){if(!isIndexSignatureParameter(parameter)){throw new Error(`Invalid index signature parameter ${parameter._tag}`)}this.parameter=parameter;this.type=type;this.merge=merge3;if(isOptional(type)&&!containsUndefined(type)){throw new Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}}}class Objects extends Base2{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context3,encodingChecks){super(annotations,checks,encoding,context3);this.propertySignatures=propertySignatures;this.indexSignatures=indexSignatures;this.encodingChecks=encodingChecks;const duplicates=propertySignatures.map((ps)=>ps.name).filter((name,i,arr)=>arr.indexOf(name)!==i);if(duplicates.length>0){throw new Error(`Duplicate identifiers: ${JSON.stringify(duplicates)}. ts(2300)`)}}getParser(recur){const ast=this;const expectedKeys=[];const expectedKeysSet=new Set;const properties=[];for(const ps of ast.propertySignatures){expectedKeys.push(ps.name);expectedKeysSet.add(ps.name);properties.push({ps,parser:recur(ps.type),name:ps.name,type:ps.type})}const indexCount=ast.indexSignatures.length;if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){return fromRefinement(ast,isNotNullish)}const parseIndexes=indexCount>0?iterateEager()({onItem:fnUntracedEager2(function*(s,[key,is]){const parserKey=recur(parameterFromPropertyKey(is.parameter));const effKey=parserKey(some2(key),s.options);const exitKey=effectIsExit(effKey)?effKey:yield*exit2(effKey);if(exitKey._tag==="Failure"){const eff=wrapPropertyKeyIssue(s,ast,key,exitKey);if(eff)yield*eff;return}const value3=some2(s.input[key]);const parserValue=recur(is.type);const effValue=parserValue(value3,s.options);const exitValue=effectIsExit(effValue)?effValue:yield*exit2(effValue);if(exitValue._tag==="Failure"){const eff=wrapPropertyKeyIssue(s,ast,key,exitValue);if(eff)yield*eff;return}else if(exitKey.value._tag==="Some"&&exitValue.value._tag==="Some"){const k2=exitKey.value.value;if(expectedKeysSet.has(key)||expectedKeysSet.has(k2)){return}const v2=exitValue.value.value;if(is.merge&&is.merge.decode&&Object.hasOwn(s.out,k2)){const[k,v]=is.merge.decode.combine([k2,s.out[k2]],[k2,v2]);set(s.out,k,v)}else{set(s.out,k2,v2)}}}),step:(_s,_,exit3)=>exit3._tag==="Failure"?exit3:undefined}):undefined;return fnUntracedEager2(function*(oinput,options){if(oinput._tag==="None"){return oinput}const input=oinput.value;if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return yield*fail6(new InvalidType(ast,oinput))}const out={};const state={ast,oinput,input,out,issues:undefined,options};const errorsAllOption=options.errors==="all";const onExcessPropertyError=options.onExcessProperty==="error";const onExcessPropertyPreserve=options.onExcessProperty==="preserve";let inputKeys;if(ast.indexSignatures.length===0&&(onExcessPropertyError||onExcessPropertyPreserve)){inputKeys=Reflect.ownKeys(input);for(let i=0;i<inputKeys.length;i++){const key=inputKeys[i];if(!expectedKeysSet.has(key)){if(onExcessPropertyError){const issue=new Pointer([key],new UnexpectedKey(ast,input[key]));if(errorsAllOption){if(state.issues){state.issues.push(issue)}else{state.issues=[issue]}continue}else{return yield*fail6(new Composite(ast,oinput,[issue]))}}else{set(out,key,input[key])}}}}const concurrency=resolveConcurrency(options?.concurrency);const eff=parseProperties(state,properties,concurrency);if(eff)yield*eff;if(parseIndexes){const keyPairs=empty3();for(let i=0;i<indexCount;i++){const is=ast.indexSignatures[i];const keys2=getIndexSignatureKeys(input,is.parameter,options);for(let j=0;j<keys2.length;j++){const key=keys2[j];keyPairs.push([key,is])}}const eff2=parseIndexes(state,keyPairs,concurrency);if(eff2)yield*eff2}if(state.issues){return yield*fail6(new Composite(ast,oinput,state.issues))}if(options.propertyOrder==="original"){const keys2=(inputKeys??Reflect.ownKeys(input)).concat(expectedKeys);const preserved={};for(const key of keys2){if(Object.hasOwn(out,key)){set(preserved,key,out[key])}}return some2(preserved)}return some2(out)})}_rebuild(recur,recurParameter,flipMerge,checks,encodingChecks){const props=mapOrSame(this.propertySignatures,(ps)=>{const t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)});const indexes=mapOrSame(this.indexSignatures,(is)=>{const p=recurParameter(is.parameter);const t=recur(is.type);const merge3=flipMerge?is.merge?.flip():is.merge;return p===is.parameter&&t===is.type&&merge3===is.merge?is:new IndexSignature(p,t,merge3)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,undefined,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,true,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,false,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}}var parseProperties=iterateEager()({onItem(s,p){const value3=Object.hasOwn(s.input,p.name)?some2(s.input[p.name]):none2();return p.parser(value3,s.options)},step(s,p,exit3){if(exit3._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,p.name,exit3)}else if(exit3.value._tag==="Some"){set(s.out,p.name,exit3.value.value)}else if(!isOptional(p.type)){const issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else{return fail4(new Composite(s.ast,s.oinput,[issue]))}}}});function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>{return new PropertySignature(key,fields[key].ast)}),[],annotations,checks)}function getAST(self){return self.ast}function tuple(elements,checks=undefined){return new Arrays(false,elements.map((e)=>e.ast),[],undefined,checks)}function union2(members,mode,checks){return new Union(members.map(getAST),mode,undefined,checks)}function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["object","array"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{const s=ast.annotations?.["~sentinels"];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{const type=ps.type;if(!isOptional(type)){if(isLiteral(type)){return[{key:ps.name,literal:type.literal}]}if(isUniqueSymbol(type)){return[{key:ps.name,literal:type.symbol}]}}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{return isLiteral(e)&&!isOptional(e)?[{key:i,literal:e.literal}]:[]});case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap;function getIndex(types){let idx=candidateIndexCache.get(types);if(idx)return idx;idx={};for(let i=0;i<types.length;i++){const a=types[i];const encoded=toEncoded(a);if(isNever2(encoded))continue;const candidateTypes=getCandidateTypes(encoded);const sentinels=collectSentinels(encoded);idx.byType??={};for(const t of candidateTypes)(idx.byType[t]??=[]).push(i);if(sentinels.length>0){idx.bySentinel??=new Map;for(const{key,literal}of sentinels){let m=idx.bySentinel.get(key);if(!m)idx.bySentinel.set(key,m=new Map);let arr=m.get(literal);if(!arr)m.set(literal,arr=[]);arr.push(i)}}else{idx.otherwise??={};for(const t of candidateTypes)(idx.otherwise[t]??=[]).push(i)}}candidateIndexCache.set(types,idx);return idx}function filterLiterals(input){return(ast)=>{const encoded=toEncoded(ast);return encoded._tag==="Literal"?encoded.literal===input:encoded._tag==="UniqueSymbol"?encoded.symbol===input:true}}function getCandidates(input,types){const idx=getIndex(types);const runtimeType=input===null?"null":Array.isArray(input)?"array":typeof input;if(idx.bySentinel){const base=idx.otherwise?.[runtimeType]??[];if(runtimeType==="object"||runtimeType==="array"){const selected=new Set(base);for(const[k,m]of idx.bySentinel){if(Object.hasOwn(input,k)){const match8=m.get(input[k]);if(match8){for(const candidate of match8)selected.add(candidate)}}}return Array.from(selected).sort((a,b)=>a-b).map((i)=>types[i]).filter(filterLiterals(input))}return base.map((i)=>types[i])}return(idx.byType?.[runtimeType]??[]).map((i)=>types[i]).filter(filterLiterals(input))}class Union extends Base2{_tag="Union";types;mode;encodingChecks;constructor(types,mode,annotations,checks,encoding,context3,encodingChecks){super(annotations,checks,encoding,context3);this.types=types;this.mode=mode;this.encodingChecks=encodingChecks}getParser(recur){const ast=this;return(oinput,options)=>{if(oinput._tag==="None"){return succeed6(oinput)}const input=oinput.value;const candidates=getCandidates(input,ast.types);const state={ast,recur,oinput,input,out:undefined,successes:[],issues:undefined,options};const concurrency=resolveConcurrency(options?.concurrency);const eff=parseUnion(state,candidates,concurrency?{...concurrency,orderedStep:true}:undefined);if(!eff){return state.out?succeed6(state.out):fail6(new AnyOf(ast,input,state.issues??[]))}return flatMap3(eff,(_)=>{return state.out?succeed6(state.out):fail6(new AnyOf(ast,input,state.issues??[]))})}}_rebuild(recur,checks,encodingChecks){const types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.mode,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(const type of this.types){const out=type.matchPart(s,options);if(out!==undefined)return out}return}getExpected(getExpected2){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";const types=this.types.map((type)=>{const encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{const literals=encoded.elements.filter(isLiteral);if(literals.length>0){return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected2(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`}break}case"Objects":{const literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0){return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected2(ps.type)}`).join(", ")}, ... }`}break}}return getExpected2(encoded)});return Array.from(new Set(types)).join(" | ")}}var parseUnion=iterateEager()({onItem(s,ast){const parser=s.recur(ast);return parser(s.oinput,s.options)},step(s,candidate,exit3){if(exit3._tag==="Failure"){const issue=getSchemaIssue(exit3.cause);if(issue===undefined){return exit3}if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.ast.mode==="oneOf"){s.successes.push(candidate);return fail4(new OneOf(s.ast,s.input,s.successes))}s.out=exit3.value;s.successes.push(candidate);if(s.ast.mode==="anyOf"){return void_2}}}});var nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")],"anyOf");var numberToJson=new Link(new Union([number2,nonFiniteLiterals],"anyOf"),new Transformation(Number4(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}class Filter2 extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=undefined,aborted=false){super();this.run=run;this.annotations=annotations;this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,true)}and(other,annotations){return new FilterGroup([this,other],annotations)}}class FilterGroup extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=undefined){super();this.checks=checks;this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}}function makeFilter(filter6,annotations,aborted=false){return new Filter2((input,ast,options)=>make7(input,ast,filter6(input,ast,options)),annotations,aborted)}function makeFilterByGuard(is,annotations){return new Filter2((input)=>is(input)?undefined:new InvalidValue(some2(input)),annotations,true)}function isPattern(regExp,annotations){const source=regExp.source;return makeFilter((s)=>regExp.test(s),{expected:`a string matching the RegExp ${source}`,meta:{_tag:"isPattern",regExp},arbitrary:{constraint:{patterns:[regExp.source]}},...annotations})}function modifyOwnPropertyDescriptors(ast,f){const d=Object.getOwnPropertyDescriptors(ast);f(d);return Object.create(Object.getPrototypeOf(ast),d)}function replaceEncoding(ast,encoding){if(ast.encoding===encoding){return ast}return modifyOwnPropertyDescriptors(ast,(d)=>{d.encoding.value=encoding})}function replaceContext(ast,context3){if(ast.context===context3){return ast}return modifyOwnPropertyDescriptors(ast,(d)=>{d.context.value=context3})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){const last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return modifyOwnPropertyDescriptors(ast,(d)=>{d.annotations.value={...d.annotations.value,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks!==undefined){throw new Error("Cannot add checks to Suspend")}if(ast.checks===checks){return ast}return modifyOwnPropertyDescriptors(ast,(d)=>{d.checks.value=checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function updateLastLink(encoding,f){const links=encoding;const last=links[links.length-1];const to=f(last.to);if(to!==last.to){return append(encoding.slice(0,encoding.length-1),new Link(to,last.transformation))}return encoding}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function applyToSelfOrLastLinkEncoding(f){function out(ast){return ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,out)):f(ast)}return memoize(out)}function middlewareDecoding(ast,middleware){return appendTransformation(ast,middleware,toType(ast))}function appendTransformation(from,transformation,to){const link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function brand(ast,brand2){const existing=resolveBrands(ast);const brands=existing?[...existing,brand2]:[brand2];return annotate(ast,{brands})}function mapOrSame(as3,f){let changed=false;const out=new Array(as3.length);for(let i=0;i<as3.length;i++){const a=as3[i];const fa=f(a);if(fa!==a){changed=true}out[i]=fa}return changed?out:as3}function annotateKey(ast,annotations){const context3=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.defaultValue,{...ast.context.annotations,...annotations}):new Context(false,false,undefined,annotations);return replaceContext(ast,context3)}var optionalKeyLastLink=applyToLastLink(optionalKey);function optionalKey(ast){const context3=ast.context?ast.context.isOptional===false?new Context(true,ast.context.isMutable,ast.context.defaultValue,ast.context.annotations):ast.context:new Context(true,false);return optionalKeyLastLink(replaceContext(ast,context3))}function withConstructorDefault(ast,defaultValue){const transformation=new Transformation(withDefault(defaultValue),passthrough2());const encoding=[new Link(unknown,transformation)];const context3=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,encoding,ast.context.annotations):new Context(false,false,encoding);return replaceContext(ast,context3)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function parseParameter(ast){const literals=[];const parameters=[];function go(ast2){switch(ast2._tag){case"Literal":if(isPropertyKey(ast2.literal)){literals.push(ast2.literal)}return;case"UniqueSymbol":literals.push(ast2.symbol);return;case"Never":return;case"Union":for(let i=0;i<ast2.types.length;i++){go(ast2.types[i])}return;default:parameters.push(ast2)}}go(ast);return{literals,parameters}}function record(key,value3,keyValueCombiner){const{literals,parameters:indexSignatures}=parseParameter(key);return new Objects(literals.map((literal)=>new PropertySignature(literal,value3)),indexSignatures.map((parameter)=>new IndexSignature(parameter,value3,keyValueCombiner)))}function isOptional(ast){return ast.context?.isOptional??false}function isMutable(ast){return ast.context?.isMutable??false}var toType=memoize((ast)=>{if(ast.encoding){return toType(replaceEncoding(ast,undefined))}const out=ast;const type=out.recur?.(toType)??out;const encodingChecks=type.encodingChecks;if(encodingChecks){return modifyOwnPropertyDescriptors(type,(d)=>{d.encodingChecks.value=undefined;if(type===ast){d.checks.value=combineChecks(type.checks,encodingChecks)}})}return type});var toEncoded=memoize((ast)=>{return toType(flip2(ast))});function flipEncoding(ast,encoding){const links=encoding;const len=links.length;const last=links[len-1];const ls=[new Link(flip2(replaceEncoding(ast,undefined)),links[0].transformation.flip())];for(let i=1;i<len;i++){ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()))}const to=flip2(last.to);if(to.encoding){return replaceEncoding(to,[...to.encoding,...ls])}else{return replaceEncoding(to,ls)}}var flip2=memoize((ast)=>{if(ast.encoding){return flipEncoding(ast,ast.encoding)}const out=ast;return out.flip?.(flip2)??out.recur?.(flip2)??out});function containsUndefined(ast){switch(ast._tag){case"Undefined":return true;case"Union":return ast.types.some(containsUndefined);default:return false}}function fromConst(ast,value3){const succeed7=succeedSome2(value3);return(oinput)=>{if(oinput._tag==="None"){return succeedNone2}return oinput.value===value3?succeed7:fail6(new InvalidType(ast,oinput))}}function fromAnyToConst(value3){const succeed7=succeedSome2(value3);return(oinput)=>oinput._tag==="None"?succeedNone2:succeed7}function fromRefinement(ast,refinement){return(oinput)=>{if(oinput._tag==="None"){return succeedNone2}return refinement(oinput.value)?succeed6(oinput):fail6(new InvalidType(ast,oinput))}}function applyTemplateLiteralPartChecks(ast,value3,options){if(options?.disableChecks||ast.checks===undefined)return value3;const issues=[];collectIssues(ast.checks,value3,issues,ast,options);return issues.length===0?value3:undefined}var parameterFromPropertyKey=applyToSelfOrLastLinkEncoding((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var parameterFromString=applyToSelfOrLastLinkEncoding((ast)=>{switch(ast._tag){default:return ast;case"Symbol":case"UniqueSymbol":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromString)}});var STRING_PATTERN="[\\s\\S]*?";var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`);var isStringNumberRegExp=new globalThis.RegExp(`(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",meta:{_tag:"isStringFinite",regExp:isStringFiniteRegExp},...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]);var finiteToString=new Link(finiteString,numberFromString);var numberToString=new Link(new Union([finiteString,nonFiniteLiterals],"anyOf"),numberFromString);var BIGINT_PATTERN="-?\\d+";var isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\((.*)\\)";var isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value3,issues,ast,options){for(let i=0;i<checks.length;i++){const check=checks[i];if(check._tag==="FilterGroup"){collectIssues(check.checks,value3,issues,ast,options)}else{const issue=check.run(value3,ast,options);if(issue){issues.push(new Filter(value3,check,issue));if(check.aborted||options?.errors!=="all"){return}}}}}var ClassTypeId="~effect/Schema/Class";var STRUCTURAL_ANNOTATION_KEY="~structural";var resolveAt2=resolveAt;var resolveIdentifier2=resolveIdentifier;var resolveDescription2=resolveDescription;function isJson(u){const onPath=new Set;const validated=new Set;return recur(u);function recur(u2){if(u2===null||typeof u2==="string"||typeof u2==="boolean"){return true}if(typeof u2==="number"){return globalThis.Number.isFinite(u2)}if(typeof u2!=="object"||u2===undefined){return false}if(onPath.has(u2)){return false}if(validated.has(u2)){return true}const isArray2=Array.isArray(u2);if(!isArray2){const prototype=Object.getPrototypeOf(u2);if(prototype!==null&&Object.getPrototypeOf(prototype)!==null){return false}}onPath.add(u2);const ok=isArray2?u2.every(recur):Object.keys(u2).every((key)=>recur(u2[key]));onPath.delete(u2);if(ok){validated.add(u2)}return ok}}var Json=new Declaration([],()=>(input,ast)=>isJson(input)?succeed6(input):fail6(new InvalidType(ast,some2(input))),{typeConstructor:{_tag:"effect/Json"},generation:{runtime:`Schema.Json`,Type:`Schema.Json`},expected:"JSON value",toCodecJson:()=>new Link(unknown,passthrough3()),toArbitrary:()=>(fc)=>fc.jsonValue()});var unknownToNull=new Link(null_,new Transformation(passthrough2(),transform(()=>null)));var unknownToJson=new Link(Json,passthrough3());function isStringTree(u){const seen=new Set;return recur(u);function recur(u2){if(u2===undefined||typeof u2==="string"){return true}if(typeof u2!=="object"||u2===null){return false}if(seen.has(u2)){return false}seen.add(u2);if(Array.isArray(u2)){return u2.every(recur)}return Object.keys(u2).every((key)=>recur(u2[key]))}}var StringTree=new Declaration([],()=>(input,ast)=>isStringTree(input)?succeed6(input):fail6(new InvalidType(ast,some2(input))),{expected:"StringTree"});var unknownToStringTree=new Link(StringTree,passthrough3());function nominal(){return Object.assign((input)=>input,{option:(input)=>some2(input),result:(input)=>succeed2(input),is:(_)=>true})}var TypeId13="~effect/platform/PlatformError";class BadArgument extends TaggedError2("BadArgument"){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}}class SystemError extends Error3{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor!==undefined?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}class PlatformError extends TaggedError2("PlatformError"){constructor(reason){if("cause"in reason){super({reason,cause:reason.cause})}else{super({reason})}}[TypeId13]=TypeId13;get message(){return this.reason.message}}var systemError=(options)=>new PlatformError(new SystemError(options));var badArgument=(options)=>new PlatformError(new BadArgument(options));var TypeId14=`~effect/Fiber/${version}`;var interrupt4=fiberInterrupt;var getCurrent=getCurrentFiber;var runIn=fiberRunIn;var makeUnsafe5=makeLatchUnsafe;var Empty=Symbol.for("effect/MutableList/Empty");var make10=()=>({head:undefined,tail:undefined,length:0});var emptyBucket=()=>({array:[],mutable:true,offset:0,next:undefined});var append2=(self,message)=>{if(!self.tail){self.head=self.tail=emptyBucket()}else if(!self.tail.mutable){self.tail.next=emptyBucket();self.tail=self.tail.next}self.tail.array.push(message);self.length++};var clear=(self)=>{self.head=self.tail=undefined;self.length=0};var takeN=(self,n)=>{if(n<=0||!self.head)return[];n=Math.min(n,self.length);if(n===self.length&&self.head?.offset===0&&!self.head.next){const array3=self.head.array;clear(self);return array3}const array2=new Array(n);let index=0;let chunk=self.head;while(chunk){while(chunk.offset<chunk.array.length){array2[index++]=chunk.array[chunk.offset];if(chunk.mutable)chunk.array[chunk.offset]=undefined;chunk.offset++;if(index===n){self.head=chunk;self.length-=n;if(self.length===0)clear(self);return array2}}chunk=chunk.next}clear(self);return array2};var take=(self)=>{if(!self.head)return Empty;const message=self.head.array[self.head.offset];if(self.head.mutable)self.head.array[self.head.offset]=undefined;self.head.offset++;self.length--;if(self.head.offset===self.head.array.length){if(self.head.next){self.head=self.head.next}else{clear(self)}}return message};var TypeId15="~effect/MutableRef";var MutableRefProto={[TypeId15]:TypeId15,...PipeInspectableProto,toJSON(){return{_id:"MutableRef",current:toJson(this.current)}}};var make11=(value3)=>{const ref=Object.create(MutableRefProto);ref.current=value3;return ref};var TypeId16="~effect/Queue";var EnqueueTypeId="~effect/Queue/Enqueue";var DequeueTypeId="~effect/Queue/Dequeue";var variance={_A:identity,_E:identity};var QueueProto={[TypeId16]:variance,[EnqueueTypeId]:variance,[DequeueTypeId]:variance,...PipeInspectableProto,toJSON(){return{_id:"effect/Queue",state:this.state._tag,size:sizeUnsafe(this)}}};var make12=(options)=>withFiber((fiber2)=>{const self=Object.create(QueueProto);self.dispatcher=fiber2.currentDispatcher;self.capacity=options?.capacity??Number.POSITIVE_INFINITY;self.strategy=options?.strategy??"suspend";self.messages=make10();self.scheduleRunning=false;self.state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};return succeed3(self)});var bounded=(capacity)=>make12({capacity});var offer=(self,message)=>suspend(()=>{if(self.state._tag!=="Open"){return exitFalse}else if(self.messages.length>=self.capacity){switch(self.strategy){case"dropping":return exitFalse;case"suspend":if(self.capacity<=0&&self.state.takers.size>0){append2(self.messages,message);releaseTakers(self);return exitTrue}return offerRemainingSingle(self,message);case"sliding":take(self.messages);append2(self.messages,message);return exitTrue}}append2(self.messages,message);scheduleReleaseTaker(self);return exitTrue});var offerUnsafe=(self,message)=>{if(self.state._tag!=="Open"){return false}else if(self.messages.length>=self.capacity){if(self.strategy==="sliding"){take(self.messages);append2(self.messages,message);return true}else if(self.capacity<=0&&self.state.takers.size>0){append2(self.messages,message);releaseTakers(self);return true}return false}append2(self.messages,message);scheduleReleaseTaker(self);return true};var failCause4=dual(2,(self,cause)=>sync(()=>failCauseUnsafe(self,cause)));var failCauseUnsafe=(self,cause)=>{if(self.state._tag!=="Open"){return false}const exit3=exitFailCause(cause);const fail8=exitZipRight(exit3,exitFailDone);if(self.state.offers.size===0&&self.messages.length===0){finalize(self,fail8);return true}self.state={...self.state,_tag:"Closing",exit:fail8};return true};var endUnsafe=(self)=>failCauseUnsafe(self,causeFail(Done()));var shutdown=(self)=>sync(()=>{if(self.state._tag==="Done"){return true}clear(self.messages);const offers=self.state.offers;finalize(self,self.state._tag==="Open"?exitInterrupt2:self.state.exit);if(offers.size>0){for(const entry of offers){if(entry._tag==="Single"){entry.resume(exitFalse)}else{entry.resume(exitSucceed(entry.remaining.slice(entry.offset)))}}offers.clear()}return true});var takeAll2=(self)=>takeBetween(self,1,Number.POSITIVE_INFINITY);var takeBetween=(self,min4,max4)=>suspend(()=>takeBetweenUnsafe(self,min4,max4)??andThen(awaitTake(self),takeBetween(self,1,max4)));var take2=(self)=>suspend(()=>takeUnsafe(self)??andThen(awaitTake(self),take2(self)));var takeUnsafe=(self)=>{if(self.state._tag==="Done"){return self.state.exit}if(self.messages.length>0){const message=take(self.messages);releaseCapacity(self);return exitSucceed(message)}else if(self.capacity<=0&&self.state.offers.size>0){self.capacity=1;releaseCapacity(self);self.capacity=0;const message=take(self.messages);releaseCapacity(self);return exitSucceed(message)}return};var sizeUnsafe=(self)=>self.state._tag==="Done"?0:self.messages.length;var exitFalse=exitSucceed(false);var exitTrue=exitSucceed(true);var exitFailDone=exitFail(Done());var exitInterrupt2=exitInterrupt();var releaseTakers=(self)=>{self.scheduleRunning=false;if(self.state._tag==="Done"||self.state.takers.size===0){return}for(const taker of self.state.takers){self.state.takers.delete(taker);taker(exitVoid);if(self.messages.length===0){break}}};var scheduleReleaseTaker=(self)=>{if(self.scheduleRunning||self.state._tag==="Done"||self.state.takers.size===0){return}self.scheduleRunning=true;self.dispatcher.scheduleTask(()=>releaseTakers(self),0)};var takeBetweenUnsafe=(self,min4,max4)=>{if(self.state._tag==="Done"){return self.state.exit}else if(max4<=0||min4<=0){return exitSucceed([])}else if(self.capacity<=0&&self.state.offers.size>0){self.capacity=1;releaseCapacity(self);self.capacity=0;const messages=[take(self.messages)];releaseCapacity(self);return exitSucceed(messages)}min4=Math.min(min4,self.capacity||1);if(min4<=self.messages.length){const messages=takeN(self.messages,max4);releaseCapacity(self);return exitSucceed(messages)}};var offerRemainingSingle=(self,message)=>{return callback((resume)=>{if(self.state._tag!=="Open"){return resume(exitFalse)}const entry={_tag:"Single",message,resume};self.state.offers.add(entry);return sync(()=>{if(self.state._tag==="Open"){self.state.offers.delete(entry)}})})};var releaseCapacity=(self)=>{if(self.state._tag==="Done"){return isDoneCause(self.state.exit.cause)}else if(self.state.offers.size===0){if(self.state._tag==="Closing"&&self.messages.length===0){finalize(self,self.state.exit);return isDoneCause(self.state.exit.cause)}return false}let n=self.capacity-self.messages.length;for(const entry of self.state.offers){if(n===0)break;else if(entry._tag==="Single"){append2(self.messages,entry.message);n--;entry.resume(exitTrue);self.state.offers.delete(entry)}else{for(;entry.offset<entry.remaining.length;entry.offset++){if(n===0)return false;append2(self.messages,entry.remaining[entry.offset]);n--}entry.resume(exitSucceed([]));self.state.offers.delete(entry)}}return false};var awaitTake=(self)=>callback((resume)=>{if(self.state._tag==="Done"){return resume(self.state.exit)}self.state.takers.add(resume);return sync(()=>{if(self.state._tag!=="Done"){self.state.takers.delete(resume)}})});var finalize=(self,exit3)=>{if(self.state._tag==="Done"){return}const openState=self.state;self.state={_tag:"Done",exit:exit3};for(const taker of openState.takers){taker(exit3)}openState.takers.clear();for(const awaiter of openState.awaiters){awaiter(exit3)}openState.awaiters.clear()};var makeUnsafe6=(permits)=>new SemaphoreImpl(permits);class SemaphoreImpl{waiters=new Set;taken=0;permits;constructor(permits){this.permits=permits}get free(){return this.permits-this.taken}take(n){const take3=suspend(()=>{if(this.free<n){return callback((resume)=>{if(this.free>=n)return resume(take3);const observer=()=>{if(this.free<n)return;this.waiters.delete(observer);resume(take3)};this.waiters.add(observer);return sync(()=>{this.waiters.delete(observer)})})}this.taken+=n;return succeed3(n)});return take3}updateTakenUnsafe(fiber2,f){this.taken=f(this.taken);if(this.waiters.size>0){fiber2.currentDispatcher.scheduleTask(()=>{const iter=this.waiters.values();let item=iter.next();while(item.done===false&&this.free>0){item.value();item=iter.next()}},0)}return this.free}updateTaken(f){return withFiber((fiber2)=>succeed3(this.updateTakenUnsafe(fiber2,f)))}resize(permits){return withFiber((fiber2)=>{this.permits=permits;if(this.free<0)return void_;this.updateTakenUnsafe(fiber2,(taken)=>taken);return void_})}release(n){return this.updateTaken((taken)=>taken-n)}get releaseAll(){return this.updateTaken((_)=>0)}withPermits(n){return(self)=>uninterruptibleMask((restore)=>flatMap2(restore(this.take(n)),(permits)=>onExitPrimitive(restore(self),()=>{this.updateTakenUnsafe(getCurrentFiber(),(taken)=>taken-permits);return},true)))}withPermit=this.withPermits(1);withPermitsIfAvailable(n){return(self)=>uninterruptibleMask((restore)=>{if(this.free<n)return succeedNone;this.taken+=n;return onExitPrimitive(restore(asSome(self)),()=>{this.updateTakenUnsafe(getCurrentFiber(),(taken)=>taken-n);return},true)})}}var TypeId17="~effect/Channel";var isChannel=(u)=>hasProperty(u,TypeId17);var ChannelProto={[TypeId17]:{_Env:identity,_InErr:identity,_InElem:identity,_OutErr:identity,_OutElem:identity},pipe(){return pipeArguments(this,arguments)}};var fromTransform=(transform3)=>{const self=Object.create(ChannelProto);self.transform=(upstream,scope3)=>catchCause2(transform3(upstream,scope3),(cause)=>succeed6(failCause3(cause)));return self};var transformPull=(self,f)=>fromTransform((upstream,scope3)=>flatMap3(toTransform(self)(upstream,scope3),(pull)=>f(pull,scope3)));var fromPull=(effect2)=>fromTransform((_,__)=>effect2);var fromTransformBracket=(f)=>fromTransform(fnUntraced2(function*(upstream,scope3){const closableScope=forkUnsafe2(scope3);const onCause=(cause)=>close(closableScope,doneExitFromCause(cause));const pull=yield*onError2(f(upstream,scope3,closableScope),onCause);return onError2(pull,onCause)}));var toTransform=(channel)=>channel.transform;var asyncQueue=(scope3,f,options)=>make12({capacity:options?.bufferSize,strategy:options?.strategy}).pipe(tap2((queue)=>addFinalizer2(scope3,shutdown(queue))),tap2((queue)=>forkIn2(provide(f(queue),scope3),scope3)));var callbackArray=(f,options)=>fromTransform((_,scope3)=>map6(asyncQueue(scope3,f,options),takeAll2));var suspend3=(evaluate2)=>fromTransform((upstream,scope3)=>suspend2(()=>toTransform(evaluate2())(upstream,scope3)));var empty5=fromPull(succeed6(done3()));var fail8=(error)=>fromPull(succeed6(fail6(error)));var map8=dual(2,(self,f)=>transformPull(self,(pull)=>sync2(()=>{let i=0;return map6(pull,(o)=>f(o,i++))})));var mapDone=dual(2,(self,f)=>mapDoneEffect(self,(o)=>succeed6(f(o))));var mapDoneEffect=dual(2,(self,f)=>transformPull(self,(pull)=>succeed6(catchDone(pull,(done4)=>flatMap3(f(done4),done3)))));var merge3=dual((args2)=>isChannel(args2[0])&&isChannel(args2[1]),(left,right,options)=>fromTransformBracket(fnUntraced2(function*(upstream,_scope,forkedScope){const strategy=options?.haltStrategy??"both";const queue=yield*bounded(0);yield*addFinalizer2(forkedScope,shutdown(queue));let done4=0;function onExit3(side,cause){done4++;if(!isDoneCause(cause)){return failCause4(queue,cause)}switch(strategy){case"both":{return done4===2?failCause4(queue,cause):void_3}case"left":case"right":{return side===strategy?failCause4(queue,cause):void_3}case"either":{return failCause4(queue,cause)}}}const runSide=(side,channel,scope3)=>toTransform(channel)(upstream,scope3).pipe(flatMap3((pull)=>pull.pipe(flatMap3((value3)=>offer(queue,value3)),forever3)),onError2((cause)=>andThen2(close(scope3,doneExitFromCause(cause)),onExit3(side,cause))),forkIn2(forkedScope));yield*runSide("left",left,forkUnsafe2(forkedScope));yield*runSide("right",right,forkUnsafe2(forkedScope));return take2(queue)})));var splitLines=()=>fromTransform((upstream,_scope)=>sync2(()=>{let stringBuilder="";let midCRLF=false;let done4=none2();function splitLinesArray(chunk){const chunkBuilder=[];function pushLine(segment){if(stringBuilder.length===0){chunkBuilder.push(segment)}else{chunkBuilder.push(stringBuilder+segment);stringBuilder=""}}for(let i=0;i<chunk.length;i++){const str=chunk[i];if(str.length!==0){let from=0;let indexOfCR=str.indexOf("\r");let indexOfLF=str.indexOf(`
182
182
  `);if(midCRLF){if(indexOfLF===0){pushLine("");from=1;indexOfLF=str.indexOf(`
@@ -278,11 +278,11 @@ ${annotate2("Wizard cancelled.",red)}`;var renderCommandBlock=(label,commandLine
278
278
  ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment.width)})}
279
279
  `};class CliValidationError extends TaggedErrorClass()("CliValidationError",{cause:optional(Defect()),message:String4,recoveryCommand:optional(String4)}){}class CliPromptError extends TaggedErrorClass()("CliPromptError",{cause:optional(Defect()),message:String4}){}var boundaryCancellationDetail=new Map([["@punks/cli/repository-check/RepositoryCheckOperationFailure","Check cancelled."],["@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure","Scaffold cancelled."],["@punks/cli/scaffold-update/ScaffoldUpdateOperationFailure","Update cancelled."]]);var isRecord2=(value3)=>typeof value3==="object"&&value3!==null;var promptWasCancelled=(value3)=>value3 instanceof CliPromptError&&isRecord2(value3.cause)&&value3.cause.name==="QuitError";var expectedFailureOutcome=(value3,cancellationDetail="Command cancelled.")=>{if(value3 instanceof CliValidationError){return{failure:{code:"validation-failed",detail:value3.message,recoverable:value3.recoveryCommand!==undefined,...value3.recoveryCommand===undefined?{}:{recoveryCommand:value3.recoveryCommand},subject:"command"},kind:"expected-failure"}}if(promptWasCancelled(value3)){return{failure:{code:"cancelled",detail:cancellationDetail,recoverable:false,subject:"command"},kind:"expected-failure"}}return};var helpCommand=(commandPath)=>`${commandPath.length===0?"hi":commandPath.join(" ")} --help`;var cliUsageFailure=(value3,commandPath=["hi"])=>{if(value3 instanceof exports_CliError.ShowHelp){if(value3.errors.length===0){return}const failures=value3.errors.map((error2)=>cliUsageFailure(error2,value3.commandPath));return failures.every((failure)=>failure!==undefined)?failures[0]:undefined}if(value3 instanceof exports_CliError.UnknownSubcommand){const parent=value3.parent??commandPath.slice(0,-1);return{code:"unknown-command",detail:`Unknown command \`${value3.subcommand}\`.`,recoverable:true,recoveryCommand:helpCommand(parent),subject:value3.subcommand}}if(value3 instanceof exports_CliError.UnrecognizedOption){return{code:"unknown-option",detail:`Unknown option \`${value3.option}\`.`,recoverable:true,recoveryCommand:helpCommand(value3.command??commandPath),subject:value3.option}}if(value3 instanceof exports_CliError.MissingOption){return{code:"missing-command-input",detail:`Missing value for \`--${value3.option}\`.`,recoverable:true,recoveryCommand:helpCommand(commandPath),subject:value3.option}}if(value3 instanceof exports_CliError.MissingArgument){return{code:"missing-command-input",detail:`Missing value for \`<${value3.argument}>\`.`,recoverable:true,recoveryCommand:helpCommand(commandPath),subject:value3.argument}}if(value3 instanceof exports_CliError.InvalidValue){return{code:"invalid-command-input",detail:`Invalid value for \`${value3.kind==="flag"?`--${value3.option}`:`<${value3.option}>`}\`.`,recoverable:true,recoveryCommand:helpCommand(commandPath),subject:value3.option}}if(value3 instanceof exports_CliError.DuplicateOption){return{code:"invalid-command-usage",detail:"Command options are ambiguous.",recoverable:true,recoveryCommand:helpCommand(commandPath),subject:value3.option}}return};class RootPresentationSink extends Service()("@punks/cli/RootPresentationSink"){}var extractOperationResult=(value3)=>{const candidate=typeof value3==="object"&&value3!==null&&"operation"in value3?value3.operation:value3;try{return decodeOperationResult(candidate)}catch{return}};var presentationOutcome=(value3)=>{const result3=extractOperationResult(value3);if(result3!==undefined){return{...isRecord2(value3)&&"jsonPayload"in value3?{jsonPayload:value3.jsonPayload}:{},kind:"result",result:result3}}if(value3===undefined){return}const directExpectedFailure=expectedFailureOutcome(value3);if(directExpectedFailure!==undefined){return directExpectedFailure}const usageFailure=cliUsageFailure(value3);if(usageFailure!==undefined){return{failure:usageFailure,kind:"expected-failure"}}if(isRecord2(value3)&&typeof value3._tag==="string"&&"cause"in value3){const cancellationDetail=boundaryCancellationDetail.get(value3._tag);if(cancellationDetail!==undefined){const wrappedExpectedFailure=expectedFailureOutcome(value3.cause,cancellationDetail);if(wrappedExpectedFailure!==undefined){return wrappedExpectedFailure}}}if(value3 instanceof RepositoryCheckOperationFailure){return{failure:{code:value3._tag,detail:value3.message,recoverable:false,subject:value3.operation},kind:"expected-failure"}}let detail;if(value3 instanceof Error){detail=value3.message}else if(typeof value3==="object"&&value3!==null){detail=JSON.stringify(value3)??"Unserializable diagnostic."}else{detail=typeof value3==="symbol"?value3.description??"":JSON.stringify(value3)??""}return{detail,kind:"unexpected-diagnostic"}};var captureCommandResult=(effect2)=>tap2(effect2,(value3)=>{const outcome=presentationOutcome(value3);if(outcome===undefined){return void_3}return RootPresentationSink.use((sink)=>sink.publish(outcome))});var resultFailed=(result3)=>result3.status==="partial"||result3.status==="degraded"||result3.status==="conflict"||result3.status==="failed";var present=({humanEnvironment,mode,outcome,writeStderr=(text3)=>process.stderr.write(text3),writeStdout=(text3)=>process.stdout.write(text3)})=>{if(outcome.kind==="unexpected-diagnostic"){writeStderr(`${outcome.detail}
280
280
  `);return 1}if(mode==="json"){let rendered;if(outcome.kind==="expected-failure"){rendered=renderJsonFailure(outcome.failure)}else if(outcome.jsonPayload===undefined){rendered=renderJsonResult(outcome.result)}else{rendered=`${JSON.stringify(outcome.jsonPayload,null,2)}
281
- `}writeStdout(rendered);return outcome.kind==="expected-failure"||resultFailed(outcome.result)?1:0}if(outcome.kind==="expected-failure"){writeStdout(renderExpectedFailure(outcome.failure,humanEnvironment));return 1}writeStdout(renderOperationResult(outcome.result,humanEnvironment));return resultFailed(outcome.result)?1:0};var UpdateInteraction=Service("@punks/cli/features/scaffold-update/UpdateInteraction");class ScaffoldUpdateOperationFailure extends TaggedErrorClass()("@punks/cli/scaffold-update/ScaffoldUpdateOperationFailure",{cause:Defect(),message:String4,operation:Literal2("update-scaffold")}){}var ScaffoldUpdateOperations=Service("@punks/cli/features/scaffold-update/ScaffoldUpdateOperations");var runScaffoldUpdateApplication=fn2("ScaffoldUpdate.run")(function*runScaffoldUpdateApplication2(input){const interaction=yield*UpdateInteraction;const operations=yield*ScaffoldUpdateOperations;return yield*operations.run(input,interaction)});var desiredFilesByPath=(files)=>{const indexed=new Map;for(const file5 of files){indexed.set(file5.path,indexed.has(file5.path)?null:file5)}return indexed};var recoveryAction=({conflict,desired,fixedManagedPaths})=>{if(conflict._tag!=="UserModifiedScaffoldEntryConflict"||conflict.item!=="file"||conflict.operation!=="update"||!fixedManagedPaths.has(conflict.identity)){return null}const file5=desired.get(conflict.identity);return file5===undefined||file5===null?null:{_tag:"ArchiveAndReplaceScaffoldFile",desired:file5,identity:conflict.identity,item:"file"}};var planFixedManagedRecovery=({authority,fixedManagedPaths,plan})=>{if(authority._tag!=="VerifiedDesiredBaseline"){return plan}const desired=desiredFilesByPath(authority.files);const recoveries=new Map;for(const conflict of plan.conflicts){const action2=recoveryAction({conflict,desired,fixedManagedPaths});if(action2!==null){recoveries.set(conflict,action2)}}if(recoveries.size===0){return plan}return{...plan,actions:[...plan.actions,...recoveries.values()],conflicts:plan.conflicts.filter((conflict)=>!recoveries.has(conflict))}};import path7 from"node:path";var packCatalog=[{category:"surface",description:"Backend pack: domain structure, recoverable actions, and logging.",hooks:[],id:"backend",lintAssets:[],promptDetails:["shared backend domain baseline","workspace backend action/recovery guidance","workspace logging/observability guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["backend-domain-structure","backend-recoverable-actions","logging-best-practices"],triggerPackages:[]},{category:"detected",description:"Better Auth guidance pack.",hooks:[],id:"better-auth",lintAssets:[],promptDetails:["shared auth guardrails","workspace auth boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["better-auth-best-practices"],triggerPackages:["better-auth"]},{category:"default",description:"Default debug pack: runtime debugging, ClawPatch bug discovery/resolution, and debug-agent workflow.",hooks:[],id:"debug",lintAssets:[],promptDetails:["shared runtime debugging baseline","workspace evidence-first debugging workflow"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["debugging-phase","bug-discovery-phase","bug-resolution-phase","debug-agent"],triggerPackages:[]},{category:"default",description:"Default docs pack: docs ingest plus public-doc and skill-writing primitives.",hooks:[],id:"docs",lintAssets:[],promptDetails:["shared docs baseline","public-doc writing flow","docs scope spec"],promptSurfaces:["shared-agents","root-prompt-spec","docs-prompt-spec"],skills:["docs-ingest-phase","docs-onboarding","writing-fragments","writing-beats","writing-shape","writing-for-agents","write-graph-based-skills","rule-authoring"],triggerPackages:[]},{category:"default",description:"Default misc pack: lightweight agent interaction helpers.",hooks:[],id:"misc",lintAssets:[],promptDetails:["shared agent interaction helpers"],promptSurfaces:["shared-agents"],skills:["handback","show-me","wait-what"],triggerPackages:[]},{category:"detected",description:"Drizzle guidance pack.",hooks:[],id:"drizzle",lintAssets:[],promptDetails:["shared data-layer baseline","workspace db flow rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:[],triggerPackages:["drizzle-kit","drizzle-orm"]},{category:"detected",description:"Effect guidance pack family.",exampleRepositories:[Object.fromEntries([["repo","AnswerOverflow/AnswerOverflow"],["url","https://github.com/AnswerOverflow/AnswerOverflow"],["packs",[{uid:"effect",version:"^3.20.0"}]]]),Object.fromEntries([["repo","rhyssullivan/executor"],["url","https://github.com/rhyssullivan/executor"],["packs",[{uid:"effect",version:"4.0.0-beta.59"}]]]),Object.fromEntries([["repo","alchemy-run/alchemy-effect"],["url","https://github.com/alchemy-run/alchemy-effect"],["packs",[{uid:"effect",version:">=4.0.0-beta.66 || >=4.0.0"}]]]),Object.fromEntries([["repo","anomalyco/opencode"],["url","https://github.com/anomalyco/opencode"],["packs",[{uid:"effect",version:"4.0.0-beta.65"}]]]),Object.fromEntries([["repo","pingdotgg/t3code"],["url","https://github.com/pingdotgg/t3code"],["packs",[{uid:"effect",version:"4.0.0-beta.59"}]]])],hooks:[],id:"effect",lintAssets:["effect-no-barrel-imports","effect-tsgo-recommended"],promptDetails:["shared Effect v4 patterns baseline","workspace backend topology and action-orchestration rules","workspace service qualification, Layer, and audit rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["effect","effect-backend-structure","effect-recoverable-actions","effect-service-design"],triggerPackages:["effect","@effect/"]},{category:"detected",description:"Elysia guidance pack.",hooks:[],id:"elysia",lintAssets:[],promptDetails:["shared api-server baseline","workspace route/plugin rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["elysiajs"],triggerPackages:["elysia"]},{category:"detected",description:"Expo guidance pack.",hooks:[],id:"expo",lintAssets:[],promptDetails:["shared expo baseline","workspace native app guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["add-app-clip","animate-expo","building-native-ui","eas-simulator","eas-update-insights","expo-api-routes","expo-brownfield","expo-cicd-workflows","expo-deployment","expo-dev-client","expo-examples","expo-module","expo-observe","expo-skill-eval","expo-tailwind-setup","expo-ui","native-data-fetching","upgrading-expo","use-dom","web-to-native"],triggerPackages:["expo","@expo/"]},{category:"surface",description:"Frontend pack: agent-browser, animation authoring/review, design taste, image generation, frontend domain structure, and mobile-web improvement.",hooks:[],id:"frontend",lintAssets:[],promptDetails:["shared product-ui baseline","workspace UX/browser guidance","workspace frontend domain boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["agent-browser","animate","design-taste-frontend","imagegen-frontend-mobile","imagegen-frontend-web","frontend-domain-structure","improve-mobile-frontend","review-animations"],triggerPackages:[]},{category:"detected",description:"Next.js guidance pack.",hooks:[],id:"nextjs",lintAssets:["next-core"],promptDetails:["shared app-router baseline","workspace next rendering rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["next-best-practices","next-cache-components"],triggerPackages:["next"]},{category:"default",description:"Default planning pack: delivery phase, specs, plans, implementation, and debt resolution.",hooks:[],id:"planning",lintAssets:[],promptDetails:["shared planning baseline","workspace plan/spec execution rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["business-finder","finder-phase","functional-finder","wayfinder","prototype-phase","delivery-phase","design-phase","goalify","grilling","handoff","create-spec","create-plan","implement-spec","verify-behavior","repo-asset-management","resolve-debt-phase"],triggerPackages:[]},{category:"detected",description:"Pulumi guidance pack.",hooks:[],id:"pulumi",lintAssets:[],promptDetails:["shared pulumi baseline","workspace infrastructure-as-code guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["pulumi-overview","pulumi-best-practices","pulumi-component","pulumi-automation-api","pulumi-esc","provider-upgrade","package-usage"],triggerPackages:["@pulumi/","@pulumi/pulumi"]},{category:"default",description:"Default quality pack: test-driven delivery, test-suite design, codebase design, and simplification.",hooks:[],id:"quality",lintAssets:["vitest-core"],promptDetails:["shared change-quality baseline","workspace test-suite and refactor expectations"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["tdd","make-tsuite","codebase-design","simplify"],triggerPackages:[]},{category:"detected",description:"React guidance pack.",hooks:[],id:"react",lintAssets:["react-core","react-you-might-not-need-an-effect"],promptDetails:["shared react structure baseline","workspace react composition rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["async-react-patterns","react-doctor","vercel-composition-patterns","vercel-react-best-practices"],triggerPackages:["react","react-dom"]},{category:"detected",description:"SQLAlchemy schema and Alembic migration guidance pack.",hooks:[],id:"sqlalchemy",lintAssets:[],promptDetails:["shared SQLAlchemy schema and migration baseline"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["sqlalchemy-schema-design"],triggerPackages:["sqlalchemy","alembic"]},{category:"default",description:"Default research pack: parallel research, prototypes, structured review, and architecture inspection.",hooks:[],id:"research",lintAssets:[],promptDetails:["shared investigation baseline","workspace research handoff rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["parallel-research","prototype","review-phase","review","autoreview","improve-codebase-architecture"],triggerPackages:[]},{category:"default",description:"Default requirements pack: requirements phase, grill, and backlog authoring.",hooks:[],id:"requirements",lintAssets:[],promptDetails:["shared requirements baseline","workspace backlog shaping rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["requirements-phase","requirements-grill","domain-modeling","repo-asset-management","write-backlog"],triggerPackages:[]},{category:"default",description:"Default security pack: pipeline architecture, CI audit review, application security best practices, and remediation guardrails.",hooks:[],id:"security",lintAssets:[],promptDetails:["shared security review baseline","evidence-first remediation routing","risk-aware approval discipline"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["architect-pipeline","audit-cicd-security","security-best-practices"],triggerPackages:[]},{category:"default",description:"Default subagents pack: swarm-planner.",hooks:[],id:"subagents",lintAssets:[],promptDetails:["shared delegation baseline","workspace ownership handoffs","subagent manifest scaffold"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec","subagent-manifest"],skills:["swarm-planner"],triggerPackages:[]},{category:"detected",description:"TanStack Query guidance pack.",hooks:[],id:"tanstack-query",lintAssets:["tanstack-query-core"],promptDetails:["shared tanstack query baseline","workspace server-state rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["tanstack-query"],triggerPackages:["@tanstack/react-query"]},{category:"detected",description:"tRPC guidance pack.",hooks:[],id:"trpc",lintAssets:[],promptDetails:["shared contract-first baseline","workspace client/server boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:[],triggerPackages:["@trpc/"]},{category:"detected",description:"Turborepo guidance pack.",hooks:[],id:"turborepo",lintAssets:[],promptDetails:["shared monorepo baseline","workspace task boundary rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["turborepo"],triggerPackages:["turbo"]},{category:"language",description:"Shared Python language pack that compounds the agnostic backend domain base with Python import structure, async, style, testing, and design guidance.",hooks:["format-edited-file"],id:"python",lintAssets:[],promptDetails:[],promptSurfaces:[],skills:["async-python-patterns","backend-domain-structure","python-backend-structure","python-code-style","python-design-patterns","python-testing-patterns"],triggerPackages:[]},{category:"language",description:"Shared JavaScript / TypeScript language pack for hook and language-level scaffold assets.",hooks:["format-edited-file"],id:"typescript",lintAssets:["typescript-anti-slop"],promptDetails:[],promptSurfaces:[],skills:["quality-types"],triggerPackages:["typescript"]}];import{createHash as createHash3}from"node:crypto";import{existsSync as existsSync2,readdirSync as readdirSync2,readFileSync as readFileSync3,renameSync}from"node:fs";var exports_HttpApi={};__export(exports_HttpApi,{reflect:()=>reflect,make:()=>make38,isHttpApi:()=>isHttpApi,AdditionalSchemas:()=>AdditionalSchemas});var exports_HttpApiEndpoint={};__export(exports_HttpApiEndpoint,{put:()=>put3,post:()=>post3,patch:()=>patch3,options:()=>options3,make:()=>make37,isHttpApiEndpoint:()=>isHttpApiEndpoint,head:()=>head3,getSuccessSchemas:()=>getSuccessSchemas,getPayloadSchemas:()=>getPayloadSchemas,getErrorSchemas:()=>getErrorSchemas,get:()=>get7,delete:()=>del3});var exports_HttpApiSchema={};__export(exports_HttpApiSchema,{status:()=>status,isStreamUint8Array:()=>isStreamUint8Array,isStreamSse:()=>isStreamSse,isStreamSchema:()=>isStreamSchema,isNoContent:()=>isNoContent,getStatusSuccess:()=>getStatusSuccess,getStatusStream:()=>getStatusStream,getStatusError:()=>getStatusError,getResponseEncoding:()=>getResponseEncoding,getPayloadEncoding:()=>getPayloadEncoding,asUint8Array:()=>asUint8Array,asText:()=>asText,asNoContent:()=>asNoContent,asMultipartStream:()=>asMultipartStream,asMultipart:()=>asMultipart,asJson:()=>asJson,asFormUrlEncoded:()=>asFormUrlEncoded,StreamUint8Array:()=>StreamUint8Array,StreamSse:()=>StreamSse,NoContent:()=>NoContent,MultipartTypeId:()=>MultipartTypeId,MultipartStreamTypeId:()=>MultipartStreamTypeId,Empty:()=>Empty3,Created:()=>Created,Accepted:()=>Accepted});var statusCodeByLiteral={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};var StreamSchemaTypeId="~effect/httpapi/HttpApiSchema/Stream";function status(code){const statusCode=typeof code==="string"?statusCodeByLiteral[code]:code;return(self)=>self.annotate({httpApiStatus:statusCode})}var Empty3=(code)=>Void2.pipe(status(code));var NoContent=Empty3(204);var Created=Empty3(201);var Accepted=Empty3(202);function asNoContent(options3){return(self)=>{return Void2.pipe(decodeTo2(toType2(self),transform2({decode:options3.decode,encode:constVoid})))}}var streamSchema=declare(isStream);var StreamSse=(options3)=>{const events=options3.events??(options3.data===undefined?undefined:Struct({id:UndefinedOr(String4),event:String4,data:fromJsonString2(options3.data)}));if(events===undefined){throw new Error("StreamSse requires either an events schema or a data schema")}return make19(streamSchema.ast,{[StreamSchemaTypeId]:StreamSchemaTypeId,_tag:"StreamSse",mode:"sse",sseMode:options3.events===undefined?"data":"events",contentType:options3.contentType??defaultStreamContentType("sse"),events,error:options3.error??Never2})};var StreamUint8Array=(options3)=>make19(streamSchema.ast,{[StreamSchemaTypeId]:StreamSchemaTypeId,_tag:"StreamUint8Array",mode:"uint8array",contentType:options3?.contentType??defaultStreamContentType("uint8array")});var isStreamSchema=(u)=>isSchema(u)&&hasProperty(u,StreamSchemaTypeId);var isStreamSse=(u)=>isStreamSchema(u)&&u._tag==="StreamSse";var isStreamUint8Array=(u)=>isStreamSchema(u)&&u._tag==="StreamUint8Array";function defaultStreamContentType(mode){switch(mode){case"sse":return"text/event-stream";case"uint8array":return"application/octet-stream"}}var MultipartTypeId="~effect/httpapi/HttpApiSchema/Multipart";function asMultipart(options3){return(self)=>self.pipe(brand2(MultipartTypeId)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"buffered",contentType:defaultContentType("Multipart"),limits:options3}})}var MultipartStreamTypeId="~effect/httpapi/HttpApiSchema/MultipartStream";function asMultipartStream(options3){return(self)=>self.pipe(brand2(MultipartStreamTypeId)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"stream",contentType:defaultContentType("Multipart"),limits:options3}})}function asNonMultipartEncoding(self,options3){return self.annotate({"~httpApiEncoding":{_tag:options3._tag,contentType:options3.contentType??defaultContentType(options3._tag)}})}function defaultContentType(_tag){switch(_tag){case"Multipart":return"multipart/form-data";case"Json":return"application/json";case"FormUrlEncoded":return"application/x-www-form-urlencoded";case"Uint8Array":return"application/octet-stream";case"Text":return"text/plain"}}function asJson(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Json",...options3})}function asFormUrlEncoded(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"FormUrlEncoded",...options3})}function asText(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Text",...options3})}function asUint8Array(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Uint8Array",...options3})}var isNoContent=(ast)=>{if(isVoid(ast))return true;const encoded=toEncoded(ast);if(isVoid(encoded))return true;const target=ast.encoding?.[0].to;if(target===undefined)return false;return isVoid(target)};var resolveHttpApiEncoding=resolveAt2("~httpApiEncoding");var resolveHttpApiStatus=resolveAt2("httpApiStatus");var defaultJsonEncoding={_tag:"Json",contentType:"application/json"};var defaultUrlEncodedEncoding={_tag:"FormUrlEncoded",contentType:"application/x-www-form-urlencoded"};function getEncoding(ast){return resolveHttpApiEncoding(ast)??defaultJsonEncoding}function getPayloadEncoding(ast,method){const encoding=resolveHttpApiEncoding(ast);if(encoding)return encoding;return hasBody(method)?defaultJsonEncoding:defaultUrlEncodedEncoding}function getResponseEncoding(ast){const out=getEncoding(ast);if(out._tag==="Multipart"){throw new Error("Multipart is not supported in response")}return out}function getStatusSuccess(self){return resolveHttpApiStatus(self)??200}function getStatusStream(self){return getStatusSuccess(self.ast)}function getStatusError(self){return resolveHttpApiStatus(self)??500}function normalize(contentType){const normalized=contentType.toLowerCase().trim();const index=normalized.indexOf(";");return index===-1?normalized:normalized.slice(0,index).trim()}var TypeId47="~effect/httpapi/HttpApiEndpoint";var isHttpApiEndpoint=(u)=>hasProperty(u,TypeId47);function getPayloadSchemas(endpoint){const result3=[];for(const{schemas}of endpoint.payload.values()){result3.push(...schemas)}return result3}function getSuccessSchemas(endpoint){const schemas=Array.from(endpoint.success);return isArrayNonEmpty2(schemas)?schemas:[NoContent]}function getErrorSchemas(endpoint){const schemas=new Set(endpoint.error);for(const middleware2 of endpoint.middlewares){const key=middleware2;for(const schema2 of key.error){schemas.add(schema2)}}return Array.from(schemas)}var Proto16={[TypeId47]:TypeId47,pipe(){return pipeArguments(this,arguments)},prefix(prefix){return makeProto({...optionsFromEndpoint(this),path:prefixPath(this.path,prefix)})},middleware(middleware2){return makeProto({...optionsFromEndpoint(this),middlewares:new Set([...this.middlewares,middleware2])})},annotate(key,value3){return makeProto({...optionsFromEndpoint(this),annotations:add(this.annotations,key,value3)})},annotateMerge(annotations){return makeProto({...optionsFromEndpoint(this),annotations:merge(this.annotations,annotations)})}};var optionsFromEndpoint=(endpoint)=>({identifier:endpoint.identifier,path:endpoint.path,method:endpoint.method,params:endpoint.params,query:endpoint.query,headers:endpoint.headers,payload:endpoint.payload,success:endpoint.success,error:endpoint.error,annotations:endpoint.annotations,middlewares:endpoint.middlewares});function makeProto(options3){function HttpApiEndpoint(){}Object.setPrototypeOf(HttpApiEndpoint,Proto16);return Object.assign(HttpApiEndpoint,options3)}var make37=(method)=>(identifier2,path4,options3)=>{const disableCodecs=options3?.disableCodecs??false;const transformStringTree=disableCodecs?identity:toCodecStringTree;return makeProto({identifier:identifier2,path:path4,method,params:ensureStruct(options3?.params,transformStringTree),query:ensureStruct(options3?.query,transformStringTree),headers:ensureStruct(options3?.headers,transformStringTree),payload:getPayload(options3?.payload,method,disableCodecs),success:getSuccessResponse(options3?.success,method,disableCodecs),error:getErrorResponse(options3?.error,disableCodecs),annotations:empty(),middlewares:new Set})};function ensureStruct(params,transform6){if(params===undefined)return;if(isSchema(params))return transform6(params);return transform6(Struct(params))}function getPayload(payload,method,disableCodecs){const result3=new Map;if(payload===undefined)return result3;const schemas=Array.isArray(payload)?payload:isSchema(payload)?[payload]:[Struct(payload).pipe(asFormUrlEncoded())];const transform6=disableCodecs?identity:transformPayload;for(const schema2 of schemas){const encoding=getPayloadEncoding(schema2.ast,method);const contentType=normalize(encoding.contentType);const existing=result3.get(contentType);if(existing){if(existing.encoding._tag!==encoding._tag){throw new Error(`Multiple payload encodings for content-type: ${encoding.contentType}`)}if(existing.encoding._tag==="Multipart"){throw new Error(`Multiple multipart payloads for content-type: ${encoding.contentType}`)}existing.schemas.push(transform6(schema2,method))}else{result3.set(contentType,{encoding,schemas:[transform6(schema2,method)]})}}return result3}var reservedStreamFailureEvent="effect/httpapi/stream/failure";function getSuccessResponse(success,method,disableCodecs){if(success===undefined)return new Set;const schemas=ensure(success);validateSuccessResponse(schemas,method);return new Set(disableCodecs?schemas:schemas.map((schema2)=>isStreamSchema(schema2)?schema2:transformResponse2(schema2)))}function getErrorResponse(error2,disableCodecs){if(error2===undefined)return new Set;const schemas=ensure(error2);for(const schema2 of schemas){if(isStreamSchema(schema2)){throw new Error("Streaming schemas are not supported in error responses")}}return new Set(disableCodecs?schemas:schemas.map(transformResponse2))}function validateSuccessResponse(schemas,method){const statuses=new Map;for(const schema2 of schemas){if(isStreamSchema(schema2)){validateStreamSuccess(schema2,method);const status2=getStatusStream(schema2);const entry=getStatusEntry(statuses,status2);if(entry.stream!==undefined){throw new Error(`Multiple streaming success responses for status: ${status2}`)}if(entry.noContent){throw new Error(`Cannot combine no-content and streaming success responses for status: ${status2}`)}if(entry.bufferedContentTypes.has(normalize(schema2.contentType))){throw new Error(`Cannot combine buffered and streaming success responses for status ${status2} and content-type: ${schema2.contentType}`)}statuses.set(status2,{...entry,stream:schema2})}else{const status2=getStatusSuccess(schema2.ast);const entry=getStatusEntry(statuses,status2);const noContent=isNoContent(schema2.ast);if(entry.stream!==undefined){if(noContent){throw new Error(`Cannot combine no-content and streaming success responses for status: ${status2}`)}const encoding=getResponseEncoding(schema2.ast);if(normalize(encoding.contentType)===normalize(entry.stream.contentType)){throw new Error(`Cannot combine buffered and streaming success responses for status ${status2} and content-type: ${encoding.contentType}`)}}if(!noContent){entry.bufferedContentTypes.add(normalize(getResponseEncoding(schema2.ast).contentType))}entry.noContent=entry.noContent||noContent}}}function getStatusEntry(statuses,status2){let entry=statuses.get(status2);if(entry===undefined){entry={bufferedContentTypes:new Set,noContent:false};statuses.set(status2,entry)}return entry}function validateStreamSuccess(schema2,method){if(method==="HEAD"){throw new Error("HEAD endpoints cannot declare streaming success responses")}if(isStreamSse(schema2)&&hasReservedSseEventName(schema2.events.ast)){throw new Error(`SSE event name is reserved: ${reservedStreamFailureEvent}`)}}function hasReservedSseEventName(ast){return hasReservedEventName(toEncoded(ast),new Set)}function hasReservedEventName(ast,seen){if(seen.has(ast))return false;seen.add(ast);if(isUnion(ast)){return ast.types.some((type)=>hasReservedEventName(type,seen))}if(isSuspend(ast)){return hasReservedEventName(ast.thunk(),seen)}if(!isObjects(ast))return false;const event=ast.propertySignatures.find((ps)=>ps.name==="event");return event!==undefined&&hasReservedEventLiteral(event.type,seen)}function hasReservedEventLiteral(ast,seen){if(seen.has(ast))return false;seen.add(ast);const encoded=toEncoded(ast);if(encoded!==ast){return hasReservedEventLiteral(encoded,seen)}if(isLiteral(ast)){return ast.literal===reservedStreamFailureEvent}if(isUnion(ast)){return ast.types.some((type)=>hasReservedEventLiteral(type,seen))}if(isSuspend(ast)){return hasReservedEventLiteral(ast.thunk(),seen)}return false}function transformResponse2(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":return toCodecJson(schema2);case"FormUrlEncoded":return toCodecStringTree(schema2);case"Text":case"Uint8Array":return schema2}}function transformPayload(schema2,method){const encoding=getPayloadEncoding(schema2.ast,method);switch(encoding._tag){case"Json":return toCodecJson(schema2);case"FormUrlEncoded":return toCodecStringTree(schema2);case"Text":case"Uint8Array":case"Multipart":return schema2}}var get7=make37("GET");var post3=make37("POST");var put3=make37("PUT");var patch3=make37("PATCH");var del3=make37("DELETE");var head3=make37("HEAD");var options3=make37("OPTIONS");var TypeId48="~effect/httpapi/HttpApi";var isHttpApi=(u)=>hasProperty(u,TypeId48);var Proto17={[TypeId48]:TypeId48,pipe(){return pipeArguments(this,arguments)},add(...toAdd){const groups={...this.groups};for(const group of toAdd){set(groups,group.identifier,group)}return makeProto2({...optionsFromApi(this),groups})},addHttpApi(api){const newGroups={...this.groups};for(const key in api.groups){const group=api.groups[key];set(newGroups,key,group.annotateMerge(merge(api.annotations,group.annotations)))}return makeProto2({...optionsFromApi(this),groups:newGroups})},prefix(prefix){return makeProto2({...optionsFromApi(this),groups:map2(this.groups,(group)=>group.prefix(prefix))})},middleware(tag2){return makeProto2({...optionsFromApi(this),groups:map2(this.groups,(group)=>group.middleware(tag2))})},annotate(key,value3){return makeProto2({...optionsFromApi(this),annotations:add(this.annotations,key,value3)})},annotateMerge(annotations){return makeProto2({...optionsFromApi(this),annotations:merge(this.annotations,annotations)})}};var optionsFromApi=(api)=>({identifier:api.identifier,groups:api.groups,annotations:api.annotations});var makeProto2=(options4)=>{function HttpApi(){}Object.setPrototypeOf(HttpApi,Proto17);return Object.assign(HttpApi,options4)};var make38=(identifier2)=>makeProto2({identifier:identifier2,groups:{},annotations:empty()});var reflect=(self,options4)=>{const groups=Object.values(self.groups);for(const group of groups){const groupAnnotations=merge(self.annotations,group.annotations);options4.onGroup({group,mergedAnnotations:groupAnnotations});const endpoints=Object.values(group.endpoints);for(const endpoint of endpoints){if(options4.predicate&&!options4.predicate({endpoint,group}))continue;options4.onEndpoint({group,endpoint,middleware:endpoint.middlewares,mergedAnnotations:merge(groupAnnotations,endpoint.annotations),successes:extractResponseContent(getSuccessSchemas(endpoint),getStatusSuccess),errors:extractResponseContent(getErrorSchemas(endpoint),getStatusError)})}}};var extractResponseContent=(schemas,getStatus)=>{const map15=new Map;schemas.forEach(add3);return map15;function add3(schema2){if(isStreamSchema(schema2))return;const ast=schema2.ast;const status2=getStatus(ast);const schemas2=map15.get(status2);if(schemas2===undefined){map15.set(status2,[schema2])}else{schemas2.push(schema2)}}};class AdditionalSchemas extends Service()("effect/httpapi/HttpApi/AdditionalSchemas"){}var decode=(schema2)=>()=>{const decode2=decodeEffect2(NonEmptyArray(schema2));return fromTransform((upstream,_scope)=>succeed6(flatMap3(upstream,(chunk)=>decode2(chunk))))};var decode2=()=>fromTransform((upstream,_scope)=>sync2(()=>{let buffer2=[];let retry5;const parser2=makeParser2((event)=>{if(event._tag==="Retry"){retry5=event}else{buffer2.push(event)}});const pump=flatMap3(upstream,(arr)=>{for(let i=0;i<arr.length;i++){parser2.feed(arr[i])}return void_3});return suspend2(function loop(){if(isArrayNonEmpty2(buffer2)){const out=buffer2;buffer2=[];return succeed6(out)}else if(retry5){return fail6(retry5)}return flatMap3(pump,loop)})}));var decodeSchema=(schema2)=>pipeTo(decode2(),decode(EventEncoded.pipe(decodeTo2(schema2)))());function makeParser2(onParse){let isFirstChunk;let buffer2;let startingPosition;let startingFieldLength;let eventId;let lastEventId;let eventName;let data;reset3();return{feed,reset:reset3};function reset3(){isFirstChunk=true;buffer2="";startingPosition=0;startingFieldLength=-1;eventId=undefined;eventName=undefined;data=""}function feed(chunk){buffer2=buffer2?buffer2+chunk:chunk;if(isFirstChunk&&hasBom(buffer2)){buffer2=buffer2.slice(BOM.length)}isFirstChunk=false;const length=buffer2.length;let position=0;let discardTrailingNewline=false;while(position<length){if(discardTrailingNewline){if(buffer2[position]===`
281
+ `}writeStdout(rendered);return outcome.kind==="expected-failure"||resultFailed(outcome.result)?1:0}if(outcome.kind==="expected-failure"){writeStdout(renderExpectedFailure(outcome.failure,humanEnvironment));return 1}writeStdout(renderOperationResult(outcome.result,humanEnvironment));return resultFailed(outcome.result)?1:0};var UpdateInteraction=Service("@punks/cli/features/scaffold-update/UpdateInteraction");class ScaffoldUpdateOperationFailure extends TaggedErrorClass()("@punks/cli/scaffold-update/ScaffoldUpdateOperationFailure",{cause:Defect(),message:String4,operation:Literal2("update-scaffold")}){}var ScaffoldUpdateOperations=Service("@punks/cli/features/scaffold-update/ScaffoldUpdateOperations");var runScaffoldUpdateApplication=fn2("ScaffoldUpdate.run")(function*runScaffoldUpdateApplication2(input){const interaction=yield*UpdateInteraction;const operations=yield*ScaffoldUpdateOperations;return yield*operations.run(input,interaction)});var desiredFilesByPath=(files)=>{const indexed=new Map;for(const file5 of files){indexed.set(file5.path,indexed.has(file5.path)?null:file5)}return indexed};var recoveryAction=({conflict,desired,fixedManagedPaths})=>{if(conflict._tag!=="UserModifiedScaffoldEntryConflict"||conflict.item!=="file"||conflict.operation!=="update"||!fixedManagedPaths.has(conflict.identity)){return null}const file5=desired.get(conflict.identity);return file5===undefined||file5===null?null:{_tag:"ArchiveAndReplaceScaffoldFile",desired:file5,identity:conflict.identity,item:"file"}};var planFixedManagedRecovery=({authority,fixedManagedPaths,plan})=>{if(authority._tag!=="VerifiedDesiredBaseline"){return plan}const desired=desiredFilesByPath(authority.files);const recoveries=new Map;for(const conflict of plan.conflicts){const action2=recoveryAction({conflict,desired,fixedManagedPaths});if(action2!==null){recoveries.set(conflict,action2)}}if(recoveries.size===0){return plan}return{...plan,actions:[...plan.actions,...recoveries.values()],conflicts:plan.conflicts.filter((conflict)=>!recoveries.has(conflict))}};import path7 from"node:path";var packCatalog=[{category:"surface",description:"Backend pack: domain structure, recoverable actions, and logging.",hooks:[],id:"backend",lintAssets:[],promptDetails:["shared backend domain baseline","workspace backend action/recovery guidance","workspace logging/observability guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["backend-domain-structure","backend-recoverable-actions","logging-best-practices"],triggerPackages:[]},{category:"detected",description:"Better Auth guidance pack.",hooks:[],id:"better-auth",lintAssets:[],promptDetails:["shared auth guardrails","workspace auth boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["better-auth-best-practices"],triggerPackages:["better-auth"]},{category:"default",description:"Default debug pack: runtime debugging, ClawPatch bug discovery/resolution, and debug-agent workflow.",hooks:[],id:"debug",lintAssets:[],promptDetails:["shared runtime debugging baseline","workspace evidence-first debugging workflow"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["debugging-phase","bug-discovery-phase","bug-resolution-phase","debug-agent"],triggerPackages:[]},{category:"default",description:"Default docs pack: docs ingest plus public-doc and skill-writing primitives.",hooks:[],id:"docs",lintAssets:[],promptDetails:["shared docs baseline","public-doc writing flow","docs scope spec"],promptSurfaces:["shared-agents","root-prompt-spec","docs-prompt-spec"],skills:["docs-ingest-phase","docs-onboarding","writing-fragments","writing-beats","writing-shape","writing-for-agents","write-graph-based-skills","rule-authoring"],triggerPackages:[]},{category:"default",description:"Default misc pack: lightweight agent interaction helpers.",hooks:[],id:"misc",lintAssets:[],promptDetails:["shared agent interaction helpers"],promptSurfaces:["shared-agents"],skills:["handback","show-me","wait-what"],triggerPackages:[]},{category:"detected",description:"Drizzle guidance pack.",hooks:[],id:"drizzle",lintAssets:[],promptDetails:["shared data-layer baseline","workspace db flow rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:[],triggerPackages:["drizzle-kit","drizzle-orm"]},{category:"detected",description:"Effect guidance pack family.",exampleRepositories:[Object.fromEntries([["repo","AnswerOverflow/AnswerOverflow"],["url","https://github.com/AnswerOverflow/AnswerOverflow"],["packs",[{uid:"effect",version:"^3.20.0"}]]]),Object.fromEntries([["repo","rhyssullivan/executor"],["url","https://github.com/rhyssullivan/executor"],["packs",[{uid:"effect",version:"4.0.0-beta.59"}]]]),Object.fromEntries([["repo","alchemy-run/alchemy-effect"],["url","https://github.com/alchemy-run/alchemy-effect"],["packs",[{uid:"effect",version:">=4.0.0-beta.66 || >=4.0.0"}]]]),Object.fromEntries([["repo","anomalyco/opencode"],["url","https://github.com/anomalyco/opencode"],["packs",[{uid:"effect",version:"4.0.0-beta.65"}]]]),Object.fromEntries([["repo","pingdotgg/t3code"],["url","https://github.com/pingdotgg/t3code"],["packs",[{uid:"effect",version:"4.0.0-beta.59"}]]])],hooks:[],id:"effect",lintAssets:["effect-no-barrel-imports","effect-tsgo-recommended"],promptDetails:["shared Effect v4 patterns baseline","workspace backend topology and action-orchestration rules","workspace service qualification, Layer, and audit rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["effect","effect-backend-structure","effect-recoverable-actions","effect-service-design"],triggerPackages:["effect","@effect/"]},{category:"detected",description:"Elysia guidance pack.",hooks:[],id:"elysia",lintAssets:[],promptDetails:["shared api-server baseline","workspace route/plugin rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["elysiajs"],triggerPackages:["elysia"]},{category:"detected",description:"Expo guidance pack.",hooks:[],id:"expo",lintAssets:[],promptDetails:["shared expo baseline","workspace native app guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["add-app-clip","animate-expo","building-native-ui","eas-simulator","eas-update-insights","expo-api-routes","expo-brownfield","expo-cicd-workflows","expo-deployment","expo-dev-client","expo-examples","expo-module","expo-observe","expo-skill-eval","expo-tailwind-setup","expo-ui","native-data-fetching","upgrading-expo","use-dom","web-to-native"],triggerPackages:["expo","@expo/"]},{category:"surface",description:"Frontend pack: agent-browser, animation authoring/review, design taste, image generation, frontend domain structure, and mobile-web improvement.",hooks:[],id:"frontend",lintAssets:[],promptDetails:["shared product-ui baseline","workspace UX/browser guidance","workspace frontend domain boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["agent-browser","animate","design-taste-frontend","imagegen-frontend-mobile","imagegen-frontend-web","frontend-domain-structure","improve-mobile-frontend","review-animations"],triggerPackages:[]},{category:"detected",description:"Next.js guidance pack.",hooks:[],id:"nextjs",lintAssets:["next-core"],promptDetails:["shared app-router baseline","workspace next rendering rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["next-best-practices","next-cache-components"],triggerPackages:["next"]},{category:"default",description:"Default planning pack: delivery phase, specs, plans, implementation, and debt resolution.",hooks:[],id:"planning",lintAssets:[],promptDetails:["shared planning baseline","workspace plan/spec execution rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["business-finder","finder-phase","functional-finder","wayfinder","prototype-phase","delivery-phase","design-phase","goalify","grilling","handoff","create-spec","create-plan","implement-spec","repo-asset-management","resolve-debt-phase"],triggerPackages:[]},{category:"default",description:"Default verification pack.",hooks:[],id:"verification",lintAssets:[],promptDetails:[],promptSurfaces:[],skills:["create-verification-skill","update-verification-skill","verify-behavior"],triggerPackages:[]},{category:"detected",description:"Pulumi guidance pack.",hooks:[],id:"pulumi",lintAssets:[],promptDetails:["shared pulumi baseline","workspace infrastructure-as-code guidance"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["pulumi-overview","pulumi-best-practices","pulumi-component","pulumi-automation-api","pulumi-esc","provider-upgrade","package-usage"],triggerPackages:["@pulumi/","@pulumi/pulumi"]},{category:"default",description:"Default quality pack: test-driven delivery, test-suite design, codebase design, and simplification.",hooks:[],id:"quality",lintAssets:["vitest-core"],promptDetails:["shared change-quality baseline","workspace test-suite and refactor expectations"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["tdd","make-tsuite","codebase-design","simplify"],triggerPackages:[]},{category:"detected",description:"React guidance pack.",hooks:[],id:"react",lintAssets:["react-core","react-you-might-not-need-an-effect"],promptDetails:["shared react structure baseline","workspace react composition rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["async-react-patterns","react-doctor","vercel-composition-patterns","vercel-react-best-practices"],triggerPackages:["react","react-dom"]},{category:"detected",description:"SQLAlchemy schema and Alembic migration guidance pack.",hooks:[],id:"sqlalchemy",lintAssets:[],promptDetails:["shared SQLAlchemy schema and migration baseline"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["sqlalchemy-schema-design"],triggerPackages:["sqlalchemy","alembic"]},{category:"default",description:"Default research pack: parallel research, prototypes, structured review, and architecture inspection.",hooks:[],id:"research",lintAssets:[],promptDetails:["shared investigation baseline","workspace research handoff rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["parallel-research","prototype","review-phase","review","autoreview","improve-codebase-architecture"],triggerPackages:[]},{category:"default",description:"Default requirements pack: requirements phase, grill, and backlog authoring.",hooks:[],id:"requirements",lintAssets:[],promptDetails:["shared requirements baseline","workspace backlog shaping rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["requirements-phase","requirements-grill","domain-modeling","repo-asset-management","write-backlog"],triggerPackages:[]},{category:"default",description:"Default security pack: pipeline architecture, CI audit review, application security best practices, and remediation guardrails.",hooks:[],id:"security",lintAssets:[],promptDetails:["shared security review baseline","evidence-first remediation routing","risk-aware approval discipline"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["architect-pipeline","audit-cicd-security","security-best-practices"],triggerPackages:[]},{category:"default",description:"Default subagents pack: swarm-planner.",hooks:[],id:"subagents",lintAssets:[],promptDetails:["shared delegation baseline","workspace ownership handoffs","subagent manifest scaffold"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec","subagent-manifest"],skills:["swarm-planner"],triggerPackages:[]},{category:"detected",description:"TanStack Query guidance pack.",hooks:[],id:"tanstack-query",lintAssets:["tanstack-query-core"],promptDetails:["shared tanstack query baseline","workspace server-state rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["tanstack-query"],triggerPackages:["@tanstack/react-query"]},{category:"detected",description:"tRPC guidance pack.",hooks:[],id:"trpc",lintAssets:[],promptDetails:["shared contract-first baseline","workspace client/server boundaries"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:[],triggerPackages:["@trpc/"]},{category:"detected",description:"Turborepo guidance pack.",hooks:[],id:"turborepo",lintAssets:[],promptDetails:["shared monorepo baseline","workspace task boundary rules"],promptSurfaces:["shared-agents","root-prompt-spec","workspace-prompt-spec"],skills:["turborepo"],triggerPackages:["turbo"]},{category:"language",description:"Shared Python language pack that compounds the agnostic backend domain base with Python import structure, async, style, testing, and design guidance.",hooks:["format-edited-file"],id:"python",lintAssets:[],promptDetails:[],promptSurfaces:[],skills:["async-python-patterns","backend-domain-structure","python-backend-structure","python-code-style","python-design-patterns","python-testing-patterns"],triggerPackages:[]},{category:"language",description:"Shared JavaScript / TypeScript language pack for hook and language-level scaffold assets.",hooks:["format-edited-file"],id:"typescript",lintAssets:["typescript-anti-slop"],promptDetails:[],promptSurfaces:[],skills:["quality-types"],triggerPackages:["typescript"]}];import{createHash as createHash3}from"node:crypto";import{existsSync as existsSync2,readdirSync as readdirSync2,readFileSync as readFileSync3,renameSync}from"node:fs";var exports_HttpApi={};__export(exports_HttpApi,{reflect:()=>reflect,make:()=>make38,isHttpApi:()=>isHttpApi,AdditionalSchemas:()=>AdditionalSchemas});var exports_HttpApiEndpoint={};__export(exports_HttpApiEndpoint,{put:()=>put3,post:()=>post3,patch:()=>patch3,options:()=>options3,make:()=>make37,isHttpApiEndpoint:()=>isHttpApiEndpoint,head:()=>head3,getSuccessSchemas:()=>getSuccessSchemas,getPayloadSchemas:()=>getPayloadSchemas,getErrorSchemas:()=>getErrorSchemas,get:()=>get7,delete:()=>del3});var exports_HttpApiSchema={};__export(exports_HttpApiSchema,{status:()=>status,isStreamUint8Array:()=>isStreamUint8Array,isStreamSse:()=>isStreamSse,isStreamSchema:()=>isStreamSchema,isNoContent:()=>isNoContent,getStatusSuccess:()=>getStatusSuccess,getStatusStream:()=>getStatusStream,getStatusError:()=>getStatusError,getResponseEncoding:()=>getResponseEncoding,getPayloadEncoding:()=>getPayloadEncoding,asUint8Array:()=>asUint8Array,asText:()=>asText,asNoContent:()=>asNoContent,asMultipartStream:()=>asMultipartStream,asMultipart:()=>asMultipart,asJson:()=>asJson,asFormUrlEncoded:()=>asFormUrlEncoded,StreamUint8Array:()=>StreamUint8Array,StreamSse:()=>StreamSse,NoContent:()=>NoContent,MultipartTypeId:()=>MultipartTypeId,MultipartStreamTypeId:()=>MultipartStreamTypeId,Empty:()=>Empty3,Created:()=>Created,Accepted:()=>Accepted});var statusCodeByLiteral={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};var StreamSchemaTypeId="~effect/httpapi/HttpApiSchema/Stream";function status(code){const statusCode=typeof code==="string"?statusCodeByLiteral[code]:code;return(self)=>self.annotate({httpApiStatus:statusCode})}var Empty3=(code)=>Void2.pipe(status(code));var NoContent=Empty3(204);var Created=Empty3(201);var Accepted=Empty3(202);function asNoContent(options3){return(self)=>{return Void2.pipe(decodeTo2(toType2(self),transform2({decode:options3.decode,encode:constVoid})))}}var streamSchema=declare(isStream);var StreamSse=(options3)=>{const events=options3.events??(options3.data===undefined?undefined:Struct({id:UndefinedOr(String4),event:String4,data:fromJsonString2(options3.data)}));if(events===undefined){throw new Error("StreamSse requires either an events schema or a data schema")}return make19(streamSchema.ast,{[StreamSchemaTypeId]:StreamSchemaTypeId,_tag:"StreamSse",mode:"sse",sseMode:options3.events===undefined?"data":"events",contentType:options3.contentType??defaultStreamContentType("sse"),events,error:options3.error??Never2})};var StreamUint8Array=(options3)=>make19(streamSchema.ast,{[StreamSchemaTypeId]:StreamSchemaTypeId,_tag:"StreamUint8Array",mode:"uint8array",contentType:options3?.contentType??defaultStreamContentType("uint8array")});var isStreamSchema=(u)=>isSchema(u)&&hasProperty(u,StreamSchemaTypeId);var isStreamSse=(u)=>isStreamSchema(u)&&u._tag==="StreamSse";var isStreamUint8Array=(u)=>isStreamSchema(u)&&u._tag==="StreamUint8Array";function defaultStreamContentType(mode){switch(mode){case"sse":return"text/event-stream";case"uint8array":return"application/octet-stream"}}var MultipartTypeId="~effect/httpapi/HttpApiSchema/Multipart";function asMultipart(options3){return(self)=>self.pipe(brand2(MultipartTypeId)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"buffered",contentType:defaultContentType("Multipart"),limits:options3}})}var MultipartStreamTypeId="~effect/httpapi/HttpApiSchema/MultipartStream";function asMultipartStream(options3){return(self)=>self.pipe(brand2(MultipartStreamTypeId)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"stream",contentType:defaultContentType("Multipart"),limits:options3}})}function asNonMultipartEncoding(self,options3){return self.annotate({"~httpApiEncoding":{_tag:options3._tag,contentType:options3.contentType??defaultContentType(options3._tag)}})}function defaultContentType(_tag){switch(_tag){case"Multipart":return"multipart/form-data";case"Json":return"application/json";case"FormUrlEncoded":return"application/x-www-form-urlencoded";case"Uint8Array":return"application/octet-stream";case"Text":return"text/plain"}}function asJson(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Json",...options3})}function asFormUrlEncoded(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"FormUrlEncoded",...options3})}function asText(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Text",...options3})}function asUint8Array(options3){return(self)=>asNonMultipartEncoding(self,{_tag:"Uint8Array",...options3})}var isNoContent=(ast)=>{if(isVoid(ast))return true;const encoded=toEncoded(ast);if(isVoid(encoded))return true;const target=ast.encoding?.[0].to;if(target===undefined)return false;return isVoid(target)};var resolveHttpApiEncoding=resolveAt2("~httpApiEncoding");var resolveHttpApiStatus=resolveAt2("httpApiStatus");var defaultJsonEncoding={_tag:"Json",contentType:"application/json"};var defaultUrlEncodedEncoding={_tag:"FormUrlEncoded",contentType:"application/x-www-form-urlencoded"};function getEncoding(ast){return resolveHttpApiEncoding(ast)??defaultJsonEncoding}function getPayloadEncoding(ast,method){const encoding=resolveHttpApiEncoding(ast);if(encoding)return encoding;return hasBody(method)?defaultJsonEncoding:defaultUrlEncodedEncoding}function getResponseEncoding(ast){const out=getEncoding(ast);if(out._tag==="Multipart"){throw new Error("Multipart is not supported in response")}return out}function getStatusSuccess(self){return resolveHttpApiStatus(self)??200}function getStatusStream(self){return getStatusSuccess(self.ast)}function getStatusError(self){return resolveHttpApiStatus(self)??500}function normalize(contentType){const normalized=contentType.toLowerCase().trim();const index=normalized.indexOf(";");return index===-1?normalized:normalized.slice(0,index).trim()}var TypeId47="~effect/httpapi/HttpApiEndpoint";var isHttpApiEndpoint=(u)=>hasProperty(u,TypeId47);function getPayloadSchemas(endpoint){const result3=[];for(const{schemas}of endpoint.payload.values()){result3.push(...schemas)}return result3}function getSuccessSchemas(endpoint){const schemas=Array.from(endpoint.success);return isArrayNonEmpty2(schemas)?schemas:[NoContent]}function getErrorSchemas(endpoint){const schemas=new Set(endpoint.error);for(const middleware2 of endpoint.middlewares){const key=middleware2;for(const schema2 of key.error){schemas.add(schema2)}}return Array.from(schemas)}var Proto16={[TypeId47]:TypeId47,pipe(){return pipeArguments(this,arguments)},prefix(prefix){return makeProto({...optionsFromEndpoint(this),path:prefixPath(this.path,prefix)})},middleware(middleware2){return makeProto({...optionsFromEndpoint(this),middlewares:new Set([...this.middlewares,middleware2])})},annotate(key,value3){return makeProto({...optionsFromEndpoint(this),annotations:add(this.annotations,key,value3)})},annotateMerge(annotations){return makeProto({...optionsFromEndpoint(this),annotations:merge(this.annotations,annotations)})}};var optionsFromEndpoint=(endpoint)=>({identifier:endpoint.identifier,path:endpoint.path,method:endpoint.method,params:endpoint.params,query:endpoint.query,headers:endpoint.headers,payload:endpoint.payload,success:endpoint.success,error:endpoint.error,annotations:endpoint.annotations,middlewares:endpoint.middlewares});function makeProto(options3){function HttpApiEndpoint(){}Object.setPrototypeOf(HttpApiEndpoint,Proto16);return Object.assign(HttpApiEndpoint,options3)}var make37=(method)=>(identifier2,path4,options3)=>{const disableCodecs=options3?.disableCodecs??false;const transformStringTree=disableCodecs?identity:toCodecStringTree;return makeProto({identifier:identifier2,path:path4,method,params:ensureStruct(options3?.params,transformStringTree),query:ensureStruct(options3?.query,transformStringTree),headers:ensureStruct(options3?.headers,transformStringTree),payload:getPayload(options3?.payload,method,disableCodecs),success:getSuccessResponse(options3?.success,method,disableCodecs),error:getErrorResponse(options3?.error,disableCodecs),annotations:empty(),middlewares:new Set})};function ensureStruct(params,transform6){if(params===undefined)return;if(isSchema(params))return transform6(params);return transform6(Struct(params))}function getPayload(payload,method,disableCodecs){const result3=new Map;if(payload===undefined)return result3;const schemas=Array.isArray(payload)?payload:isSchema(payload)?[payload]:[Struct(payload).pipe(asFormUrlEncoded())];const transform6=disableCodecs?identity:transformPayload;for(const schema2 of schemas){const encoding=getPayloadEncoding(schema2.ast,method);const contentType=normalize(encoding.contentType);const existing=result3.get(contentType);if(existing){if(existing.encoding._tag!==encoding._tag){throw new Error(`Multiple payload encodings for content-type: ${encoding.contentType}`)}if(existing.encoding._tag==="Multipart"){throw new Error(`Multiple multipart payloads for content-type: ${encoding.contentType}`)}existing.schemas.push(transform6(schema2,method))}else{result3.set(contentType,{encoding,schemas:[transform6(schema2,method)]})}}return result3}var reservedStreamFailureEvent="effect/httpapi/stream/failure";function getSuccessResponse(success,method,disableCodecs){if(success===undefined)return new Set;const schemas=ensure(success);validateSuccessResponse(schemas,method);return new Set(disableCodecs?schemas:schemas.map((schema2)=>isStreamSchema(schema2)?schema2:transformResponse2(schema2)))}function getErrorResponse(error2,disableCodecs){if(error2===undefined)return new Set;const schemas=ensure(error2);for(const schema2 of schemas){if(isStreamSchema(schema2)){throw new Error("Streaming schemas are not supported in error responses")}}return new Set(disableCodecs?schemas:schemas.map(transformResponse2))}function validateSuccessResponse(schemas,method){const statuses=new Map;for(const schema2 of schemas){if(isStreamSchema(schema2)){validateStreamSuccess(schema2,method);const status2=getStatusStream(schema2);const entry=getStatusEntry(statuses,status2);if(entry.stream!==undefined){throw new Error(`Multiple streaming success responses for status: ${status2}`)}if(entry.noContent){throw new Error(`Cannot combine no-content and streaming success responses for status: ${status2}`)}if(entry.bufferedContentTypes.has(normalize(schema2.contentType))){throw new Error(`Cannot combine buffered and streaming success responses for status ${status2} and content-type: ${schema2.contentType}`)}statuses.set(status2,{...entry,stream:schema2})}else{const status2=getStatusSuccess(schema2.ast);const entry=getStatusEntry(statuses,status2);const noContent=isNoContent(schema2.ast);if(entry.stream!==undefined){if(noContent){throw new Error(`Cannot combine no-content and streaming success responses for status: ${status2}`)}const encoding=getResponseEncoding(schema2.ast);if(normalize(encoding.contentType)===normalize(entry.stream.contentType)){throw new Error(`Cannot combine buffered and streaming success responses for status ${status2} and content-type: ${encoding.contentType}`)}}if(!noContent){entry.bufferedContentTypes.add(normalize(getResponseEncoding(schema2.ast).contentType))}entry.noContent=entry.noContent||noContent}}}function getStatusEntry(statuses,status2){let entry=statuses.get(status2);if(entry===undefined){entry={bufferedContentTypes:new Set,noContent:false};statuses.set(status2,entry)}return entry}function validateStreamSuccess(schema2,method){if(method==="HEAD"){throw new Error("HEAD endpoints cannot declare streaming success responses")}if(isStreamSse(schema2)&&hasReservedSseEventName(schema2.events.ast)){throw new Error(`SSE event name is reserved: ${reservedStreamFailureEvent}`)}}function hasReservedSseEventName(ast){return hasReservedEventName(toEncoded(ast),new Set)}function hasReservedEventName(ast,seen){if(seen.has(ast))return false;seen.add(ast);if(isUnion(ast)){return ast.types.some((type)=>hasReservedEventName(type,seen))}if(isSuspend(ast)){return hasReservedEventName(ast.thunk(),seen)}if(!isObjects(ast))return false;const event=ast.propertySignatures.find((ps)=>ps.name==="event");return event!==undefined&&hasReservedEventLiteral(event.type,seen)}function hasReservedEventLiteral(ast,seen){if(seen.has(ast))return false;seen.add(ast);const encoded=toEncoded(ast);if(encoded!==ast){return hasReservedEventLiteral(encoded,seen)}if(isLiteral(ast)){return ast.literal===reservedStreamFailureEvent}if(isUnion(ast)){return ast.types.some((type)=>hasReservedEventLiteral(type,seen))}if(isSuspend(ast)){return hasReservedEventLiteral(ast.thunk(),seen)}return false}function transformResponse2(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":return toCodecJson(schema2);case"FormUrlEncoded":return toCodecStringTree(schema2);case"Text":case"Uint8Array":return schema2}}function transformPayload(schema2,method){const encoding=getPayloadEncoding(schema2.ast,method);switch(encoding._tag){case"Json":return toCodecJson(schema2);case"FormUrlEncoded":return toCodecStringTree(schema2);case"Text":case"Uint8Array":case"Multipart":return schema2}}var get7=make37("GET");var post3=make37("POST");var put3=make37("PUT");var patch3=make37("PATCH");var del3=make37("DELETE");var head3=make37("HEAD");var options3=make37("OPTIONS");var TypeId48="~effect/httpapi/HttpApi";var isHttpApi=(u)=>hasProperty(u,TypeId48);var Proto17={[TypeId48]:TypeId48,pipe(){return pipeArguments(this,arguments)},add(...toAdd){const groups={...this.groups};for(const group of toAdd){set(groups,group.identifier,group)}return makeProto2({...optionsFromApi(this),groups})},addHttpApi(api){const newGroups={...this.groups};for(const key in api.groups){const group=api.groups[key];set(newGroups,key,group.annotateMerge(merge(api.annotations,group.annotations)))}return makeProto2({...optionsFromApi(this),groups:newGroups})},prefix(prefix){return makeProto2({...optionsFromApi(this),groups:map2(this.groups,(group)=>group.prefix(prefix))})},middleware(tag2){return makeProto2({...optionsFromApi(this),groups:map2(this.groups,(group)=>group.middleware(tag2))})},annotate(key,value3){return makeProto2({...optionsFromApi(this),annotations:add(this.annotations,key,value3)})},annotateMerge(annotations){return makeProto2({...optionsFromApi(this),annotations:merge(this.annotations,annotations)})}};var optionsFromApi=(api)=>({identifier:api.identifier,groups:api.groups,annotations:api.annotations});var makeProto2=(options4)=>{function HttpApi(){}Object.setPrototypeOf(HttpApi,Proto17);return Object.assign(HttpApi,options4)};var make38=(identifier2)=>makeProto2({identifier:identifier2,groups:{},annotations:empty()});var reflect=(self,options4)=>{const groups=Object.values(self.groups);for(const group of groups){const groupAnnotations=merge(self.annotations,group.annotations);options4.onGroup({group,mergedAnnotations:groupAnnotations});const endpoints=Object.values(group.endpoints);for(const endpoint of endpoints){if(options4.predicate&&!options4.predicate({endpoint,group}))continue;options4.onEndpoint({group,endpoint,middleware:endpoint.middlewares,mergedAnnotations:merge(groupAnnotations,endpoint.annotations),successes:extractResponseContent(getSuccessSchemas(endpoint),getStatusSuccess),errors:extractResponseContent(getErrorSchemas(endpoint),getStatusError)})}}};var extractResponseContent=(schemas,getStatus)=>{const map15=new Map;schemas.forEach(add3);return map15;function add3(schema2){if(isStreamSchema(schema2))return;const ast=schema2.ast;const status2=getStatus(ast);const schemas2=map15.get(status2);if(schemas2===undefined){map15.set(status2,[schema2])}else{schemas2.push(schema2)}}};class AdditionalSchemas extends Service()("effect/httpapi/HttpApi/AdditionalSchemas"){}var decode=(schema2)=>()=>{const decode2=decodeEffect2(NonEmptyArray(schema2));return fromTransform((upstream,_scope)=>succeed6(flatMap3(upstream,(chunk)=>decode2(chunk))))};var decode2=()=>fromTransform((upstream,_scope)=>sync2(()=>{let buffer2=[];let retry5;const parser2=makeParser2((event)=>{if(event._tag==="Retry"){retry5=event}else{buffer2.push(event)}});const pump=flatMap3(upstream,(arr)=>{for(let i=0;i<arr.length;i++){parser2.feed(arr[i])}return void_3});return suspend2(function loop(){if(isArrayNonEmpty2(buffer2)){const out=buffer2;buffer2=[];return succeed6(out)}else if(retry5){return fail6(retry5)}return flatMap3(pump,loop)})}));var decodeSchema=(schema2)=>pipeTo(decode2(),decode(EventEncoded.pipe(decodeTo2(schema2)))());function makeParser2(onParse){let isFirstChunk;let buffer2;let startingPosition;let startingFieldLength;let eventId;let lastEventId;let eventName;let data;reset3();return{feed,reset:reset3};function reset3(){isFirstChunk=true;buffer2="";startingPosition=0;startingFieldLength=-1;eventId=undefined;eventName=undefined;data=""}function feed(chunk){buffer2=buffer2?buffer2+chunk:chunk;if(isFirstChunk&&hasBom(buffer2)){buffer2=buffer2.slice(BOM.length)}isFirstChunk=false;const length=buffer2.length;let position=0;let discardTrailingNewline=false;while(position<length){if(discardTrailingNewline){if(buffer2[position]===`
282
282
  `){++position}discardTrailingNewline=false}let lineLength=-1;let fieldLength=startingFieldLength;let character;for(let index=startingPosition;lineLength<0&&index<length;++index){character=buffer2[index];if(character===":"&&fieldLength<0){fieldLength=index-position}else if(character==="\r"){discardTrailingNewline=true;lineLength=index-position}else if(character===`
283
283
  `){lineLength=index-position}}if(lineLength<0){startingPosition=length-position;startingFieldLength=fieldLength;break}else{startingPosition=0;startingFieldLength=-1}parseEventStreamLine(buffer2,position,fieldLength,lineLength);position+=lineLength+1}if(position===length){buffer2=""}else if(position>0){buffer2=buffer2.slice(position)}}function parseEventStreamLine(lineBuffer,index,fieldLength,lineLength){if(lineLength===0){if(data.length>0){onParse({_tag:"Event",id:eventId,event:eventName??"message",data:data.slice(0,-1)});data="";eventId=undefined}eventName=undefined;return}const noValue=fieldLength<0;const field=lineBuffer.slice(index,index+(noValue?lineLength:fieldLength));let step=0;if(noValue){step=lineLength}else if(lineBuffer[index+fieldLength+1]===" "){step=fieldLength+2}else{step=fieldLength+1}const position=index+step;const valueLength=lineLength-step;const value3=lineBuffer.slice(position,position+valueLength).toString();if(field==="data"){data+=value3?`${value3}
284
284
  `:`
285
- `}else if(field==="event"){eventName=value3}else if(field==="id"&&!value3.includes("\x00")){eventId=value3;lastEventId=value3}else if(field==="retry"){const retry5=parseInt(value3,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index)=>buffer2.charCodeAt(index)===charCode)}var EventEncoded=Struct({id:optional(String4),event:String4,data:String4});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});var toJsonAnnotationsBlacklist=new Set([...fromASTBlacklist,"expected","contentMediaType","contentSchema"]);var fromASTs2=fromASTs;var toJsonSchemaMultiDocument2=toJsonSchemaMultiDocument;var toCodeAnnotationsBlacklist=new Set([...toJsonAnnotationsBlacklist,"typeConstructor","generation","brands"]);class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags)=>{const entries=Object.entries(tags);return(options4)=>{let context3=empty();for(const[key,tag2]of entries){if(options4[key]!==undefined){context3=add(context3,tag2,options4[key])}}return context3}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag2={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag2.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag2.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag2,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag2=transformFn(tag2)});spec.tags.push(tag2)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map15,encoding)=>{map15.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream2,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream2)){pathOps.push({_tag:"schema",ast:getAST(stream2.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream2.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream2.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map3(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value3=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value3}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map15=new Map;schemas.forEach(process2);return map15;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map15.get(status2);if(statusMap===undefined){map15.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map15.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map15.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set5=schemasByContentType.get(contentType);if(set5===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set5.add(schema2)}}}}}function addStreamContent(stream2){const status2=getStatusStream(stream2);const statusMap=map15.get(status2);if(statusMap===undefined){map15.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream2.contentType,stream2]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream2.contentType,stream2]])}else{statusMap.streamContent.set(stream2.contentType,stream2)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String4.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String4.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format4=getOption(security.annotations,Format).pipe(map((format5)=>({bearerFormat:format5})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format4}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make39,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request,middlewareKeys,index){if(index===-1){return httpClient.execute(request)}const middleware2=services.mapUnsafe.get(middlewareKeys[index]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request,middlewareKeys,index-1)}return middleware2({endpoint,group,request,next(request2){return executeMiddleware(group,endpoint,request2,middlewareKeys,index-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode3=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap3(catchCause2(decode3(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map10(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map10(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map10(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag2)=>`${tag2.key}/Client`);const endpointFn=fnUntraced2(function*(request){let httpRequest=make35(endpoint.method)(endpoint.path);if(request!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request.payload)}else{const body=yield*encodePayload(request.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request?.responseMode==="response-only"){return response}const value3=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request?.responseMode==="decoded-and-response"?[value3,response]:value3});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make39=(api,options4)=>flatMap3(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map6(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map6(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request)=>{const params=request?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request?.query===undefined?undefined:encodeQuery===undefined?request.query:encodeQuery(request.query);const query=queryInput===undefined?"":toString(fromInput2(queryInput));const url=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url:new URL(url,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value3=params[key];if(value3===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value3)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode3=decodeEffect2(codec);return(response)=>flatMap3(response.arrayBuffer,decode3)}function addResponseAlternative(map15,status2,contentType,decode3){const normalizedContentType=normalize(contentType);const alternatives=map15.get(status2);if(alternatives===undefined){map15.set(status2,[{contentType:normalizedContentType,decode:decode3}])}else{alternatives.push({contentType:normalizedContentType,decode:decode3})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map6(context2(),(context3)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context3))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream2,declaration,decoder){const events=transformPull2(stream2.pipe(decodeText,pipeThroughChannel(decoder)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap3(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String4,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput2(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make40,isHttpApiGroup:()=>isHttpApiGroup});var TypeId49="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId49);var Proto18={[TypeId49]:TypeId49,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto3({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto3({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value3){return makeProto3({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value3)})},annotateEndpointsMerge(annotations2){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value3){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value3))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto3=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto18);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make40=(identifier2,options4)=>makeProto3({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String4,email:optionalKey2(String4),emailVerified:optionalKey2(Boolean3)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value3)=>{const groups=isoDateTimePattern.exec(value3)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date5=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value3))&&date5.getUTCFullYear()===year&&date5.getUTCMonth()===month-1&&date5.getUTCDate()===day&&date5.getUTCHours()===hour&&date5.getUTCMinutes()===minute&&date5.getUTCSeconds()===second};var IsoDateTimeString=String4.pipe(refine((value3)=>isValidIsoDateTime(value3),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String4),email:optionalKey2(String4)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String4),remoteHost:optionalKey2(String4),remotePath:optionalKey2(String4),branch:optionalKey2(String4),commitSha:optionalKey2(String4),dirty:optionalKey2(Boolean3),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String4}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey=Union2([String4,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey),message:String4}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String4},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var NonBlankString=String4.check(isTrimmed(),isNonEmpty());var BaselineRevision=String4.check(isPattern2(/^[1-9][0-9]*$/u)).annotate({identifier:"BaselineRevision"});var BaselineSha256=String4.check(isPattern2(/^[0-9a-f]{64}$/u)).annotate({identifier:"BaselineSha256"});var BaselinePromotionArtifact=Struct({url:NonBlankString,sha256:BaselineSha256}).annotate({identifier:"BaselinePromotionArtifact"});var BaselinePromotionCandidate=Struct({releaseId:NonBlankString,version:BaselineVersion,tag:NonBlankString,publishedAt:IsoDateTimeString,commitSha:NonBlankString,provenance:NonBlankString,cliVersionRange:NonBlankString,manifest:BaselinePromotionArtifact,archive:BaselinePromotionArtifact}).annotate({identifier:"BaselinePromotionCandidate"});var BaselinePublishRequest=Struct({mode:Literal2("publish"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),reason:optionalKey2(Never2)});var BaselineRollbackRequest=Struct({mode:Literal2("rollback"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:BaselineRevision,reason:NonBlankString});var BaselinePromotionRequest=Union2([BaselinePublishRequest,BaselineRollbackRequest]).annotate({identifier:"BaselinePromotionRequest"});var BaselinePromotionResult=Struct({outcome:Literals(["committed","already-committed"]),revision:BaselineRevision,mode:Literals(["publish","rollback"]),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,previousRevision:optionalKey2(BaselineRevision),previousReleaseId:optionalKey2(NonBlankString),committedAt:IsoDateTimeString}).annotate({identifier:"BaselinePromotionResult"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String4}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String4,contentType:String4,url:String4,sha256:String4,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String4,source:BaselineSource,provenance:String4,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String4,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String4},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String4),actualDigest:optionalKey2(String4),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}class BaselinePublisherUnauthorized extends TaggedErrorClass()("@punks/contract/errors/BaselinePublisherUnauthorized",{message:defaultMessage2("Baseline publisher authentication is required.")},{httpApiStatus:401,title:"Baseline Publisher Unauthorized"}){}class BaselinePromotionConflict extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionConflict",{publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),actualRevision:optionalKey2(BaselineRevision),message:String4},{httpApiStatus:409,title:"Baseline Promotion Conflict"}){}class BaselinePromotionIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionIntegrityFailure",{publicationIdentity:NonBlankString,releaseId:optionalKey2(NonBlankString),expectedDigest:optionalKey2(BaselineSha256),actualDigest:optionalKey2(BaselineSha256),message:defaultMessage2("Baseline promotion evidence failed integrity verification.")},{httpApiStatus:422,title:"Baseline Promotion Integrity Failure"}){}class BaselinePromotionUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionUnavailable",{publicationIdentity:NonBlankString,outcome:Literals(["not-committed","indeterminate"]),message:defaultMessage2("Baseline promotion is unavailable.")},{httpApiStatus:503,title:"Baseline Promotion Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var promotionErrors=[HttpApiDecodeError,Forbidden2,BaselinePublisherUnauthorized,BaselinePromotionConflict,BaselinePromotionIntegrityFailure,BaselinePromotionUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2}),exports_HttpApiEndpoint.post("promote","/stable/promotions",{payload:BaselinePromotionRequest,success:BaselinePromotionResult,error:promotionErrors})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries=[];for(const{root,prefix,include=()=>true,logicalPath=(value3)=>value3}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash2=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash2.update(identity3);hash2.update("\x00");if(stat3.isSymbolicLink()){hash2.update("symlink\x00");hash2.update(readlinkSync(absolutePath))}else{hash2.update("file\x00");hash2.update(readFileSync(absolutePath))}hash2.update("\x00")}return hash2.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="5.0.0";var findFirst4=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst4(dataCandidates);var resolvedSkillsRoot=findFirst4(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst4([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst4([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="42f08bf080b0e6d29f6db18b0061079a4849e0a0f5451cc25a8e568e0611d3f8";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var antiSlopRules={"anti-slop/no-chained-type-assertions":"error","anti-slop/no-conditional-empty-object-spread":"error","anti-slop/no-known-value-widening":"error","anti-slop/no-module-mocking":"error","anti-slop/no-object-parameters":"error","anti-slop/no-reflect-apply":"error","anti-slop/no-reflect-get":"error","anti-slop/no-runtime-typeof":"error","anti-slop/no-shape-in-symbol-names":"error","anti-slop/no-unknown-parameters":"error","anti-slop/no-unknown-returns":"error","anti-slop/no-unknown-type-aliases":"error","anti-slop/no-unsafe-dictionary-type":"error","anti-slop/no-widen-then-assert":"error","anti-slop/require-safety-comment-for-type-assertion":"error"};var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Vendored Anti-Slop rules for rejecting low-evidence TypeScript and JavaScript patterns.",id:"typescript-anti-slop",ignorePatterns:["tools/oxlint/anti-slop/**"],jsPlugins:[{name:"anti-slop",specifier:"./tools/oxlint/anti-slop/index.mjs"}],oxlintPresets:[],placement:{placementNotes:"Apply to JavaScript and TypeScript workspaces.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript and TypeScript workspaces"]},plugins:[],requiredDevDependencies:["@oxlint/plugins"],rules:antiSlopRules,settings:{},sourceFiles:[{sourcePath:"lint/anti-slop/index.mjs",targetPath:"tools/oxlint/anti-slop/index.mjs"},{sourcePath:"lint/anti-slop/LICENSE",targetPath:"tools/oxlint/anti-slop/LICENSE"}]},{description:"Explicit Anti-Slop adoption policy for existing Harness workspaces.",id:"punks-anti-slop-transition",jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to existing Harness workspaces while they adopt Anti-Slop.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["Harness workspaces"]},plugins:[],requiredDevDependencies:[],rules:Object.fromEntries(Object.keys(antiSlopRules).map((rule)=>[rule,"off"])),settings:{},targetPackageNames:["@punks/api","@punks/auth","@punks/backoffice","@punks/cli","@punks/config","@punks/contract","@punks/db","@punks/env","@punks/scaffold","@punks/ui","@punks/web","@punks/wiki"]},{categories:{correctness:"error"},description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:["react"],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin","@typescript-eslint/utils","eslint"],requiredDevDependencyVersions:{"@typescript-eslint/utils":"8.22.0",eslint:"9.39.5"},rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Effect tsgo recommended type-aware Oxlint rules.",id:"effect-tsgo-recommended",jsPlugins:[],oxlintConfigExtensions:[{exportName:"recommended",specifier:"@effect/tsgo/oxlint-presets"}],oxlintPresets:[],placement:effectPlacement,plugins:[],prepareCommands:["effect-tsgo patch --no-typescript --oxlint"],requiredDevDependencies:["@effect/tsgo","oxlint-tsgolint"],requiredDevDependencyVersions:{"@effect/tsgo":"0.39.0",oxfmt:"0.66.0",oxlint:"1.80.0","oxlint-tsgolint":"7.0.2001",ultracite:"7.10.7"},rules:{},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Canonical lint policy for the shipped Harness CLI package.",id:"punks-cli-canonical",ignorePatterns:["src/data/lint/anti-slop/**","src/data/hooks/format-edited-file.mjs","src/data/hooks/require-tests-for-pr.mjs","src/data/hooks/scaffold-update-check.mjs","src/data/scripts/harness-projection/adapters/claude.mjs","src/data/scripts/harness-projection/adapters/codex.mjs","src/data/scripts/harness-projection/adapters/cursor.mjs","src/data/scripts/harness-projection/adapters/opencode.mjs","src/data/scripts/harness-projection/apply.mjs","src/data/scripts/harness-projection/core.mjs","src/data/scripts/sync-subagents.mjs","src/data/subagents/manifest.mjs"],jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/cli package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/cli"]},plugins:[],requiredDevDependencies:[],rules:{},settings:{},targetPackageNames:["@punks/cli"]},{description:"Canonical lint exceptions for the Harness backoffice package.",id:"punks-backoffice-canonical",jsPlugins:[],oxlintPresetRules:{vitest:{"vitest/prefer-import-in-mock":"off","vitest/prefer-importing-vitest-globals":"off"}},oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/backoffice package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/backoffice"]},plugins:[],requiredDevDependencies:[],rules:{"eslint/func-style":"off"},settings:{},targetPackageNames:["@punks/backoffice"]}];var stableJson=(value3)=>JSON.stringify(value3);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateConfigExtensions=(asset)=>{for(const extension of asset.oxlintConfigExtensions??[]){if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(extension.exportName)){throw new Error(`Invalid Oxlint config extension export name \`${extension.exportName}\`: ${asset.id}`)}if(extension.specifier.length===0){throw new Error(`Empty Oxlint config extension specifier: ${asset.id}`)}}};var validateRequiredVersions=(asset,seen)=>{for(const[packageName,version3]of Object.entries(asset.requiredDevDependencyVersions??{})){const previous=seen.get(packageName);if(previous!==undefined&&previous.version!==version3){throw new Error(`Conflicting required dev dependency version \`${packageName}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seen.set(packageName,{assetId:asset.id,version:version3})}}};var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;const seenRequiredVersions=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=[placementKeyOf(asset.placement),...asset.targetPackageNames===undefined?["all-packages"]:[...asset.targetPackageNames].toSorted()].join("::");for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value3=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value3){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value3})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value3=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value3){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value3})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}validateConfigExtensions(asset);validateRequiredVersions(asset,seenRequiredVersions)}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"architect-pipeline",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/architect-pipeline",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"effect",id:"effect-service-design",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect-service-design",tier:"framework"},{framework:"sqlalchemy",id:"sqlalchemy-schema-design",language:"python",requiresTools:[],sourceDirectory:"skills/frameworks/sqlalchemy/sqlalchemy-schema-design",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"animate-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/animate-expo",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"animate",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/animate",tier:"agnostic"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"improve-mobile-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/improve-mobile-frontend",tier:"agnostic"},{framework:null,id:"review-animations",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/review-animations",tier:"agnostic"},{framework:null,id:"business-finder",language:null,requiresTools:[],sourceDirectory:"skills/phases/business-finder",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"functional-finder",language:null,requiresTools:[],sourceDirectory:"skills/phases/functional-finder",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"handback",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handback",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"verify-behavior",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/verify-behavior",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"prototype-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/prototype-phase",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-backend-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-backend-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"domain-modeling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/domain-modeling",tier:"agnostic"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"make-tsuite",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/make-tsuite",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"wait-what",language:null,requiresTools:[],sourceDirectory:"skills/misc/wait-what",tier:"agnostic"},{framework:null,id:"rule-authoring",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/rule-authoring",tier:"agnostic"},{framework:null,id:"show-me",language:null,requiresTools:[],sourceDirectory:"skills/misc/show-me",tier:"agnostic"},{framework:null,id:"writing-for-agents",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-for-agents",tier:"agnostic"},{framework:null,id:"write-graph-based-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/write-graph-based-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var skillIdPattern=/^[a-z0-9][a-z0-9._-]*$/u;var stripSkillIdCompatibilityProjectionRows=(skills,entries)=>{const compatibilitySources=new Map(entries.flatMap(({alias,compatibilitySourceDirectory})=>compatibilitySourceDirectory===undefined?[]:[[alias,compatibilitySourceDirectory]]));return skills.filter(({id,sourceDirectory})=>compatibilitySources.get(id)!==sourceDirectory)};var validateSkillIdAliases=(entries,skills)=>{const canonicalIds=new Set(skills.map(({id})=>id));const entriesByAlias=new Map;for(const entry of entries){if(!skillIdPattern.test(entry.alias)||!skillIdPattern.test(entry.canonicalId)){throw new Error(`Invalid skill ID alias: ${entry.alias} -> ${entry.canonicalId}`)}if(entry.kind!=="alias"&&entry.kind!=="rename"){throw new Error(`Invalid skill ID alias kind: ${entry.alias}`)}if(entry.compatibilitySourceDirectory!==undefined&&entry.compatibilitySourceDirectory===""){throw new Error(`Invalid skill ID alias compatibility source: ${entry.alias}`)}if(entriesByAlias.has(entry.alias)){throw new Error(`Duplicate skill ID alias: ${entry.alias}`)}if(canonicalIds.has(entry.alias)){throw new Error(`Skill ID alias collides with canonical skill: ${entry.alias}`)}if(entry.alias===entry.canonicalId){throw new Error(`Skill ID alias cannot map to itself: ${entry.alias}`)}entriesByAlias.set(entry.alias,entry)}const resolveTerminal=(entry)=>{const visited=new Set([entry.alias]);let target=entry.canonicalId;while(entriesByAlias.has(target)){if(visited.has(target)){throw new Error(`Skill ID alias cycle includes: ${target}`)}visited.add(target);target=entriesByAlias.get(target)?.canonicalId??target}if(!canonicalIds.has(target)){throw new Error(`Skill ID alias target is missing: ${entry.alias} -> ${target}`)}return target};return entries.map((entry)=>({...entry,canonicalId:resolveTerminal(entry)})).toSorted((left,right)=>left.alias.localeCompare(right.alias))};var skillIdAliasCatalog=validateSkillIdAliases([{alias:"python-project-structure",canonicalId:"python-backend-structure",compatibilitySourceDirectory:"skills/languages/python/python-project-structure",kind:"rename"},{alias:"writing-great-skills",canonicalId:"writing-for-agents",compatibilitySourceDirectory:"skills/agnostic/docs/writing-great-skills",kind:"rename"}],skillCatalog);var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]}];var path6=runSync2(Path.pipe(provide4(layer9)));var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var bundledBaseline={capabilities:{scopedAuthoring:{revision:"1",skills:skillCatalog.map(({id})=>({activationRevision:"1",authoringRevision:"1",id})),version:1},sharedPrompt:{path:"data/shared-agents.md",sha256:fileSha256(path6.join(dataRoot,"shared-agents.md")),version:1}},dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skillIdAliases:skillIdAliasCatalog,skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts")&&relativePath!=="CLAUDE.md",prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
285
+ `}else if(field==="event"){eventName=value3}else if(field==="id"&&!value3.includes("\x00")){eventId=value3;lastEventId=value3}else if(field==="retry"){const retry5=parseInt(value3,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index)=>buffer2.charCodeAt(index)===charCode)}var EventEncoded=Struct({id:optional(String4),event:String4,data:String4});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});var toJsonAnnotationsBlacklist=new Set([...fromASTBlacklist,"expected","contentMediaType","contentSchema"]);var fromASTs2=fromASTs;var toJsonSchemaMultiDocument2=toJsonSchemaMultiDocument;var toCodeAnnotationsBlacklist=new Set([...toJsonAnnotationsBlacklist,"typeConstructor","generation","brands"]);class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags)=>{const entries=Object.entries(tags);return(options4)=>{let context3=empty();for(const[key,tag2]of entries){if(options4[key]!==undefined){context3=add(context3,tag2,options4[key])}}return context3}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag2={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag2.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag2.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag2,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag2=transformFn(tag2)});spec.tags.push(tag2)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map15,encoding)=>{map15.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream2,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream2)){pathOps.push({_tag:"schema",ast:getAST(stream2.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream2.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream2.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map3(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value3=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value3}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map15=new Map;schemas.forEach(process2);return map15;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map15.get(status2);if(statusMap===undefined){map15.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map15.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map15.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set5=schemasByContentType.get(contentType);if(set5===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set5.add(schema2)}}}}}function addStreamContent(stream2){const status2=getStatusStream(stream2);const statusMap=map15.get(status2);if(statusMap===undefined){map15.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream2.contentType,stream2]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream2.contentType,stream2]])}else{statusMap.streamContent.set(stream2.contentType,stream2)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String4.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String4.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format4=getOption(security.annotations,Format).pipe(map((format5)=>({bearerFormat:format5})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format4}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make39,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request,middlewareKeys,index){if(index===-1){return httpClient.execute(request)}const middleware2=services.mapUnsafe.get(middlewareKeys[index]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request,middlewareKeys,index-1)}return middleware2({endpoint,group,request,next(request2){return executeMiddleware(group,endpoint,request2,middlewareKeys,index-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode3=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap3(catchCause2(decode3(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map10(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map10(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map10(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag2)=>`${tag2.key}/Client`);const endpointFn=fnUntraced2(function*(request){let httpRequest=make35(endpoint.method)(endpoint.path);if(request!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request.payload)}else{const body=yield*encodePayload(request.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request?.responseMode==="response-only"){return response}const value3=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request?.responseMode==="decoded-and-response"?[value3,response]:value3});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make39=(api,options4)=>flatMap3(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map6(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map6(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request)=>{const params=request?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request?.query===undefined?undefined:encodeQuery===undefined?request.query:encodeQuery(request.query);const query=queryInput===undefined?"":toString(fromInput2(queryInput));const url=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url:new URL(url,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value3=params[key];if(value3===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value3)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode3=decodeEffect2(codec);return(response)=>flatMap3(response.arrayBuffer,decode3)}function addResponseAlternative(map15,status2,contentType,decode3){const normalizedContentType=normalize(contentType);const alternatives=map15.get(status2);if(alternatives===undefined){map15.set(status2,[{contentType:normalizedContentType,decode:decode3}])}else{alternatives.push({contentType:normalizedContentType,decode:decode3})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map6(context2(),(context3)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context3))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream2,declaration,decoder){const events=transformPull2(stream2.pipe(decodeText,pipeThroughChannel(decoder)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap3(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String4,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput2(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make40,isHttpApiGroup:()=>isHttpApiGroup});var TypeId49="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId49);var Proto18={[TypeId49]:TypeId49,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto3({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto3({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value3){return makeProto3({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value3)})},annotateEndpointsMerge(annotations2){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value3){return makeProto3({...optionsFromGroup(this),endpoints:map2(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value3))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto3=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto18);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make40=(identifier2,options4)=>makeProto3({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String4,email:optionalKey2(String4),emailVerified:optionalKey2(Boolean3)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value3)=>{const groups=isoDateTimePattern.exec(value3)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date5=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value3))&&date5.getUTCFullYear()===year&&date5.getUTCMonth()===month-1&&date5.getUTCDate()===day&&date5.getUTCHours()===hour&&date5.getUTCMinutes()===minute&&date5.getUTCSeconds()===second};var IsoDateTimeString=String4.pipe(refine((value3)=>isValidIsoDateTime(value3),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String4),email:optionalKey2(String4)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String4),remoteHost:optionalKey2(String4),remotePath:optionalKey2(String4),branch:optionalKey2(String4),commitSha:optionalKey2(String4),dirty:optionalKey2(Boolean3),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String4}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey=Union2([String4,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey),message:String4}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String4},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var NonBlankString=String4.check(isTrimmed(),isNonEmpty());var BaselineRevision=String4.check(isPattern2(/^[1-9][0-9]*$/u)).annotate({identifier:"BaselineRevision"});var BaselineSha256=String4.check(isPattern2(/^[0-9a-f]{64}$/u)).annotate({identifier:"BaselineSha256"});var BaselinePromotionArtifact=Struct({url:NonBlankString,sha256:BaselineSha256}).annotate({identifier:"BaselinePromotionArtifact"});var BaselinePromotionCandidate=Struct({releaseId:NonBlankString,version:BaselineVersion,tag:NonBlankString,publishedAt:IsoDateTimeString,commitSha:NonBlankString,provenance:NonBlankString,cliVersionRange:NonBlankString,manifest:BaselinePromotionArtifact,archive:BaselinePromotionArtifact}).annotate({identifier:"BaselinePromotionCandidate"});var BaselinePublishRequest=Struct({mode:Literal2("publish"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),reason:optionalKey2(Never2)});var BaselineRollbackRequest=Struct({mode:Literal2("rollback"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:BaselineRevision,reason:NonBlankString});var BaselinePromotionRequest=Union2([BaselinePublishRequest,BaselineRollbackRequest]).annotate({identifier:"BaselinePromotionRequest"});var BaselinePromotionResult=Struct({outcome:Literals(["committed","already-committed"]),revision:BaselineRevision,mode:Literals(["publish","rollback"]),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,previousRevision:optionalKey2(BaselineRevision),previousReleaseId:optionalKey2(NonBlankString),committedAt:IsoDateTimeString}).annotate({identifier:"BaselinePromotionResult"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String4}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String4,contentType:String4,url:String4,sha256:String4,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String4,source:BaselineSource,provenance:String4,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String4,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String4},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String4),actualDigest:optionalKey2(String4),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}class BaselinePublisherUnauthorized extends TaggedErrorClass()("@punks/contract/errors/BaselinePublisherUnauthorized",{message:defaultMessage2("Baseline publisher authentication is required.")},{httpApiStatus:401,title:"Baseline Publisher Unauthorized"}){}class BaselinePromotionConflict extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionConflict",{publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),actualRevision:optionalKey2(BaselineRevision),message:String4},{httpApiStatus:409,title:"Baseline Promotion Conflict"}){}class BaselinePromotionIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionIntegrityFailure",{publicationIdentity:NonBlankString,releaseId:optionalKey2(NonBlankString),expectedDigest:optionalKey2(BaselineSha256),actualDigest:optionalKey2(BaselineSha256),message:defaultMessage2("Baseline promotion evidence failed integrity verification.")},{httpApiStatus:422,title:"Baseline Promotion Integrity Failure"}){}class BaselinePromotionUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionUnavailable",{publicationIdentity:NonBlankString,outcome:Literals(["not-committed","indeterminate"]),message:defaultMessage2("Baseline promotion is unavailable.")},{httpApiStatus:503,title:"Baseline Promotion Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var promotionErrors=[HttpApiDecodeError,Forbidden2,BaselinePublisherUnauthorized,BaselinePromotionConflict,BaselinePromotionIntegrityFailure,BaselinePromotionUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2}),exports_HttpApiEndpoint.post("promote","/stable/promotions",{payload:BaselinePromotionRequest,success:BaselinePromotionResult,error:promotionErrors})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries=[];for(const{root,prefix,include=()=>true,logicalPath=(value3)=>value3}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash2=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash2.update(identity3);hash2.update("\x00");if(stat3.isSymbolicLink()){hash2.update("symlink\x00");hash2.update(readlinkSync(absolutePath))}else{hash2.update("file\x00");hash2.update(readFileSync(absolutePath))}hash2.update("\x00")}return hash2.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="5.1.0";var findFirst4=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst4(dataCandidates);var resolvedSkillsRoot=findFirst4(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst4([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst4([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="25161fef900765c0c3a205e5c08238aff5b08b75fe516c179a27f3d9b4b5bd8d";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var antiSlopRules={"anti-slop/no-chained-type-assertions":"error","anti-slop/no-conditional-empty-object-spread":"error","anti-slop/no-known-value-widening":"error","anti-slop/no-module-mocking":"error","anti-slop/no-object-parameters":"error","anti-slop/no-reflect-apply":"error","anti-slop/no-reflect-get":"error","anti-slop/no-runtime-typeof":"error","anti-slop/no-shape-in-symbol-names":"error","anti-slop/no-unknown-parameters":"error","anti-slop/no-unknown-returns":"error","anti-slop/no-unknown-type-aliases":"error","anti-slop/no-unsafe-dictionary-type":"error","anti-slop/no-widen-then-assert":"error","anti-slop/require-safety-comment-for-type-assertion":"error"};var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Vendored Anti-Slop rules for rejecting low-evidence TypeScript and JavaScript patterns.",id:"typescript-anti-slop",ignorePatterns:["tools/oxlint/anti-slop/**"],jsPlugins:[{name:"anti-slop",specifier:"./tools/oxlint/anti-slop/index.mjs"}],oxlintPresets:[],placement:{placementNotes:"Apply to JavaScript and TypeScript workspaces.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript and TypeScript workspaces"]},plugins:[],requiredDevDependencies:["@oxlint/plugins"],rules:antiSlopRules,settings:{},sourceFiles:[{sourcePath:"lint/anti-slop/index.mjs",targetPath:"tools/oxlint/anti-slop/index.mjs"},{sourcePath:"lint/anti-slop/LICENSE",targetPath:"tools/oxlint/anti-slop/LICENSE"}]},{description:"Explicit Anti-Slop adoption policy for existing Harness workspaces.",id:"punks-anti-slop-transition",jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to existing Harness workspaces while they adopt Anti-Slop.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["Harness workspaces"]},plugins:[],requiredDevDependencies:[],rules:Object.fromEntries(Object.keys(antiSlopRules).map((rule)=>[rule,"off"])),settings:{},targetPackageNames:["@punks/api","@punks/auth","@punks/backoffice","@punks/cli","@punks/config","@punks/contract","@punks/db","@punks/env","@punks/scaffold","@punks/ui","@punks/web","@punks/wiki"]},{categories:{correctness:"error"},description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:["react"],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin","@typescript-eslint/utils","eslint"],requiredDevDependencyVersions:{"@typescript-eslint/utils":"8.22.0",eslint:"9.39.5"},rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Effect tsgo recommended type-aware Oxlint rules.",id:"effect-tsgo-recommended",jsPlugins:[],oxlintConfigExtensions:[{exportName:"recommended",specifier:"@effect/tsgo/oxlint-presets"}],oxlintPresets:[],placement:effectPlacement,plugins:[],prepareCommands:["effect-tsgo patch --no-typescript --oxlint"],requiredDevDependencies:["@effect/tsgo","oxlint-tsgolint"],requiredDevDependencyVersions:{"@effect/tsgo":"0.39.0",oxfmt:"0.66.0",oxlint:"1.80.0","oxlint-tsgolint":"7.0.2001",ultracite:"7.10.7"},rules:{},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Canonical lint policy for the shipped Harness CLI package.",id:"punks-cli-canonical",ignorePatterns:["src/data/lint/anti-slop/**","src/data/hooks/format-edited-file.mjs","src/data/hooks/require-tests-for-pr.mjs","src/data/hooks/scaffold-update-check.mjs","src/data/scripts/harness-projection/adapters/claude.mjs","src/data/scripts/harness-projection/adapters/codex.mjs","src/data/scripts/harness-projection/adapters/cursor.mjs","src/data/scripts/harness-projection/adapters/opencode.mjs","src/data/scripts/harness-projection/apply.mjs","src/data/scripts/harness-projection/core.mjs","src/data/scripts/sync-subagents.mjs","src/data/subagents/manifest.mjs"],jsPlugins:[],oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/cli package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/cli"]},plugins:[],requiredDevDependencies:[],rules:{},settings:{},targetPackageNames:["@punks/cli"]},{description:"Canonical lint exceptions for the Harness backoffice package.",id:"punks-backoffice-canonical",jsPlugins:[],oxlintPresetRules:{vitest:{"vitest/prefer-import-in-mock":"off","vitest/prefer-importing-vitest-globals":"off"}},oxlintPresets:[],placement:{placementNotes:"Apply only to the exact @punks/backoffice package.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["@punks/backoffice"]},plugins:[],requiredDevDependencies:[],rules:{"eslint/func-style":"off"},settings:{},targetPackageNames:["@punks/backoffice"]}];var stableJson=(value3)=>JSON.stringify(value3);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateConfigExtensions=(asset)=>{for(const extension of asset.oxlintConfigExtensions??[]){if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(extension.exportName)){throw new Error(`Invalid Oxlint config extension export name \`${extension.exportName}\`: ${asset.id}`)}if(extension.specifier.length===0){throw new Error(`Empty Oxlint config extension specifier: ${asset.id}`)}}};var validateRequiredVersions=(asset,seen)=>{for(const[packageName,version3]of Object.entries(asset.requiredDevDependencyVersions??{})){const previous=seen.get(packageName);if(previous!==undefined&&previous.version!==version3){throw new Error(`Conflicting required dev dependency version \`${packageName}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seen.set(packageName,{assetId:asset.id,version:version3})}}};var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;const seenRequiredVersions=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=[placementKeyOf(asset.placement),...asset.targetPackageNames===undefined?["all-packages"]:[...asset.targetPackageNames].toSorted()].join("::");for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value3=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value3){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value3})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value3=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value3){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value3})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}validateConfigExtensions(asset);validateRequiredVersions(asset,seenRequiredVersions)}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"architect-pipeline",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/architect-pipeline",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"create-verification-skill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-verification-skill",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"effect",id:"effect-service-design",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect-service-design",tier:"framework"},{framework:"sqlalchemy",id:"sqlalchemy-schema-design",language:"python",requiresTools:[],sourceDirectory:"skills/frameworks/sqlalchemy/sqlalchemy-schema-design",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"animate-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/animate-expo",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"animate",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/animate",tier:"agnostic"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"improve-mobile-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/improve-mobile-frontend",tier:"agnostic"},{framework:null,id:"review-animations",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/review-animations",tier:"agnostic"},{framework:null,id:"business-finder",language:null,requiresTools:[],sourceDirectory:"skills/phases/business-finder",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"functional-finder",language:null,requiresTools:[],sourceDirectory:"skills/phases/functional-finder",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"handback",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handback",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"update-verification-skill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/update-verification-skill",tier:"agnostic"},{framework:null,id:"verify-behavior",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/verify-behavior",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"prototype-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/prototype-phase",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-backend-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-backend-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"domain-modeling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/domain-modeling",tier:"agnostic"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"make-tsuite",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/make-tsuite",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"wait-what",language:null,requiresTools:[],sourceDirectory:"skills/misc/wait-what",tier:"agnostic"},{framework:null,id:"rule-authoring",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/rule-authoring",tier:"agnostic"},{framework:null,id:"show-me",language:null,requiresTools:[],sourceDirectory:"skills/misc/show-me",tier:"agnostic"},{framework:null,id:"writing-for-agents",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-for-agents",tier:"agnostic"},{framework:null,id:"write-graph-based-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/write-graph-based-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var skillIdPattern=/^[a-z0-9][a-z0-9._-]*$/u;var stripSkillIdCompatibilityProjectionRows=(skills,entries)=>{const compatibilitySources=new Map(entries.flatMap(({alias,compatibilitySourceDirectory})=>compatibilitySourceDirectory===undefined?[]:[[alias,compatibilitySourceDirectory]]));return skills.filter(({id,sourceDirectory})=>compatibilitySources.get(id)!==sourceDirectory)};var validateSkillIdAliases=(entries,skills)=>{const canonicalIds=new Set(skills.map(({id})=>id));const entriesByAlias=new Map;for(const entry of entries){if(!skillIdPattern.test(entry.alias)||!skillIdPattern.test(entry.canonicalId)){throw new Error(`Invalid skill ID alias: ${entry.alias} -> ${entry.canonicalId}`)}if(entry.kind!=="alias"&&entry.kind!=="rename"){throw new Error(`Invalid skill ID alias kind: ${entry.alias}`)}if(entry.compatibilitySourceDirectory!==undefined&&entry.compatibilitySourceDirectory===""){throw new Error(`Invalid skill ID alias compatibility source: ${entry.alias}`)}if(entriesByAlias.has(entry.alias)){throw new Error(`Duplicate skill ID alias: ${entry.alias}`)}if(canonicalIds.has(entry.alias)){throw new Error(`Skill ID alias collides with canonical skill: ${entry.alias}`)}if(entry.alias===entry.canonicalId){throw new Error(`Skill ID alias cannot map to itself: ${entry.alias}`)}entriesByAlias.set(entry.alias,entry)}const resolveTerminal=(entry)=>{const visited=new Set([entry.alias]);let target=entry.canonicalId;while(entriesByAlias.has(target)){if(visited.has(target)){throw new Error(`Skill ID alias cycle includes: ${target}`)}visited.add(target);target=entriesByAlias.get(target)?.canonicalId??target}if(!canonicalIds.has(target)){throw new Error(`Skill ID alias target is missing: ${entry.alias} -> ${target}`)}return target};return entries.map((entry)=>({...entry,canonicalId:resolveTerminal(entry)})).toSorted((left,right)=>left.alias.localeCompare(right.alias))};var skillIdAliasCatalog=validateSkillIdAliases([{alias:"python-project-structure",canonicalId:"python-backend-structure",compatibilitySourceDirectory:"skills/languages/python/python-project-structure",kind:"rename"},{alias:"writing-great-skills",canonicalId:"writing-for-agents",compatibilitySourceDirectory:"skills/agnostic/docs/writing-great-skills",kind:"rename"}],skillCatalog);var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]}];var path6=runSync2(Path.pipe(provide4(layer9)));var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var bundledBaseline={capabilities:{scopedAuthoring:{revision:"1",skills:skillCatalog.map(({id})=>({activationRevision:"1",authoringRevision:"1",id})),version:1},sharedPrompt:{path:"data/shared-agents.md",sha256:fileSha256(path6.join(dataRoot,"shared-agents.md")),version:1}},dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skillIdAliases:skillIdAliasCatalog,skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts")&&relativePath!=="CLAUDE.md",prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
286
286
  `)};var formatList=(values)=>values.length===0?[" ∅"]:values.map((value3)=>` • ${value3}`);var wrapInlineValues=({values,firstPrefix,continuationPrefix,maxLineLength=88})=>{if(values.length===0){return[`${firstPrefix}∅`]}const lines2=[];let currentLine=firstPrefix;for(const value3 of values){const candidate=currentLine===firstPrefix?`${currentLine}${value3}`:`${currentLine}, ${value3}`;if(candidate.length<=maxLineLength||currentLine===firstPrefix){currentLine=candidate;continue}lines2.push(currentLine);currentLine=`${continuationPrefix}${value3}`}lines2.push(currentLine);return lines2};var formatPackRows=({label,values,isLast})=>wrapInlineValues({continuationPrefix:`${isLast?" ":" │ "}${" ".repeat(`${label}: `.length)}`,firstPrefix:` ${isLast?"└":"├"} ${label}: `,values});var formatPackList=(values,baseline=bundledBaseline)=>values.length===0?[" ∅"]:values.flatMap((packId)=>{const skills=skillsForPack(packId,baseline);const lintAssets=lintAssetsForPack(packId,baseline);const hooks=hooksForPack(packId,baseline);const detailRows=[...skills.length===0?[]:[{label:"skills",values:skills}],...lintAssets.length===0?[]:[{label:"lint",values:lintAssets}],...hooks.length===0?[]:[{label:"hooks",values:hooks}],...(()=>{const promptLabels=promptDetailsForPack(packId,baseline);return promptLabels.length===0?[]:[{label:"prompts",values:promptLabels}]})()];return[` • ${packId}`,...detailRows.flatMap((row,index)=>formatPackRows({isLast:index===detailRows.length-1,label:row.label,values:row.values}))]});var formatCompactPackList=(values)=>values.length===0?[" ∅"]:wrapInlineValues({continuationPrefix:" ",firstPrefix:" • ",values});var section=(title,lines2)=>[title,...lines2];var maybeSection=(title,lines2)=>lines2.length===1&&lines2[0]===" ∅"?[]:section(title,lines2);var formatDetectionSummary=(detection)=>["Scaffold detection summary",`cwd: ${detection.cwd}`,...section("detected languages:",formatList(detection.detectedLanguages)),...section("detected technologies:",formatList(detection.detectedTechnologies)),...section("manifest files:",formatList(detection.manifests.map((manifest)=>path7.relative(detection.cwd,manifest.path)||"package.json"))),...section("monorepo signals:",formatList(detection.monorepoSignals.map((signal)=>`${signal.type} (${path7.relative(detection.cwd,signal.path)||"."})`)))].join(`
287
287
  `);var formatConfirmationSummary=(result3,baseline=bundledBaseline)=>["Confirmed scaffold selection",`baseline: ${result3.baseline.source}/${result3.baseline.channel} ${result3.baseline.version}`,`cwd: ${result3.cwd}`,`repo shape mode: ${result3.repoShapeMode}`,`effective repo shape: ${result3.monorepo?"monorepo":"single"}`,...section("detected languages:",formatList(result3.detectedLanguages)),...section("detected technologies:",formatList(result3.detectedTechnologies)),...section("default packs:",formatPackList(result3.defaultPacks,baseline)),...section("language packs:",formatPackList(result3.languagePacks,baseline)),...section("detected packs:",formatPackList(result3.detectedPacks,baseline)),...section("surface packs:",formatPackList(result3.surfacePacks,baseline)),...maybeSection("added packs:",formatPackList(result3.addedPacks,baseline)),...maybeSection("removed packs:",formatPackList(result3.removedPacks,baseline)),...section("final packs:",formatCompactPackList(result3.finalPacks)),`output directory: ${result3.outputDirectory}`,...section("shared core files:",formatList(result3.promptOutputs)),...section("lint spec files:",formatList(result3.lintSpecFiles)),...section("source guide files:",formatList(result3.sourceGuideFiles)),...section("skill files:",formatList(result3.skillFiles)),...section("prompt spec files:",formatList(result3.promptSpecFiles)),...section("subagent scaffold files:",formatList(result3.subagentFiles)),...section("script files:",formatList(result3.scriptFiles)),...section("hook files:",formatList(result3.hookFiles)),...section("harness files:",formatList(result3.harnessFiles)),...maybeSection("hidden output directories:",formatList(result3.hiddenOutputDirectories)),...section("agent handoff file:",formatList([result3.agentHandoffFile])),...section("required tools source:",formatList([".devpunks/settings.json"])),...maybeSection("tool bootstrap:",formatList(result3.toolBootstrapStatuses.map((entry)=>`${entry.toolId}: ${formatToolBootstrapStatus(entry)}`))),...section("scaffold manifest:",formatList([result3.scaffoldManifestFile]))].join(`
288
288
  `);var formatAgentHandoffSummary=(result3)=>["Give this to the next agent","","You are continuing a `hi scaffold` run.","","Read first:",` • \`${result3.scaffoldManifestFile}\``,` • \`${result3.agentHandoffFile}\``," • `.devpunks/settings.json`","",...result3.toolBootstrapStatuses.length===0?[]:["Tool bootstrap status:",...result3.toolBootstrapStatuses.map((entry)=>` • \`${entry.toolId}\`: ${formatToolBootstrapStatus(entry)}`),""],...result3.toolBootstrapStatuses.some((entry)=>entry.status==="failed")?["Tool bootstrap recovery:"," • Read `.devpunks/settings.json` and manually verify every listed required tool before deeper repo work."," • Repair failed installs outside the scaffold command. For `agent-browser` Chromium failures, rerun `agent-browser install` after fixing the local browser dependency.",""]:[],"What was scaffolded:"," • final scoped/root prompt files were not written yet",...formatList([...result3.promptOutputs,...result3.lintSpecFiles,...result3.sourceGuideFiles,...result3.skillFiles,...result3.promptSpecFiles,...result3.subagentFiles,...result3.scriptFiles,...result3.hookFiles,...result3.harnessFiles]),"","What you must do:"," 1. Treat the prompt spec markdown files as instructions, not final prompt bodies."," 1a. Activate `writing-for-agents`, then `rule-authoring`, before reconciling prompt specs, scoped guidance, or `.agents/rules/`."," 1c. Preserve the generated `$handback` autonomy pointer once in shared/root guidance and immediately after every docs/workspace scope boundary."," 1b. Preserve project-owned `.agents/rules/`; each scoped `AGENTS.md` carries one exhaustive Rule Registry pointer.",result3.monorepo?" 2. Repo is in monorepo mode. Generate final prompt files for root, docs, and each relevant app/package scope.":" 2. Repo is in single-repo mode. Stitch scoped guidance into one root prompt, plus docs guidance when present."," 3. Read `.devpunks/settings.json` and verify listed required tools such as `skills`, `portless`, `opensrc`, and `agent-browser` are actually available. If any are missing, install/fix that first."," 4. Use the root prompt spec criteria to author root `AGENTS.md` from real repo evidence: surface map, workflow routing, cross-surface contract rules, validation routing, then short source/URL/docs rules. Do not add a root `Primary skills here` line."," 4a. Use each generated docs/workspace prompt spec as the sole detailed authority; follow its repository-invariant, exact skill-pointer, Source Guide, mirror, and validation checks without restating them here."," 4b. Complete scoped prompt authoring only when every generated docs/workspace target is written, existing nested prompts remain preserved, no new deeper prompt exists, and every relative reference resolves."," 5. Treat every authored root/docs/workspace `AGENTS.md` file as the neutral scoped prompt source and create a sibling `CLAUDE.md` symlink mirror beside each one."," 6. Keep `.agents/AGENTS.md` as the shared global prompt source behind the scoped prompt tree; `.claude/CLAUDE.md` should mirror that neutral file."," 7. Before relying on subagents, verify the active harness global/project settings enable subagent execution, then verify `.agents/subagents/manifest.mjs` and selected specialist path/guidance/skill coverage. Repair settings/setup or execute locally if the guard fails."," 8. Keep `.agents/hooks/` as the neutral hook source, `.agents/skills/` as the main skill directory, and `.agents/scripts/sync-subagents.mjs` as the harness sync entrypoint. Only `.claude/skills` should mirror `.agents/skills`."," 9. Reconcile `.agents/subagents/manifest.mjs` with both `.agents/subagents/manifest.prompt.md` and `.devpunks/specs/subagents/manifest-spec.json`."," 10. Update owned paths / guidance file references in the subagent manifest to match the real repo shape."," 11. Use `portless` as the local-dev URL baseline. Prefer stable subdomains over raw `localhost:<port>` values in env examples, endpoint defaults, callback URLs, allowed origins, CORS, and app-to-app proxies."," 12. If adopting Oxlint or Oxfmt, replace existing lint/format setup deliberately: package scripts, task pipelines, CI, editor/docs references, and hooks should agree on the new tools."," 13. Before authoring final prompts or implementation plans, identify the core detected libraries whose source behavior matters."," 14. If an `opensrc/<package>.md` guide exists for a package, read that card first, then run its `opensrc path --cwd . <package>` command or fallback repository lookup."," 15. Inspect the returned checkout paths. Clone the major framework/runtime libraries you will reason about; do not clone every dependency mechanically."].join(`
@@ -303,9 +303,9 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
303
303
  `};var initializeProjectSettings=fn2("ProjectSettings.initialize")(function*initializeProjectSettings2(fileSystem,rootDirectory,initialization,session){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const settingsDirectoryExisted=yield*fileSystem.directoryExists(settingsDirectory,session);const expectedContent=projectSettingsInitializationContent(initialization);const created=yield*fileSystem.createTextFile(settingsPath,expectedContent,session);if(!created){return yield*new ProjectSettingsAlreadyExists({message:`Project settings already exist at ${settingsPath}.`,path:settingsPath})}const read2=yield*readProjectSettings(fileSystem,rootDirectory,session).pipe(result2);if(isSuccess2(read2)){return read2.success}yield*gen2(function*rollbackProjectSettingsInitialization(){yield*fileSystem.removeTextFileIfContent(settingsPath,expectedContent,session);if(!settingsDirectoryExisted){yield*fileSystem.removeEmptyDirectory(settingsDirectory,session)}}).pipe(result2);return yield*read2.failure});var rollbackProjectSettingsInitialization=fn2("ProjectSettings.rollbackInitialization")(function*rollbackProjectSettingsInitialization2(fileSystem,rootDirectory,rollback,session){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const removed=yield*fileSystem.removeTextFileIfContent(settingsPath,projectSettingsInitializationContent(rollback.initialization),session);if(rollback.removeSettingsDirectory){yield*fileSystem.removeEmptyDirectory(settingsDirectory,session)}return removed});var ProjectSettings=Service("@punks/cli/ProjectSettings");var ProjectSettingsDefault=effect(ProjectSettings,gen2(function*ProjectSettingsDefault2(){const fileSystem=yield*ProjectSettingsFileSystem;return{infer:(rootDirectory)=>inferProjectSettings(fileSystem,rootDirectory),initialize:(rootDirectory,initialization,session)=>initializeProjectSettings(fileSystem,rootDirectory,initialization,session),read:(rootDirectory,session)=>readProjectSettings(fileSystem,rootDirectory,session),rollbackInitialization:(rootDirectory,rollback,session)=>rollbackProjectSettingsInitialization(fileSystem,rootDirectory,rollback,session),write:(rootDirectory,change,session)=>writeProjectSettings(fileSystem,rootDirectory,change,session)}}));import{execFileSync}from"node:child_process";import{accessSync,constants as constants2,existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String4,operation:Literals(["ensure-required-tool","infer-repo-settings"])}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var repoSettingsFile=".devpunks/settings.json";var repositoryManagerTools2={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var repositoryManagers2=new Set(Object.keys(repositoryManagerTools2));var backlogProviders2=new Set(["azure-devops","github","linear","monday"]);var assetProviders=new Set([...backlogProviders2,...repositoryManagers2]);var requiredToolsForRepositoryManager2=(repositoryManager)=>repositoryManagerTools2[repositoryManager];var reconcileRepositoryManagerTools=({previousRepositoryManager,requiredTools,repositoryManager})=>{const previousManagerTools=new Set(requiredToolsForRepositoryManager2(previousRepositoryManager));return[...new Set([...requiredTools.filter((tool)=>!previousManagerTools.has(tool)),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted()};var isRepositoryManager=(value5)=>typeof value5==="string"&&repositoryManagers2.has(value5);var isBacklogProvider=(value5)=>typeof value5==="string"&&backlogProviders2.has(value5);var isAssetProvider=(value5)=>typeof value5==="string"&&assetProviders.has(value5);var isStringArray=(value5)=>Array.isArray(value5)&&value5.every((tool)=>typeof tool==="string");var isRecord4=(value5)=>typeof value5==="object"&&value5!==null;var normalizeRepoSettings=(value5)=>{if(!isRecord4(value5)){return null}const record2=value5;if(!isBacklogProvider(record2.backlogProvider)||!isAssetProvider(record2.assetProviderSlug)||!isRepositoryManager(record2.repositoryManager)||!isStringArray(record2.requiredTools)){return null}return{assetProviderSlug:record2.assetProviderSlug,backlogProvider:record2.backlogProvider,...typeof record2.backlogProjectUrl==="string"?{backlogProjectUrl:record2.backlogProjectUrl}:{},...typeof record2.baselineVersion==="string"?{baselineVersion:record2.baselineVersion}:{},...typeof record2.cliVersion==="string"?{cliVersion:record2.cliVersion}:{},repositoryManager:record2.repositoryManager,requiredTools:[...new Set([...record2.requiredTools,...requiredToolsForRepositoryManager2(record2.repositoryManager)])].toSorted()}};var readRepoSettings=(rootDirectory)=>{const settingsPath=path9.join(rootDirectory,repoSettingsFile);if(!existsSync3(settingsPath)){return null}return normalizeRepoSettings(JSON.parse(readFileSync4(settingsPath,"utf-8")))};var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path9.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path9.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options4)=>{execFileSync(command,[...args2],{cwd:options4?.cwd,env:environment,stdio:options4?.stdio==="inherit"?["ignore","inherit","inherit"]:"ignore"})},execFileOutput:(command,args2,options4)=>execFileSync(command,[...args2],{cwd:options4?.cwd,encoding:"utf-8",env:environment})});var defaultRuntime=makeToolCommandRuntime({});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value5)=>{const match8=/\d+(?:\.\d+){0,2}/u.exec(value5);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Math.trunc(Number(part)))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index=0;index<length;index+=1){const actualPart=actual[index]??0;const minimumPart=minimum[index]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var isMinimumVersionSatisfied=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return true}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return true}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value5=env[candidate.env];return value5===undefined||value5.length===0?null:value5};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var manualProviderCliTools=Object.fromEntries([...new Set(Object.values(repositoryManagerTools2).flat())].map((toolId)=>[toolId,{ensureCommands:[],manual:true,requiredBins:[]}]));var installTool=({cwd,installTarget,runtime,stdio,toolId,versionContract})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}if(installTarget===undefined){throw toolManagementFailure("ensure-required-tool",`Required tool \`${toolId}\` cannot be installed automatically.`)}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(toolId)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the binary is still not available on PATH afterwards.`)}if(!isMinimumVersionSatisfied(versionContract,runtime,cwd)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the installed version does not satisfy ${versionContract.minimumVersion}.`)}};var ensureToolsInstalled=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>{const statuses=[];const toolCatalogById=Object.fromEntries(baseline.tools.map((tool)=>[tool.id,tool]));const cwd=runtime.cwd??homedir();for(const toolId of toolIds){const tool=toolCatalogById[toolId]===undefined?manualProviderCliTools[toolId]:{...toolCatalogById[toolId],manual:false};if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\` in baseline.`)}const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${toolId}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}const versionContract=tool;const alreadyPresent=runtime.commandExists(toolId)&&isMinimumVersionSatisfied(versionContract,runtime,cwd);const refreshLatest=options4.mode==="refresh-latest"&&!tool.manual;if(!alreadyPresent&&tool.manual){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${toolId}\` is not available on PATH. Install it before running scaffold/update workflows.`)}if(!alreadyPresent||refreshLatest){const installTarget=refreshLatest?tool.latestInstallTarget:tool.packageName;installTool({cwd,installTarget,runtime,stdio:options4.stdio,toolId,versionContract})}const ensureCommandContract=tool;if(!shouldSkipEnsureCommands(ensureCommandContract,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options4.stdio})}}statuses.push({status:alreadyPresent&&!refreshLatest?"already-present":"installed",toolId})}return statuses};var errorMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var errorStack=(cause)=>cause instanceof Error?cause.stack??cause.message:String(cause);var ensureToolsInstalledBestEffort=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],baseline,runtime,options4)}catch(error2){return[{errorMessage:errorMessage(error2),errorStack:errorStack(error2),status:"failed",toolId}]}});var readPackageForInstallation=(rootDirectory)=>{try{const value5=JSON.parse(readFileSync4(path9.join(rootDirectory,"package.json"),"utf-8"));return typeof value5==="object"&&value5!==null&&!Array.isArray(value5)?Object.fromEntries(Object.entries(value5)):null}catch{return null}};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path9.join(rootDirectory,"yarn.lock");return existsSync3(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync4(yarnLockfile,"utf-8"))};var dependencyInstallationCommand=(rootDirectory)=>{const rootManifest=readPackageForInstallation(rootDirectory);const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync3(path9.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case null:{return null}case"bun":{return["bun",["install","--ignore-scripts"]]}case"npm":{return["npm",["install","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=skip-build"]]}default:{return null}}};var backlogProviderChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"}];var assetChoices=[...backlogProviderChoices,{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"},{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var commitGateChoices=[{title:"Enabled",value:"enabled"},{title:"Disabled",value:"disabled"}];var isBacklogProvider2=(value5)=>value5==="github"||value5==="linear"||value5==="monday"||value5==="azure-devops";var isAssetProvider2=(value5)=>isBacklogProvider2(value5)||value5==="gitlab"||value5==="bitbucket";var isRepositoryManager2=(value5)=>value5==="github"||value5==="gitlab"||value5==="azure-devops"||value5==="bitbucket";var isCommitGatePolicy=(value5)=>value5==="enabled"||value5==="disabled";var selectCommitGate=(prompt,defaultValue)=>gen2(function*selectCommitGatePolicy(){const value5=yield*prompt.singleSelect({choices:commitGateChoices,defaultValue,message:"Select Commit Gate policy"});if(!isCommitGatePolicy(value5)){return yield*fail6(new CliPromptError({message:"Invalid Commit Gate policy selection."}))}return value5});var getDefaultBacklogProvider=(value5)=>{if(value5===undefined){return"github"}if(value5==="github"||value5==="linear"){return value5}return};var validateProjectUrl=(input2,backlogProvider)=>{const value5=input2.trim();try{const url=new URL(value5);if(url.protocol!=="http:"&&url.protocol!=="https:"){return{_tag:"InvalidProjectUrl",reason:"absolute-http"}}if(backlogProvider!=="linear"){return{_tag:"ValidProjectUrl",value:value5}}const pathSegments=url.pathname.split("/").filter(Boolean);if(url.hostname==="linear.app"&&pathSegments[1]==="project"){return{_tag:"InvalidProjectUrl",reason:"legacy-linear-project"}}if(url.hostname!=="linear.app"||pathSegments[1]!=="initiative"||pathSegments.length<3){return{_tag:"InvalidProjectUrl",reason:"linear-root-initiative"}}return{_tag:"ValidProjectUrl",value:value5}}catch{return{_tag:"InvalidProjectUrl",reason:"absolute-http"}}};var selectRepoSettings=({prompt,defaults:defaults2,retryCommand})=>gen2(function*selectSettings(){const defaultBacklogProvider=getDefaultBacklogProvider(defaults2?.backlogProvider);const backlogProviderValue=yield*prompt.singleSelect({choices:backlogProviderChoices,...defaultBacklogProvider===undefined?{}:{defaultValue:defaultBacklogProvider},message:"Select backlog provider"});if(!isBacklogProvider2(backlogProviderValue)){return yield*fail6(new CliPromptError({message:"Invalid backlog provider selection."}))}const backlogProvider=backlogProviderValue;const assetProviderValue=yield*prompt.singleSelect({choices:assetChoices,defaultValue:defaults2?.assetProviderSlug??backlogProvider,message:"Select asset provider"});if(!isAssetProvider2(assetProviderValue)){return yield*fail6(new CliPromptError({message:"Invalid asset provider selection."}))}const assetProviderSlug=assetProviderValue;const repositoryManagerValue=yield*prompt.singleSelect({choices:repositoryChoices,defaultValue:defaults2?.repositoryManager??"github",message:"Select repository manager"});if(!isRepositoryManager2(repositoryManagerValue)){return yield*fail6(new CliPromptError({message:"Invalid repository manager selection."}))}const repositoryManager=repositoryManagerValue;const commitGate=yield*selectCommitGate(prompt,defaults2?.commitGate??"enabled");const defaultBacklogProjectUrl=defaults2?.backlogProvider===backlogProvider?defaults2.backlogProjectUrl:undefined;const input2=yield*prompt.readLine(`Backlog project URL${defaultBacklogProjectUrl===undefined?"":` [${defaultBacklogProjectUrl}]`}: `);const backlogProjectUrl=validateProjectUrl(input2===""?defaultBacklogProjectUrl??"":input2,backlogProvider);if(backlogProjectUrl._tag==="InvalidProjectUrl"){let message=`Backlog project URL must be an absolute HTTP(S) URL. Rerun \`${retryCommand}\`.`;if(backlogProjectUrl.reason==="legacy-linear-project"){message=`A legacy Linear Project URL cannot identify the backlog root. Enter the root Initiative URL when you rerun \`${retryCommand}\`.`}else if(backlogProjectUrl.reason==="linear-root-initiative"){message=`A Linear backlog destination must be a root Initiative URL. Rerun \`${retryCommand}\`.`}return yield*fail6(new CliPromptError({message}))}return{assetProviderSlug,backlogProjectUrl:backlogProjectUrl.value,backlogProvider,commitGate,repositoryManager}});var ensureCommandMetadata=declareCommandMetadata({examples:[{command:"hi ensure",summary:"Reconfigure current project settings."}],group:"commands",interaction:"required",name:"ensure",options:[],outputModes:["interactive","plain"],summary:"Reconfigure backlog, asset, repository, and backlog project URL settings only."});var mapSettingsError=(error2)=>new CliPromptError({message:error2._tag==="ProjectSettingsMissing"?`${projectSettingsFile} was not found. Run \`hi init\` first.`:error2.message});var runEnsure=({rootDirectory,prompt})=>gen2(function*ensureSettings(){const projectSettings=yield*ProjectSettings;const current=(yield*projectSettings.read(rootDirectory).pipe(mapError3(mapSettingsError))).settings;const selected=yield*selectRepoSettings({defaults:current,prompt,retryCommand:"hi ensure"});const requiredTools=reconcileRepositoryManagerTools({previousRepositoryManager:current.repositoryManager,repositoryManager:selected.repositoryManager,requiredTools:current.requiredTools});yield*projectSettings.write(rootDirectory,{_tag:"ReconfigurationChange",assetProviderSlug:selected.assetProviderSlug,backlogProjectUrl:selected.backlogProjectUrl,backlogProvider:selected.backlogProvider,commitGate:selected.commitGate,repositoryManager:selected.repositoryManager,requiredTools}).pipe(mapError3(mapSettingsError));return{changes:[{action:"configure",state:"completed",subject:projectSettingsFile}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var executeEnsureCommand=(input2)=>captureCommandResult(runEnsure(input2));var ensureCommand=exports_Command.make(ensureCommandMetadata.name,{},()=>scoped2(gen2(function*runEnsureCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi ensure` requires interactive input and is unavailable in JSON mode.":"`hi ensure` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi ensure"})}const prompt=yield*PromptLive;return yield*executeEnsureCommand({prompt,rootDirectory:process.cwd()})}))).pipe(withCommandMetadata(ensureCommandMetadata));import path11 from"node:path";import{createHash as createHash4}from"node:crypto";import{execFileSync as execFileSync2}from"node:child_process";import{accessSync as accessSync2,constants as constants3,existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync5,realpathSync,writeFileSync as writeFileSync3}from"node:fs";import path10 from"node:path";var digest2=(content)=>createHash4("sha256").update(content).digest("hex");var read2=(filePath)=>{try{return existsSync4(filePath)?readFileSync5(filePath,"utf-8"):null}catch{return null}};var isCommitGateApplicable=(rootDirectory)=>{const packageJson=read2(path10.join(rootDirectory,"package.json"));if(packageJson===null){return false}try{const parsed=JSON.parse(packageJson);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return false}const hasLockfile=["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"].some((name2)=>existsSync4(path10.join(rootDirectory,name2)));const declaredManager="packageManager"in parsed&&typeof parsed.packageManager==="string"?parsed.packageManager:null;return hasLockfile||declaredManager!==null&&/^(?:npm|pnpm|bun|yarn)@\S+$/u.test(declaredManager)}catch{return false}};var commitGateDesiredStateHash=(rootDirectory)=>digest2(JSON.stringify([["lefthook.yml",read2(path10.join(rootDirectory,"lefthook.yml"))],["lefthook.yaml",read2(path10.join(rootDirectory,"lefthook.yaml"))],[".devpunks/commit-gate-contracts.json",read2(path10.join(rootDirectory,".devpunks/commit-gate-contracts.json"))],[".agents/scripts/commit-gate-runner.mjs",read2(path10.join(rootDirectory,".agents/scripts/commit-gate-runner.mjs"))]]));var hookPath=(rootDirectory)=>{try{return path10.resolve(rootDirectory,execFileSync2("git",["rev-parse","--git-path","hooks/pre-commit"],{cwd:rootDirectory,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim())}catch{return path10.join(rootDirectory,".git/hooks/pre-commit")}};var indent=(line)=>line.length-line.trimStart().length;var managedLintCommand=(config)=>{const lines2=config.split(`
304
304
  `);const preCommit=lines2.findIndex((line)=>line.trim()==="pre-commit:");if(preCommit===-1){return null}const preIndent=indent(lines2[preCommit]);const preCommitEnd=lines2.findIndex((line,index)=>index>preCommit&&line.trim()!==""&&indent(line)<=preIndent);const preCommitLimit=preCommitEnd===-1?lines2.length:preCommitEnd;const commands=lines2.findIndex((line,index)=>index>preCommit&&index<preCommitLimit&&line.trim()==="commands:"&&indent(line)>preIndent);if(commands===-1){return null}const commandsIndent=indent(lines2[commands]);const end=lines2.findIndex((line,index)=>index>commands&&line.trim()!==""&&indent(line)<=commandsIndent);const limit=end===-1?lines2.length:end;const lint=lines2.findIndex((line,index)=>index>commands&&index<limit&&line.trim()==="lint:"&&indent(line)>commandsIndent);if(lint===-1){return null}const lintIndent=indent(lines2[lint]);const lintEnd=lines2.findIndex((line,index)=>index>lint&&line.trim()!==""&&!line.trimStart().startsWith("#")&&indent(line)<=lintIndent);const lintLimit=lintEnd===-1?limit:Math.min(limit,lintEnd);const lintFields=lines2.slice(lint+1,lintLimit).filter((line)=>line.trim()!==""&&!line.trimStart().startsWith("#"));const fieldIndent=lintFields[0]===undefined?undefined:indent(lintFields[0]);const run6=lintFields.find((line)=>line.trimStart().startsWith("run:")&&indent(line)===fieldIndent);return run6?.slice(run6.indexOf(":")+1).trim()===managedCommitGateCommand?managedCommitGateCommand:null};var expectedLefthookVersion="2.1.10";var expectedLefthookIntegrity="sha512-K7mM4WoqMwqfXYK11EHy+lSH1uW8XHni3Yn/bSqyerPkUPygGdf3xn18JoV5HyA06xuQL3ofGAOjG01QX9oJ4w==";var isRecord5=(value5)=>typeof value5==="object"&&value5!==null;var isConfinedRelativePath=(relativePath)=>relativePath===""||relativePath!==".."&&!relativePath.startsWith(`..${path10.sep}`)&&!path10.isAbsolute(relativePath);var confinedPackageDirectory=({candidate,rootDirectory})=>{try{const canonicalRoot=realpathSync(rootDirectory);const packageDirectory=path10.resolve(rootDirectory,candidate);const canonicalPackageDirectory=realpathSync(packageDirectory);const canonicalManifest=realpathSync(path10.join(packageDirectory,"package.json"));const directoryRelative=path10.relative(canonicalRoot,canonicalPackageDirectory);const manifestRelative=path10.relative(canonicalRoot,canonicalManifest);return isConfinedRelativePath(directoryRelative)&&isConfinedRelativePath(manifestRelative)?packageDirectory:null}catch{return null}};var commitGatePackageDirectory=(rootDirectory)=>{const resolvedRoot=path10.resolve(rootDirectory);const rootPackageDirectory=confinedPackageDirectory({candidate:".",rootDirectory});if(rootPackageDirectory!==null){return rootPackageDirectory}const contracts=read2(path10.join(rootDirectory,".devpunks","commit-gate-contracts.json"));if(contracts===null){return resolvedRoot}try{const parsed=JSON.parse(contracts);if(!Array.isArray(parsed)){return resolvedRoot}for(const contract of parsed){if(!isRecord5(contract)||typeof contract.path!=="string"){continue}const packageDirectory=confinedPackageDirectory({candidate:contract.path,rootDirectory});if(packageDirectory!==null){return packageDirectory}}return resolvedRoot}catch{return resolvedRoot}};var packageDeclaration=(rootDirectory)=>{const packageJson=read2(path10.join(rootDirectory,"package.json"));if(packageJson===null){return null}try{const parsed=JSON.parse(packageJson);if(!isRecord5(parsed)){return null}const dependencies=isRecord5(parsed.dependencies)?parsed.dependencies:undefined;const devDependencies=isRecord5(parsed.devDependencies)?parsed.devDependencies:undefined;const declaration=devDependencies?.lefthook??dependencies?.lefthook;return typeof declaration==="string"?declaration:null}catch{return null}};var packageLockResolution=(rootDirectory)=>{for(const fileName of["package-lock.json","npm-shrinkwrap.json"]){const lockfile=read2(path10.join(rootDirectory,fileName));if(lockfile===null){continue}try{const parsed=JSON.parse(lockfile);if(!isRecord5(parsed)){continue}const packages=isRecord5(parsed.packages)?parsed.packages:undefined;const dependencies=isRecord5(parsed.dependencies)?parsed.dependencies:undefined;const rawEntry=packages?.["node_modules/lefthook"]??dependencies?.lefthook;if(isRecord5(rawEntry)){return{integrity:typeof rawEntry.integrity==="string"?rawEntry.integrity:null,version:typeof rawEntry.version==="string"?rawEntry.version:null}}}catch{return{integrity:null,version:null}}}return{integrity:null,version:null}};var bunLockResolution=(rootDirectory)=>{const lockfile=read2(path10.join(rootDirectory,"bun.lock"));if(lockfile===null){return{integrity:null,version:null}}const entry=/^\s*"lefthook":\s*\[\s*"lefthook@(?<version>[^"]+)"[^\n]*?(?<integrity>sha512-[^"]+)"/mu.exec(lockfile);return{integrity:entry?.groups?.integrity??null,version:entry?.groups?.version??null}};var textLockResolution=(rootDirectory)=>{for(const fileName of["pnpm-lock.yaml","yarn.lock"]){const lockfile=read2(path10.join(rootDirectory,fileName));if(lockfile===null){continue}const match8=/lefthook[^\n]*\n(?:[^\n]*\n)*?\s+version:\s*["']?(?<version>[^"'\s]+)|lefthook[^\n]*:\s*\n\s+version\s+["'](?<yarnVersion>[^"']+)["']/mu.exec(lockfile);if(match8!==null){return{integrity:null,version:match8.groups?.version??match8.groups?.yarnVersion??null}}return{integrity:null,version:"unknown"}}if(existsSync4(path10.join(rootDirectory,"bun.lockb"))){return{integrity:null,version:"unknown"}}return{integrity:null,version:null}};var installedResolution=(rootDirectory)=>{const packageJson=read2(path10.join(rootDirectory,"node_modules","lefthook","package.json"));if(packageJson===null){return{integrity:null,version:null}}try{const parsed=JSON.parse(packageJson);return{integrity:null,version:isRecord5(parsed)&&typeof parsed.version==="string"?parsed.version:null}}catch{return{integrity:null,version:null}}};class CommitGateProbeFailure extends TaggedErrorClass()("@punks/cli/commit-gate/ProbeFailure",{cause:Unknown2}){}var probeCommand=(executable,args2,rootDirectory)=>runSync2(try_3({catch:(cause)=>new CommitGateProbeFailure({cause}),try:()=>{if(path10.isAbsolute(executable)){accessSync2(executable,constants3.X_OK)}return execFileSync2(executable,args2,{cwd:rootDirectory,encoding:"utf-8",maxBuffer:64*1024,stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}}).pipe(match6({onFailure:()=>null,onSuccess:(output2)=>output2})));var isExecutable=(file5)=>runSync2(try_3({catch:(cause)=>new CommitGateProbeFailure({cause}),try:()=>{accessSync2(file5,constants3.X_OK);return true}}).pipe(match6({onFailure:()=>false,onSuccess:(value5)=>value5})));var observedDependencyVersion=(rootDirectory)=>{const declaration=packageDeclaration(rootDirectory);if(declaration===null||declaration!==expectedLefthookVersion){return declaration}const lockResolutions=[packageLockResolution(rootDirectory),bunLockResolution(rootDirectory),textLockResolution(rootDirectory)];const resolutions=[...lockResolutions,installedResolution(rootDirectory)];const resolvedVersion=resolutions.find(({version:version4})=>version4!==null&&version4!==expectedLefthookVersion)?.version;if(resolvedVersion!==undefined){return resolvedVersion}if(!lockResolutions.some(({version:version4})=>version4===expectedLefthookVersion)){return`${expectedLefthookVersion}#lock-unverified`}const integrityDrift=resolutions.some(({integrity})=>integrity!==null&&integrity!==expectedLefthookIntegrity);if(integrityDrift){return`${expectedLefthookVersion}#integrity-drift`}if(installedResolution(rootDirectory).version!==expectedLefthookVersion){return`${expectedLefthookVersion}#not-installed`}const executable=path10.join(rootDirectory,"node_modules",".bin","lefthook");const output2=probeCommand(executable,["--version"],rootDirectory);const version3=output2?.match(/^(?:lefthook version v?|v)?(?<version>\d+\.\d+\.\d+)(?: [a-f0-9]{40})?$/u)?.groups?.version;return version3??`${expectedLefthookVersion}#execution-unverified`};var observeCommitGate=(rootDirectory)=>{const packageDirectory=commitGatePackageDirectory(rootDirectory);const config=read2(path10.join(rootDirectory,"lefthook.yml"))??read2(path10.join(rootDirectory,"lefthook.yaml"));const activeHookPath=hookPath(rootDirectory);const hook=read2(activeHookPath);const invokesLefthook=hook!==null&&hook.split(`
305
305
  `).some((line)=>{const command=line.trim();return command.length>0&&!command.startsWith("#")&&(/^(?:(?:command|exec)\s+)?lefthook\s+run\s+["']?pre-commit["']?(?:\s|$)/u.test(command)||/^call_lefthook\s+run\s+["']pre-commit["'](?:\s|$)/u.test(command))});const packageVersionValue=observedDependencyVersion(packageDirectory);const hasOtherManager=existsSync4(path10.join(rootDirectory,".husky"))||existsSync4(path10.join(rootDirectory,".githooks"))||probeCommand("git",["config","--get","core.hooksPath"],rootDirectory)!==null||hook!==null&&hook.trim().length>0&&!invokesLefthook;let manager="none";if(hasOtherManager){manager="other"}else if(config!==null){manager="lefthook"}const lintCommand=config===null?null:managedLintCommand(config);return{configHash:config===null?null:digest2(config),dependencyVersion:packageVersionValue,hookHash:invokesLefthook&&isExecutable(activeHookPath)?digest2(hook):null,hookManager:manager,lintCommandHash:lintCommand===null?null:digest2(lintCommand)}};var writeCommitGateLifecycleReceipt=({desiredStateHash,observed,policy,rootDirectory,verifiedAt=runSync2(now2.pipe(map6(formatIso2)))})=>{const current=observed??observeCommitGate(rootDirectory);const verification=verifyAndBuildLifecycleReceipt({desiredStateHash,observed:current,...policy===undefined?{}:{policy},verifiedAt});if(verification._tag==="Unresolved"){return verification}const receiptPath=path10.join(rootDirectory,commitGateLifecycleReceiptFile);mkdirSync3(path10.dirname(receiptPath),{recursive:true});writeFileSync3(receiptPath,`${JSON.stringify(verification.receipt,null,2)}
306
- `,"utf-8");return verification};var commitGateVerifyCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"verify",options:[{name:"repo-root",summary:"Repository root. Defaults to the current directory."}],outputModes:["interactive","plain","json"],summary:"Verify the installed Commit Gate and write its lifecycle receipt."});var repoRootOption=exports_Flag.string(metadataOptionName(commitGateVerifyCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(commitGateVerifyCommandMetadata,"repo-root"));var runCommitGateVerify=({rootDirectory})=>gen2(function*verifyCommitGate(){const projectSettings=yield*ProjectSettings;const settings=yield*projectSettings.read(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:"Commit Gate verification requires initialized project settings.",recoveryCommand:"hi init"})));const verification=writeCommitGateLifecycleReceipt({desiredStateHash:commitGateDesiredStateHash(rootDirectory),observed:observeCommitGate(rootDirectory),...settings.settings.commitGate===undefined?{}:{policy:settings.settings.commitGate},rootDirectory});if(verification._tag==="Unresolved"){return yield*new CliValidationError({message:verification.reason,recoveryCommand:"hi commit-gate verify"})}return{changes:[{action:"verify",state:"completed",subject:".devpunks/commit-gate-lifecycle-receipt.json"}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var commitGateVerifyCommand=exports_Command.make(commitGateVerifyCommandMetadata.name,{"repo-root":repoRootOption},({"repo-root":repoRoot})=>captureCommandResult(runCommitGateVerify({rootDirectory:path11.resolve(repoRoot)}))).pipe(withCommandMetadata(commitGateVerifyCommandMetadata));var commitGateCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"commit-gate",options:[],outputModes:["interactive","plain","json"],summary:"Inspect and verify Commit Gate lifecycle state."});var commitGateCommand=exports_Command.make(commitGateCommandMetadata.name,{},()=>succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]})).pipe(withCommandMetadata(commitGateCommandMetadata),exports_Command.withSubcommands([commitGateVerifyCommand]));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String4}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String4}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={message:String4,operation:Literals(["list","install","remove"]),scope:SkillsCliScope};class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String4}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String4}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String4}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String4,version:String4}){}var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String4),cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),name:String4,path:String4,revision:String4,scope:SkillsCliScope,source:String4,version:String4});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String4,skillPath:String4,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,targetSelection){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,targetSelection)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy2)=>("version"in copy2)?JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"","verified",copy2.version,copy2.source,copy2.revision,copy2.compatibility,[...copy2.boundAgents].toSorted()]):JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.verification,copy2.path,[...copy2.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy2)=>({...copy2,boundAgents:[...copy2.boundAgents].toSorted()})));continue}for(const copy2 of inspection.copies){if(copy2.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy2.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy2,boundAgents:[...copy2.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy2)=>("compatibility"in copy2)&&copy2.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy2)=>copy2.scope==="global"||isWithinCanonicalPath(input2.cwd,copy2.projectRoot)).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy2)=>copy2.scope===effective.scope);if(topCandidates.some((copy2)=>installedOperatorSkillCopyIdentity(copy2)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}if(!("version"in effective)){return{_tag:"Outdated",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))===true){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index=0;index<length;index+=1){const leftIdentifier=left[index];const rightIdentifier=right[index];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index=0;index<parsedLeft.core.length;index+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index],parsedRight.core[index]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var authoritativeContentManifest=Object.freeze([Object.freeze({path:"SKILL.md",sha256:"aee7ff55492ba810ca75bfbc8bbf5d4a14695828634c3fb1c6aea0a895589b98"}),Object.freeze({path:"references/commands.md",sha256:"62e07c52acd6add81a8feccbe39eb99521d6a2c9682d97e940bcc39a5e705e1a"}),Object.freeze({path:"references/post-command-flow.md",sha256:"0bb59c307a9d4ce1be73f4660870df4a8f8831958712210872ecf98abab96eb2"})]);var authoritativeOperatorSkillTarget=Object.freeze({cliCompatibility:Object.freeze({maximumExclusive:"6.0.0",minimum:"4.0.0"}),contentManifest:authoritativeContentManifest,revision:"dbfd199e89ab17f6241270ab1f23ea50c294926f",source:"https://github.com/wearedevpunks/skills/tree/dbfd199e89ab17f6241270ab1f23ea50c294926f/skills/agnostic/cli/hi-cli",version:"2.0.0"});var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}if(target.source!==authoritativeOperatorSkillTarget.source||target.version!==authoritativeOperatorSkillTarget.version||target.revision!==authoritativeOperatorSkillTarget.revision||target.cliCompatibility.minimum!==authoritativeOperatorSkillTarget.cliCompatibility.minimum||target.cliCompatibility.maximumExclusive!==authoritativeOperatorSkillTarget.cliCompatibility.maximumExclusive||JSON.stringify(target.contentManifest)!==JSON.stringify(authoritativeOperatorSkillTarget.contentManifest)){return"NonAuthoritativeIdentity"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:authoritativeOperatorSkillTarget}};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const outdatedOperatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&("verification"in skill)&&skill.verification==="outdated");const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:"global",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:"project-local",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2){const resolution=resolveOperatorSkillTarget({activeCliVersion:input2.activeCliVersion,candidates:[authoritativeOperatorSkillTarget]});if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target,targetSelection:input2.targetSelection})),result2(skillsCli.list({cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target,targetSelection:input2.targetSelection}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy2,target)=>("version"in copy2)&&copy2.version===target.version&&copy2.source===target.source&&copy2.revision===target.revision&&copy2.compatibility==="compatible";var copyAppliesToScope=(copy2,input2)=>copy2.scope==="global"||copy2.projectRoot===input2.projectRoot;var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy2)=>copyMatchesTarget(copy2,target)&&copyAppliesToScope(copy2,input2));var hasCompetingCopyIdentity=(inspection,copy2,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy2));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy2=targetCopy(inspection,input2,target);if(copy2!==undefined){if(hasCompetingCopyIdentity(inspection,copy2,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy2,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,target){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({cwd:operatorSkillScopeCwd(scope3,input2),scope:scope3==="global"?"global":"project",target,targetSelection:input2.targetSelection}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2);return verifyOperatorSkillScope(scope3,input2,target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&inspection.failure._tag==="SkillsCliVerificationFailure"&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedScope=(operation,scope3,before,input2)=>{const inspection=inspectionFor(before,scope3);if(inspection?._tag!=="Inspected"){return}const copy2=targetCopy(inspection,input2,before.target);if(copy2===undefined||hasCompetingCopyIdentity(inspection,copy2,input2)){return}return{_tag:"AlreadyVerified",copy:copy2,operation,scope:scope3,verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const candidateScopes=scopesToMutate(operation,before);const alreadyVerified=candidateScopes.flatMap((scope3)=>{const action2=alreadyVerifiedScope(operation,scope3,before,input2);return action2===undefined?[]:[action2]});const verifiedScopes=new Set(alreadyVerified.map((action2)=>action2.scope));const actions=[...unknownScopeFailures(operation,before,input2),...alreadyVerified];let wrote=false;const scopes=candidateScopes.filter((scope3)=>!verifiedScopes.has(scope3));for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2){return yield*mutateOperatorSkill("install",input2)});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2){return yield*mutateOperatorSkill("update",input2)});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.length>0));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy2)=>JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.path,[...copy2.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}if(legacyCopiesMatch(input2.legacySnapshots.get(scope3)??[],observed)){return[]}const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason:"LegacyChanged",reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterRemoval",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context3,failure){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const legacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(legacyCopies.get(scope3)??[],observedLegacy);if(legacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterFailure",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){legacyCopies.set(scope3,observedLegacy)}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context3){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const verification=yield*inspectOperatorSkillLifecycle(input2);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);if(inspection!==undefined&&inspection.legacy.length>0){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){legacyCopies.set(scope3,observedCurrentLegacy)}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit??recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]);const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const legacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){const replacementAgents=new Set(barrierCopies.get(scope3)?.boundAgents);const uncovered=(legacyCopies.get(scope3)??[]).some((copy2)=>copy2.boundAgents.some((agent)=>!replacementAgents.has(agent)));if(!uncovered){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",reason:"ReplacementCoverageIncomplete",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(legacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove4=yield*result2(skillsCli.remove({cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project",targetSelection:input2.targetSelection}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context3={barrierCopies,input:input2,legacyCopies,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target};if(isFailure2(remove4)){const failureResult=yield*handleFailedLegacyRemoval(context3,remove4.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context3))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2){return yield*migrateLegacyOperatorSkillPolicy(input2)});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput){return yield*migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection},retry5.affectedScopes,retry5.target,retry5.phase)});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),contentManifest:ArraySchema(Struct({path:String4,sha256:String4})),revision:String4,source:String4,version:String4})});var mutationRetrySchema=Struct({input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeRetry=(retry5)=>{const{targetSelection:_targetSelection,...input2}=retry5.input;return Buffer.from(JSON.stringify({...retry5,input:input2}),"utf-8").toString("base64url")};var encodeMigrationRetry=(retry5)=>encodeRetry(retry5);var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>{const decoded=decodeUnknownSync(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")));return{...decoded,input:{...decoded.input,targetSelection:"automatic"}}}});var encodeMutationRetry=(retry5)=>encodeRetry(retry5);var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>{const decoded=decodeUnknownSync(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")));return{...decoded,input:{...decoded.input,targetSelection:"automatic"}}}});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection};const before=yield*inspectOperatorSkillLifecycle(retryInput);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,retry5.target);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request){const{action:action2,input:input2}=request;if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){const lifecycle2=request.mutationRetryToken===undefined?yield*action2==="install"?installOperatorSkill(input2):updateOperatorSkill(input2):yield*decodeMutationRetry(request.mutationRetryToken).pipe(flatMap3((retry5)=>retryOperatorSkillMutation(retry5,action2,input2)));return{action:action2,lifecycle:lifecycle2}}const lifecycle=request.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2):yield*decodeMigrationRetry(request.migrationRetryToken).pipe(flatMap3((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2)));return{action:action2,lifecycle}});var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure={};for(const[key,nestedValue]of Object.entries(value5)){failure[key]=nestedValue}return Object.fromEntries(["_tag","exitCode","message","operation","reason","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){const omittedValue=undefined;return omittedValue}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"status",code:`operator-target-${lifecycle.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.resolution)}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}let nextActions;if(lifecycle.installed._tag==="Outdated"){nextActions=[{kind:"run",subject:"hi operator update"}]}else if(issues.length===0){nextActions=[{kind:"none"}]}else{nextActions=[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}]}return{changes,degradations:[],issues,nextActions,status:status2,warnings:lifecycle.installed._tag==="Outdated"?[{code:"operator-installed-outdated",subject:operatorFact(lifecycle.installed.effective)}]:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.before.resolution)}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"migrate",code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context3=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context3})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context3)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context3)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,mode="plain")=>gen2(function*runOperatorCommand(){const result4=yield*operation(action2,mode==="interactive"?"prompt":"automatic");if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;return yield*captureCommandResult(executeOperatorCommand(action2,operation,mode))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String4,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String4,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String4,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String4,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
306
+ `,"utf-8");return verification};var commitGateVerifyCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"verify",options:[{name:"repo-root",summary:"Repository root. Defaults to the current directory."}],outputModes:["interactive","plain","json"],summary:"Verify the installed Commit Gate and write its lifecycle receipt."});var repoRootOption=exports_Flag.string(metadataOptionName(commitGateVerifyCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(commitGateVerifyCommandMetadata,"repo-root"));var runCommitGateVerify=({rootDirectory})=>gen2(function*verifyCommitGate(){const projectSettings=yield*ProjectSettings;const settings=yield*projectSettings.read(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:"Commit Gate verification requires initialized project settings.",recoveryCommand:"hi init"})));const verification=writeCommitGateLifecycleReceipt({desiredStateHash:commitGateDesiredStateHash(rootDirectory),observed:observeCommitGate(rootDirectory),...settings.settings.commitGate===undefined?{}:{policy:settings.settings.commitGate},rootDirectory});if(verification._tag==="Unresolved"){return yield*new CliValidationError({message:verification.reason,recoveryCommand:"hi commit-gate verify"})}return{changes:[{action:"verify",state:"completed",subject:".devpunks/commit-gate-lifecycle-receipt.json"}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var commitGateVerifyCommand=exports_Command.make(commitGateVerifyCommandMetadata.name,{"repo-root":repoRootOption},({"repo-root":repoRoot})=>captureCommandResult(runCommitGateVerify({rootDirectory:path11.resolve(repoRoot)}))).pipe(withCommandMetadata(commitGateVerifyCommandMetadata));var commitGateCommandMetadata=declareCommandMetadata({examples:[{command:"hi commit-gate verify",summary:"Verify the installed Commit Gate."}],group:"commands",interaction:"none",name:"commit-gate",options:[],outputModes:["interactive","plain","json"],summary:"Inspect and verify Commit Gate lifecycle state."});var commitGateCommand=exports_Command.make(commitGateCommandMetadata.name,{},()=>succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]})).pipe(withCommandMetadata(commitGateCommandMetadata),exports_Command.withSubcommands([commitGateVerifyCommand]));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String4}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String4}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={message:String4,operation:Literals(["resolve","list","install","remove"]),scope:SkillsCliScope};class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String4}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String4}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String4}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String4,version:String4}){}var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String4),cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),name:String4,path:String4,revision:String4,scope:SkillsCliScope,source:String4,version:String4});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String4,skillPath:String4,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,targetSelection){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,targetSelection)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy2)=>("version"in copy2)?JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"","verified",copy2.version,copy2.source,copy2.revision,copy2.compatibility,[...copy2.boundAgents].toSorted()]):JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.verification,copy2.path,[...copy2.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy2)=>({...copy2,boundAgents:[...copy2.boundAgents].toSorted()})));continue}for(const copy2 of inspection.copies){if(copy2.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy2.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy2,boundAgents:[...copy2.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy2)=>("compatibility"in copy2)&&copy2.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy2)=>copy2.scope==="global"||isWithinCanonicalPath(input2.cwd,copy2.projectRoot)).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy2)=>copy2.scope===effective.scope);if(topCandidates.some((copy2)=>installedOperatorSkillCopyIdentity(copy2)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}if(!("version"in effective)){return{_tag:"Outdated",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))===true){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index=0;index<length;index+=1){const leftIdentifier=left[index];const rightIdentifier=right[index];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index=0;index<parsedLeft.core.length;index+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index],parsedRight.core[index]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const outdatedOperatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&("verification"in skill)&&skill.verification==="outdated");const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:"global",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:"project-local",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var resolveOperatorSkillTargetForOperation=fn2("OperatorSkillLifecycle.resolveTarget")(function*resolveOperatorSkillTargetForOperation2(input2){const skillsCli=yield*SkillsCli;const resolution=yield*result2(skillsCli.resolveTarget({activeCliVersion:input2.activeCliVersion,cwd:input2.cwd,scope:"global",targetSelection:input2.targetSelection}));return isFailure2(resolution)?{_tag:"UpstreamResolutionFailed",failure:resolution.failure}:resolution.success});var inspectResolvedOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.inspectResolved")(function*inspectResolvedOperatorSkillLifecycle2(input2,resolution){if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target,targetSelection:input2.targetSelection})),result2(skillsCli.list({cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target,targetSelection:input2.targetSelection}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2,resolution){if(resolution!==undefined){return yield*inspectResolvedOperatorSkillLifecycle(input2,resolution)}return yield*scoped2(resolveOperatorSkillTargetForOperation(input2).pipe(flatMap3((resolved)=>inspectResolvedOperatorSkillLifecycle(input2,resolved))))});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy2,target)=>("version"in copy2)&&copy2.version===target.version&&copy2.source===target.source&&copy2.revision===target.revision&&copy2.compatibility==="compatible";var copyAppliesToScope=(copy2,input2)=>copy2.scope==="global"||copy2.projectRoot===input2.projectRoot;var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy2)=>copyMatchesTarget(copy2,target)&&copyAppliesToScope(copy2,input2));var hasCompetingCopyIdentity=(inspection,copy2,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy2));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy2=targetCopy(inspection,input2,target);if(copy2!==undefined){if(hasCompetingCopyIdentity(inspection,copy2,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy2,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,resolvedTarget){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({cwd:operatorSkillScopeCwd(scope3,input2),resolvedTarget,scope:scope3==="global"?"global":"project",targetSelection:input2.targetSelection}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);return verifyOperatorSkillScope(scope3,input2,resolvedTarget.target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&inspection.failure._tag==="SkillsCliVerificationFailure"&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedScope=(operation,scope3,before,input2)=>{const inspection=inspectionFor(before,scope3);if(inspection?._tag!=="Inspected"){return}const copy2=targetCopy(inspection,input2,before.target);if(copy2===undefined||hasCompetingCopyIdentity(inspection,copy2,input2)){return}return{_tag:"AlreadyVerified",copy:copy2,operation,scope:scope3,verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2,resolvedTarget){const before=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const candidateScopes=scopesToMutate(operation,before);const alreadyVerified=candidateScopes.flatMap((scope3)=>{const action2=alreadyVerifiedScope(operation,scope3,before,input2);return action2===undefined?[]:[action2]});const verifiedScopes=new Set(alreadyVerified.map((action2)=>action2.scope));const actions=[...unknownScopeFailures(operation,before,input2),...alreadyVerified];let wrote=false;const scopes=candidateScopes.filter((scope3)=>!verifiedScopes.has(scope3));for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,resolvedTarget);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2,operationTarget){return yield*scoped2(gen2(function*runInstall(){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));if(resolution._tag!=="Resolved"){const before={_tag:"TargetResolutionFailed",resolution};return{_tag:"TargetResolutionFailed",actions:[],before,operation:"install",reload:{_tag:"NotRequired"}}}return yield*mutateOperatorSkill("install",input2,resolution)}))});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2,operationTarget){return yield*scoped2(gen2(function*runUpdate(){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));if(resolution._tag!=="Resolved"){const before={_tag:"TargetResolutionFailed",resolution};return{_tag:"TargetResolutionFailed",actions:[],before,operation:"update",reload:{_tag:"NotRequired"}}}return yield*mutateOperatorSkill("update",input2,resolution)}))});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.length>0));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy2)=>JSON.stringify([copy2.scope,copy2.scope==="project-local"?copy2.projectRoot:"",copy2.path,[...copy2.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}if(legacyCopiesMatch(input2.legacySnapshots.get(scope3)??[],observed)){return[]}const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason:"LegacyChanged",reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterRemoval",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context3,failure){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2,context3.resolvedTarget);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const legacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(legacyCopies.get(scope3)??[],observedLegacy);if(legacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:"LegacyChangedAfterFailure",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){legacyCopies.set(scope3,observedLegacy)}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context3){const{legacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target}=context3;const verification=yield*inspectOperatorSkillLifecycle(input2,context3.resolvedTarget);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);if(inspection!==undefined&&inspection.legacy.length>0){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({afterIndex:scopeIndex,legacySnapshots:legacyCopies,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){legacyCopies.set(scope3,observedCurrentLegacy)}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit??recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]);const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before,resolvedTarget){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,resolvedTarget);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,resolvedTarget,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2,resolvedTarget);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase,operationTarget){const resolution=operationTarget??(yield*resolveOperatorSkillTargetForOperation(input2));const before=yield*inspectOperatorSkillLifecycle(input2,resolution);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",actions:[],before:{_tag:"TargetResolutionFailed",resolution},reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before,resolution);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,resolution,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const legacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){const replacementAgents=new Set(barrierCopies.get(scope3)?.boundAgents);const uncovered=(legacyCopies.get(scope3)??[]).some((copy2)=>copy2.boundAgents.some((agent)=>!replacementAgents.has(agent)));if(!uncovered){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",reason:"ReplacementCoverageIncomplete",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(legacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove4=yield*result2(skillsCli.remove({cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project",targetSelection:input2.targetSelection}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context3={barrierCopies,input:input2,legacyCopies,lostBarrierScopes,refusedScopes,reportedLegacyScopes,resolvedTarget:resolution,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target};if(isFailure2(remove4)){const failureResult=yield*handleFailedLegacyRemoval(context3,remove4.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context3))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2,operationTarget){return yield*scoped2(migrateLegacyOperatorSkillPolicy(input2,undefined,undefined,undefined,operationTarget))});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput,operationTarget){return yield*scoped2(migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection},retry5.affectedScopes,retry5.target,retry5.phase,operationTarget))});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String4,minimum:String4}),contentManifest:ArraySchema(Struct({path:String4,sha256:String4})),revision:String4,source:String4,version:String4})});var mutationRetrySchema=Struct({input:Struct({activeCliVersion:String4,cwd:String4,projectRoot:String4}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeRetry=(retry5)=>{const{targetSelection:_targetSelection,...input2}=retry5.input;return Buffer.from(JSON.stringify({...retry5,input:input2}),"utf-8").toString("base64url")};var encodeMigrationRetry=(retry5)=>encodeRetry(retry5);var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>{const decoded=decodeUnknownSync(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")));return{...decoded,input:{...decoded.input,targetSelection:"automatic"}}}});var encodeMutationRetry=(retry5)=>encodeRetry(retry5);var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>{const decoded=decodeUnknownSync(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")));return{...decoded,input:{...decoded.input,targetSelection:"automatic"}}}});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput,resolvedTarget)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion,targetSelection:currentInput.targetSelection};const before=yield*inspectOperatorSkillLifecycle(retryInput,resolvedTarget);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,resolvedTarget);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request){return yield*scoped2(gen2(function*executeResolvedOperatorAction(){const{action:action2,input:input2}=request;const resolution=yield*resolveOperatorSkillTargetForOperation(input2);if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2,resolution);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){if(request.mutationRetryToken!==undefined&&resolution._tag==="Resolved"){const lifecycle3=yield*decodeMutationRetry(request.mutationRetryToken).pipe(flatMap3((retry5)=>retryOperatorSkillMutation(retry5,action2,input2,resolution)));return{action:action2,lifecycle:lifecycle3}}const lifecycle2=yield*action2==="install"?installOperatorSkill(input2,resolution):updateOperatorSkill(input2,resolution);return{action:action2,lifecycle:lifecycle2}}const lifecycle=request.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2,resolution):yield*decodeMigrationRetry(request.migrationRetryToken).pipe(flatMap3((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2,resolution)));return{action:action2,lifecycle}}))});var operatorSkillCompatibilityPolicy=Object.freeze({maximumExclusive:"6.0.0",minimum:"4.0.0"});var operatorSkillMetadataVersion="2.0.0";var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:input2.candidates[compatibleIndexes[0]]}};var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure={};for(const[key,nestedValue]of Object.entries(value5)){failure[key]=nestedValue}return Object.fromEntries(["_tag","exitCode","message","operation","reason","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){const omittedValue=undefined;return omittedValue}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var targetResolutionFailure=(resolution)=>{if(resolution._tag!=="UpstreamResolutionFailed"||resolution.failure===undefined){return{code:`operator-target-${resolution._tag}`,subject:operatorFact(resolution)}}const failureTag=typeof resolution.failure==="object"&&resolution.failure!==null&&"_tag"in resolution.failure?String(resolution.failure._tag):resolution._tag;return{code:`operator-target-${failureTag}`,subject:operatorFact(resolution.failure)}};var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.resolution);return{changes:[],degradations:[],issues:[{action:"status",code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}let nextActions;if(lifecycle.installed._tag==="Outdated"){nextActions=[{kind:"run",subject:"hi operator update"}]}else if(issues.length===0){nextActions=[{kind:"none"}]}else{nextActions=[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}]}return{changes,degradations:[],issues,nextActions,status:status2,warnings:lifecycle.installed._tag==="Outdated"?[{code:"operator-installed-outdated",subject:operatorFact(lifecycle.installed.effective)}]:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.before.resolution);return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){const failure=targetResolutionFailure(lifecycle.before.resolution);return{changes:[],degradations:[],issues:[{action:"migrate",code:failure.code,kind:"handled-failure",subject:failure.subject}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context3=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context3})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context3)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context3)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,mode="plain")=>gen2(function*runOperatorCommand(){const result4=yield*operation(action2,mode==="interactive"?"prompt":"automatic");if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;return yield*captureCommandResult(executeOperatorCommand(action2,operation,mode))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String4,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String4,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String4,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String4,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
307
307
 
308
- `));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption2=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption2,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path12 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String4,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var isRecord6=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:{...isRecord6(result4.machinePayload)?result4.machinePayload:{},operation:operationResult},operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path12.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json2,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json2||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path12.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({changes:operation.changes,degradations:operation.degradations,facts:operation.facts,issues:operation.issues,nextActions:operation.nextActions,status:operation.status,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(SelectedOutputMode.pipe(flatMap3((mode)=>executeOperatorCommand("migrate",undefined,mode)),map6(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path13 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String4,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path13.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path14 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check2,write:write2,yes,json:json2,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;if(check2&&(write2||yes)){return yield*new CliValidationError({message:"--check cannot be combined with --write or --yes."})}return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check2,emitJson:json2||selectedOutputMode==="json",refreshBaseline,rootDirectory:path14.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync5,realpathSync as realpathSync2}from"node:fs";var parseSemver=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u.exec(value5);if(match8===null){return null}return{major:Math.trunc(Number(match8[1])),minor:Math.trunc(Number(match8[2])),patch:Math.trunc(Number(match8[3])),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index=0;index<maxLength;index+=1){const candidatePart=candidateParts[index];const currentPart=currentParts[index];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&&currentIsNumeric){return Math.trunc(Number(candidatePart))>Math.trunc(Number(currentPart))?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>{controller.abort()},timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload==="object"&&payload!==null&&"version"in payload&&typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync5(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync2(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check2=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check2===null){return{check:check2,status:"unavailable"}}if(!check2.updateAvailable){return{check:check2,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check2,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check2,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check2=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check2===null){return{check:check2,status:"unavailable"}}if(!check2.updateAvailable&&!force){return{check:check2,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check2,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check2,command,environment,packageManager,status:"upgraded"}}return{check:check2,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path15 from"node:path";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_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),COLORFGBG:optional(String4),DP_SCRIPT_RUNTIME:optional(NonEmptyString),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(NumberFromString.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=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CODEX_HOME","DISPLAY","DP_SCRIPT_RUNTIME","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","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map6((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),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},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",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,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map6((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.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)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path15.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var safeEnvironmentKey=/^[A-Za-z_][A-Za-z0-9_]*$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var redactedEnvironmentValue="<redacted>";var redactCommandEnvironment=(environment)=>Object.fromEntries(Object.keys(environment).filter((key)=>safeEnvironmentKey.test(key)).map((key)=>[key,redactedEnvironmentValue]));var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=/\\+$/u.exec(value5)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}const safeCommandComponents=commandComponents.filter((component)=>component!==undefined);return`cmd.exe /d /v:off /s /c "${[...assignments,...safeCommandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:redactCommandEnvironment(result4.environment),kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}case"available":case"failed":case"manager-not-detected":case"unavailable":{return}default:{return result4}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:result4.packageManager===null?{}:minimumReleaseAgeEnvironmentForPackageManager(result4.packageManager),platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:async()=>await operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}const operationResult=upgradeOperationResult(result4);if(operationResult===undefined){return yield*fail6(new CliValidationError({message:"CLI upgrade failed."}))}return operationResult}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();function registration(command,commandMetadata,children=[]){return{children,command,metadata:commandMetadata}}var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(commitGateCommand,commitGateCommandMetadata,[registration(commitGateVerifyCommand,commitGateVerifyCommandMetadata)]),registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path16=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path16),command:node.command,metadata:commandMetadataFromDeclaration(path16,node.metadata)}});function buildRegisteredCommand(node){const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)}function buildCommandRegistry(rootCommand,registrations){const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}}var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync3}from"node:child_process";import{homedir as homedir2}from"node:os";var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");var clipboardWorkingDirectory=homedir2();var tryClipboardCommand=({command,args:args2,text:text3,runtime})=>{if(!runtime.commandExists(command)){return{ok:false}}try{runtime.execFile(command,args2,{cwd:clipboardWorkingDirectory,input:text3});return{command,ok:true}}catch{return{ok:false}}};var copyToClipboard=(text3,runtime)=>{const environment=runtime.env??{};if(!shouldUseClipboard(environment)){return{ok:false}}const commandRuntime={commandExists:runtime.commandExists??((command)=>commandExistsOnPath(command,environment)),execFile:runtime.execFile??((command,args2,options4)=>execFileSync3(command,[...args2],{cwd:options4.cwd,env:environment,input:options4.input,stdio:["pipe","ignore","ignore"]}))};const platform=runtime.platform??process.platform;if(platform==="darwin"){return tryClipboardCommand({args:[],command:"pbcopy",runtime:commandRuntime,text:text3})}if(platform==="win32"){return tryClipboardCommand({args:[],command:"clip",runtime:commandRuntime,text:text3})}const candidates=[{args:[],command:"wl-copy"},{args:["-selection","clipboard"],command:"xclip"},{args:["--clipboard","--input"],command:"xsel"}];for(const candidate of candidates){const result4=tryClipboardCommand({...candidate,runtime:commandRuntime,text:text3});if(result4.ok){return result4}}return{ok:false}};var makeScaffoldCapabilities=(runtime)=>({copyToClipboard:(text3,override={})=>copyToClipboard(text3,{...override,env:override.env??runtime.commandEnvironment}),ensureTools:(toolIds,baseline,override,options4)=>ensureToolsInstalledBestEffort(toolIds,baseline,override??makeToolCommandRuntime(runtime.commandEnvironment),options4),readSettings:readRepoSettings,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath});var scaffoldCapabilitiesLayer=effect(ScaffoldCapabilities,CliRuntimeConfig.pipe(map6(makeScaffoldCapabilities)));import{readFileSync as readFileSync6}from"node:fs";import path16 from"node:path";var isMissingFile=(cause)=>cause instanceof Error&&("code"in cause)&&cause.code==="ENOENT";var makeRepositoryCheckCapabilities=(runtime,projectSettings)=>({assessSettings:(rootDirectory)=>projectSettings.read(rootDirectory).pipe(map6(({settings,upgrade})=>({settings:{...settings.baselineVersion===undefined?{}:{baselineVersion:settings.baselineVersion},...settings.cliVersion===undefined?{}:{cliVersion:settings.cliVersion},commitGate:settings.commitGate??"enabled"},upgrade})),catchTag2("ProjectSettingsMissing",()=>succeed6(null)),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:"Failed to assess project settings.",operation:"assess-project-settings"}))),checkCli:(tag4)=>promise2(async()=>await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:tag4})),commitGateDesiredStateHash,isCommitGateApplicable,observeCommitGate,readCommitGateLifecycleReceipt:(rootDirectory)=>{try{const content=readFileSync6(path16.join(rootDirectory,commitGateLifecycleReceiptFile),"utf-8");return decodeCommitGateLifecycleReceipt(JSON.parse(content))}catch{return null}},readTextFile:(filePath)=>try_3({catch:(cause)=>new RepositoryCheckOperationFailure({cause,message:`Failed to read changelog: ${filePath}`,operation:"read-changelog"}),try:()=>readFileSync6(filePath,"utf-8")}).pipe(catchIf2((failure)=>isMissingFile(failure.cause),()=>succeed6(null)))});var repositoryCheckCapabilitiesLayer=effect(RepositoryCheckCapabilities,gen2(function*repositoryCheckCapabilitiesLayer2(){const runtime=yield*CliRuntimeConfig;const projectSettings=yield*ProjectSettings;return makeRepositoryCheckCapabilities(runtime,projectSettings)}));import{createHash as createHash5}from"node:crypto";import{execFileSync as execFileSync5}from"node:child_process";import{copyFileSync,existsSync as existsSync7,mkdirSync as mkdirSync4,mkdtempSync,readFileSync as readFileSync8,renameSync as renameSync2,rmSync,writeFileSync as writeFileSync4}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path18 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var BaselineChannel2=Literals(["stable","bundled"]);var BaselineSource2=Literals(["bundled","remote","local","control-plane"]);var SharedPromptCapability=Struct({path:Literal2("data/shared-agents.md"),sha256:String4.check(isPattern2(/^[0-9a-f]{64}$/u)),version:Literal2(1)});var SkillAuthoringContract=Struct({activationRevision:NonEmptyString,authoringRevision:NonEmptyString,id:NonEmptyString});var ScopedAuthoringCapability=Struct({revision:NonEmptyString,skills:ArraySchema(SkillAuthoringContract),version:Literal2(1)});var BaselineCapabilities=Struct({scopedAuthoring:optionalKey2(ScopedAuthoringCapability),sharedPrompt:optionalKey2(SharedPromptCapability)});var ArtifactObligation=Struct({contentAuthority:Literals(["scaffold","repository","mixed","unknown"]),dependencies:ArraySchema(NonEmptyString),presence:Literals(["required","optional"]),producer:NonEmptyString,validity:Literals(["managed-bytes","authored-content","structured-entries"])});var SharedPromptIdentity=Struct({baselineDigest:NonEmptyString,baselineVersion:NonEmptyString,capabilityVersion:Literal2(1),templateDigest:NonEmptyString});var ScaffoldArtifactKind=Literals(["manifest","archive"]);class ScaffoldArtifactMetadata extends Class4("ScaffoldArtifactMetadata")(orderedSchemaFields(["kind",ScaffoldArtifactKind],["fileName",String4],["contentType",String4],["url",String4],["sha256",String4],["sizeBytes",optional(Number6)])){}var ScaffoldManagedFileKind=Literals(["agent-prompt","context-plan","handoff","harness","hook","lint-spec","manifest","prompt-spec","projection-receipt","required-tools","script","skill","source-guide","subagent"]);var Sha256Digest=String4.check(isPattern2(/^[0-9a-f]{64}$/u));var FileMode=Number6.check(isInt(),isGreaterThanOrEqualTo3(0),isLessThanOrEqualTo4(511));var ManagedFileFingerprint=TaggedUnion({File:{mode:FileMode,sha256:Sha256Digest},Symlink:{sha256:Sha256Digest,target:NonEmptyString}});var ProjectGeneratedAuthority=TaggedUnion({RepositoryMirror:{sourcePath:NonEmptyString}});var ProjectGeneratedOwnership=Struct(orderedSchemaFields(["producer",NonEmptyString],["revision",optionalKey2(NonEmptyString)],["authority",ProjectGeneratedAuthority],["outputFingerprint",ManagedFileFingerprint]));var ManagedFileOwnership=TaggedUnion({ProjectGenerated:{evidence:ProjectGeneratedOwnership},ScaffoldManaged:{}});var scaffoldManagedOwnership=ManagedFileOwnership.cases.ScaffoldManaged.make({});class ScaffoldManagedFileSummary extends Class4("ScaffoldManagedFileSummary")(orderedSchemaFields(["path",String4],["sha256",String4],["kind",ScaffoldManagedFileKind],["obligation",optionalKey2(ArtifactObligation)],["sharedPromptIdentity",optionalKey2(SharedPromptIdentity)],["ownership",optionalKey2(ManagedFileOwnership).pipe(decodeTo2(ManagedFileOwnership,{decode:withDefault(succeed6(scaffoldManagedOwnership)),encode:transformOptional(filter((ownership)=>ownership._tag!=="ScaffoldManaged"))}),withConstructorDefault2(succeed6(scaffoldManagedOwnership)))])){}class ScaffoldProvenance extends Class4("ScaffoldProvenance")(orderedSchemaFields(["source",BaselineSource2],["channel",BaselineChannel2],["version",String4],["tag",optional(NullOr(String4))],["commit",optional(NullOr(String4))],["sha256",optional(NullOr(String4))])){}class ScaffoldBaselineManifest extends Class4("ScaffoldBaselineManifest")(orderedSchemaFields(["channel",BaselineChannel2],["version",String4],["tag",optional(NullOr(String4))],["commit",optional(NullOr(String4))],["sha256",optional(NullOr(String4))])){}var CliVersionRange=String4.check(isTrimmed(),isNonEmpty());var EmbeddedBaselineFields=[["capabilities",optionalKey2(BaselineCapabilities)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["sha256",optionalKey2(NullOr(NonEmptyString))],["generatedAt",optionalKey2(NonEmptyString)]];var EmbeddedScaffoldBaselineMetadataV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],...EmbeddedBaselineFields,["compatibility",optionalKey2(Struct({cliVersionRange:CliVersionRange}))]));var EmbeddedScaffoldBaselineMetadataV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],...EmbeddedBaselineFields,["compatibility",Struct({cliVersionRange:CliVersionRange})]));var EmbeddedScaffoldBaselineMetadata=Union2([EmbeddedScaffoldBaselineMetadataV1,EmbeddedScaffoldBaselineMetadataV2]);var PublishedScaffoldBaselineManifestV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString]));var PublishedScaffoldBaselineManifestV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString],["compatibility",Struct({cliVersionRange:CliVersionRange})]));var PublishedScaffoldBaselineManifest=Union2([PublishedScaffoldBaselineManifestV1,PublishedScaffoldBaselineManifestV2]);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 versionPattern=new RegExp(String.raw`^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?$`,"u");var constraintPattern=new RegExp(String.raw`^(?<operator>>=|<=|>|<|=)?(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?)?)?$`,"u");var numericIdentifierPattern=/^\d+$/u;var parseVersion=(value5)=>{const groups=versionPattern.exec(value5)?.groups;return groups===undefined?null:[Number(groups.major),Number(groups.minor),Number(groups.patch),groups.prerelease?.split(".")??[]]};var comparePrereleaseIdentifiers=(left,right)=>{const leftNumeric=numericIdentifierPattern.test(left);const rightNumeric=numericIdentifierPattern.test(right);if(leftNumeric&&rightNumeric){if(BigInt(left)<BigInt(right)){return-1}return BigInt(left)>BigInt(right)?1:0}if(leftNumeric!==rightNumeric){return leftNumeric?-1:1}if(left<right){return-1}return left>right?1:0};var comparePrereleases=(left,right)=>{if(left.length===0||right.length===0){if(left.length===right.length){return 0}return left.length===0?1:-1}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){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}const compared=comparePrereleaseIdentifiers(leftIdentifier,rightIdentifier);if(compared!==0){return compared}}return 0};var compareCoreVersions=(left,right)=>left[0]-right[0]||left[1]-right[1]||left[2]-right[2];var compareVersions2=(left,right)=>compareCoreVersions(left,right)||comparePrereleases(left[3],right[3]);var nextPartialVersion=(version3,precision)=>precision===1?[version3[0]+1,0,0,[]]:[version3[0],version3[1]+1,0,[]];var constraintPrecision=(groups)=>{if(groups.patch!==undefined){return 3}return groups.minor===undefined?1:2};var parseCompatibilityRange=(range2)=>{const normalized=range2.trim();if(normalized==="*"){return[]}return normalized.split(/\s+/u).map((constraint)=>{const groups=constraintPattern.exec(constraint)?.groups;if(groups===undefined){return null}return{operator:groups.operator??"=",precision:constraintPrecision(groups),target:[Number(groups.major),Number(groups.minor??0),Number(groups.patch??0),groups.prerelease?.split(".")??[]]}})};var satisfiesCliCompatibilityRange=(range2,version3)=>{if(range2.trim()==="*"){return true}const constraints=parseCompatibilityRange(range2);const current=parseVersion(version3);if(current===null||constraints.some((constraint)=>constraint===null)){return false}return constraints.every(({operator,precision,target})=>{const compare=precision===3?compareVersions2:compareCoreVersions;const compared=compare(current,target);const next=precision===3?undefined:nextPartialVersion(target,precision);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}}})};import{existsSync as existsSync6,readFileSync as readFileSync7}from"node:fs";import path17 from"node:path";function readJson(filePath){const value5=JSON.parse(readFileSync7(filePath,"utf-8"));return value5}var validateBaselineAssets=({root,skills,skillIdAliases})=>{for(const skill of skills){if(!existsSync6(path17.join(root,skill.sourceDirectory))){throw new Error(`Baseline skill asset missing: ${skill.sourceDirectory}`)}}for(const alias of skillIdAliases??[]){if(alias.compatibilitySourceDirectory!==undefined&&!existsSync6(path17.join(root,alias.compatibilitySourceDirectory))){throw new Error(`Baseline skill compatibility asset missing: ${alias.compatibilitySourceDirectory}`)}}};var loadBaselineFromDirectory=(root,verifiedSummary)=>{const metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(readJson(path17.join(root,"baseline.json")));if(metadata.version!==verifiedSummary.resolvedVersion){throw new Error("Baseline metadata does not match the verified version.")}const dataRoot2=path17.join(root,"data");const aliasesPath=path17.join(dataRoot2,"catalog","skill-id-aliases.json");const aliases=existsSync6(aliasesPath)?readJson(aliasesPath):[];const skills=stripSkillIdCompatibilityProjectionRows(readJson(path17.join(dataRoot2,"catalog","skills.json")),aliases);const skillIdAliases=validateSkillIdAliases(aliases,skills);const baseline={...metadata.capabilities===undefined?{}:{capabilities:metadata.capabilities},dataRoot:dataRoot2,hooks:readJson(path17.join(dataRoot2,"catalog","hooks.json")),lintAssets:validateLintCatalog(readJson(path17.join(dataRoot2,"catalog","lint-assets.json"))),packs:readJson(path17.join(dataRoot2,"catalog","packs.json")),root,skillIdAliases,skills,skillsRoot:path17.join(root,"skills"),summary:verifiedSummary,tools:readJson(path17.join(dataRoot2,"catalog","tools.json"))};validateBaselineAssets(baseline);return baseline};var defaultMessage3=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BackofficeAccessRole=Literals(["admin","member"]);var BackofficeAccessStatus=Literals(["invited","active","revoked"]);var BackofficeAccessSummary=Struct({email:String4,role:BackofficeAccessRole,status:BackofficeAccessStatus,userId:optionalKey2(String4),invitedBy:optionalKey2(String4),revokedBy:optionalKey2(String4),invitedAt:optionalKey2(String4),activatedAt:optionalKey2(String4),revokedAt:optionalKey2(String4),createdAt:String4,updatedAt:String4}).annotate({identifier:"BackofficeAccessSummary"});var BackofficeAccessList=Struct({users:ArraySchema(BackofficeAccessSummary)}).annotate({identifier:"BackofficeAccessList"});var BackofficeAccessInviteRequest=Struct({email:String4,role:BackofficeAccessRole}).annotate({identifier:"BackofficeAccessInviteRequest"});var BackofficeOperatorSummary=Struct({operatorId:optionalKey2(String4),email:optionalKey2(String4),name:optionalKey2(String4)}).annotate({identifier:"BackofficeOperatorSummary"});var ObservedRepositorySummary=Struct({id:String4,projectUsageId:String4,remoteHost:optionalKey2(String4),remotePath:optionalKey2(String4),remoteUrl:optionalKey2(String4),branch:optionalKey2(String4),lastCommitSha:optionalKey2(String4),dirty:optionalKey2(Boolean3),gitIdentity:optionalKey2(GitIdentity),firstSeenAt:optionalKey2(IsoDateTimeString),lastSeenAt:optionalKey2(IsoDateTimeString)}).annotate({identifier:"ObservedRepositorySummary"});var ProjectUsageEventSummary=Struct({id:String4,eventId:String4,name:String4,source:String4,counted:Boolean3,cliVersion:String4,baseline:optionalKey2(Struct({channel:optionalKey2(String4),version:optionalKey2(String4)})),occurredAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageEventSummary"});var HarnessReportSummary=Struct({id:String4,projectUsageId:optionalKey2(String4),observedRepositoryId:optionalKey2(String4),title:String4,body:optionalKey2(String4),type:String4,severity:String4,status:String4,githubUrl:optionalKey2(String4),createdAt:IsoDateTimeString,updatedAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"HarnessReportSummary"});var ProjectUsageSummary=Struct({id:String4,name:optionalKey2(String4),repositoryCount:Finite,countedEventCount:Finite,openReportCount:Finite,latestCliVersion:optionalKey2(String4),latestBaselineChannel:optionalKey2(String4),latestBaselineVersion:optionalKey2(String4),lastActivityAt:optionalKey2(IsoDateTimeString),initializedBy:optionalKey2(BackofficeOperatorSummary),lastUpdatedBy:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageSummary"});var ProjectUsageList=Struct({projects:ArraySchema(ProjectUsageSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageList"});var ProjectUsageDetail=Struct({project:ProjectUsageSummary,repositories:ArraySchema(ObservedRepositorySummary),events:ArraySchema(ProjectUsageEventSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageDetail"});var BackofficeRepositoryMappingRequest=Struct({observedRepositoryId:String4}).annotate({identifier:"BackofficeRepositoryMappingRequest"});var BackofficeReportUpdateRequest=Struct({status:optionalKey2(HarnessReportStatus),githubUrl:optionalKey2(NullOr(String4))}).annotate({identifier:"BackofficeReportUpdateRequest"});class Unauthorized extends TaggedErrorClass()("@punks/contract/errors/Unauthorized",{message:defaultMessage3("Backoffice session is required.")},{httpApiStatus:401,title:"Unauthorized"}){}class BackofficeRequestRejected extends TaggedErrorClass()("@punks/contract/errors/BackofficeRequestRejected",{message:String4},{httpApiStatus:400,title:"Backoffice Request Rejected"}){}class BackofficePersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficePersistenceUnavailable",{message:defaultMessage3("Backoffice persistence is unavailable.")},{httpApiStatus:503,title:"Backoffice Persistence Unavailable"}){}class BackofficeDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficeDependencyUnavailable",{message:defaultMessage3("Backoffice dependency is unavailable.")},{httpApiStatus:503,title:"Backoffice Dependency Unavailable"}){}var listErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficePersistenceUnavailable];var rejectedErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficeRequestRejected,BackofficePersistenceUnavailable];var projectUsageListErrors=[...listErrors,BackofficeDependencyUnavailable];var projectUsageDetailErrors=[...rejectedErrors,BackofficeDependencyUnavailable];var BackofficeApi=exports_HttpApiGroup.make("backoffice").add(exports_HttpApiEndpoint.get("currentAccess","/access/current",{success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("accessList","/access-users",{success:BackofficeAccessList,error:listErrors}),exports_HttpApiEndpoint.post("inviteAccess","/access-users",{payload:BackofficeAccessInviteRequest,success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.post("revokeAccess","/access-users/:email/revoke",{params:{email:String4},success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("projectUsageList","/project-usages",{success:ProjectUsageList,error:projectUsageListErrors}),exports_HttpApiEndpoint.get("projectUsageDetail","/project-usages/:projectUsageId",{params:{projectUsageId:String4},success:ProjectUsageDetail,error:projectUsageDetailErrors}),exports_HttpApiEndpoint.post("mapRepository","/project-usages/:projectUsageId/repositories",{params:{projectUsageId:String4},payload:BackofficeRepositoryMappingRequest,success:ObservedRepositorySummary,error:rejectedErrors}),exports_HttpApiEndpoint.patch("updateReport","/reports/:reportId",{params:{reportId:String4},payload:BackofficeReportUpdateRequest,success:HarnessReportSummary,error:rejectedErrors})).prefix("/backoffice").annotateMerge(exports_OpenApi.annotations({title:"Backoffice project usage"}));var defaultMessage4=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var HarnessReportType=Literals(["bug","docs","workflow","tooling","other"]);var HarnessReportSeverity=Literals(["low","medium","high"]);var HarnessReportLabel=String4.check(isTrimmed(),isNonEmpty(),isMaxLength(50));var HarnessReportLabels=ArraySchema(HarnessReportLabel).check(isMaxLength(10));var HarnessReportInput=Struct({title:optionalKey2(String4),body:optionalKey2(String4),type:HarnessReportType,severity:HarnessReportSeverity,createdAt:IsoDateTimeString,cliVersion:String4,area:optionalKey2(String4),skillPack:optionalKey2(String4),command:optionalKey2(String4),expected:optionalKey2(String4),actual:optionalKey2(String4),steps:optionalKey2(String4),labels:optionalKey2(HarnessReportLabels),projectUsageId:optionalKey2(String4),repository:optionalKey2(ObservedRepositoryInput),githubUrl:optionalKey2(String4)}).annotate({identifier:"HarnessReportInput"});var HarnessReportCreated=Struct({reportId:String4,status:HarnessReportStatus,githubUrl:optionalKey2(String4),title:optionalKey2(String4),deduplicated:optionalKey2(Boolean3),duplicateOf:optionalKey2(String4)}).annotate({identifier:"HarnessReportCreated"});class HarnessReportRejected extends TaggedErrorClass()("@punks/contract/errors/HarnessReportRejected",{message:String4},{httpApiStatus:400,title:"Harness Report Rejected"}){}class HarnessReportPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportPersistenceUnavailable",{message:defaultMessage4("Harness report persistence is unavailable.")},{httpApiStatus:503,title:"Harness Report Persistence Unavailable"}){}class HarnessReportDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportDependencyUnavailable",{message:defaultMessage4("Harness report submission dependency is unavailable.")},{httpApiStatus:503,title:"Harness Report Dependency Unavailable"}){}var ReportsApi=exports_HttpApiGroup.make("reports").add(exports_HttpApiEndpoint.post("submit","/",{payload:HarnessReportInput,success:HarnessReportCreated,error:[HttpApiDecodeError,Forbidden2,HarnessReportRejected,HarnessReportDependencyUnavailable,HarnessReportPersistenceUnavailable]})).prefix("/reports").annotateMerge(exports_OpenApi.annotations({title:"Harness reports"}));var defaultMessage5=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ProductTelemetryEventName=Literals(["cli.artifact.pull.completed","cli.scaffold.init.completed","cli.scaffold.setup.completed","cli.scaffold.update.applied","cli.harness.report.submitted"]);var TelemetrySource=Literals(["normal","local-dev","ci","debug","test"]);var TelemetryBaselineContext=Struct({channel:optionalKey2(BaselineChannel),version:optionalKey2(String4)}).annotate({identifier:"TelemetryBaselineContext"});var ProductTelemetryEventInput=Struct({eventId:String4,name:ProductTelemetryEventName,occurredAt:IsoDateTimeString,cliVersion:String4,source:TelemetrySource,projectUsageId:optionalKey2(String4),repository:optionalKey2(ObservedRepositoryInput),baseline:optionalKey2(TelemetryBaselineContext)}).annotate({identifier:"ProductTelemetryEventInput"});var ProductTelemetryEventAccepted=Struct({eventId:String4,accepted:Boolean3,counted:Boolean3}).annotate({identifier:"ProductTelemetryEventAccepted"});class TelemetryEventRejected extends TaggedErrorClass()("@punks/contract/errors/TelemetryEventRejected",{message:String4},{httpApiStatus:400,title:"Telemetry Event Rejected"}){}class TelemetryPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/TelemetryPersistenceUnavailable",{message:defaultMessage5("Telemetry persistence is unavailable.")},{httpApiStatus:503,title:"Telemetry Persistence Unavailable"}){}var TelemetryApi=exports_HttpApiGroup.make("telemetry").add(exports_HttpApiEndpoint.post("record","/events",{payload:ProductTelemetryEventInput,success:ProductTelemetryEventAccepted,error:[HttpApiDecodeError,Forbidden2,TelemetryEventRejected,TelemetryPersistenceUnavailable]})).prefix("/telemetry").annotateMerge(exports_OpenApi.annotations({title:"Product telemetry"}));var HealthApi=exports_HttpApiGroup.make("health",{topLevel:true}).add(exports_HttpApiEndpoint.get("healthz","/healthz",{success:exports_HttpApiSchema.NoContent.annotate({description:"Empty health response"}),error:[HttpApiDecodeError,Forbidden2]}));var HarnessApi=exports_HttpApi.make("harness").add(HealthApi,BaselineApi,TelemetryApi,ReportsApi,BackofficeApi).prefix("/api").annotateMerge(exports_OpenApi.annotations({title:"Harness Intelligence Control Plane",summary:"Shared typed contract for Devpunks CLI/backend control-plane calls."}));var ControlPlaneOperation=Literals(["record-product-telemetry","resolve-stable-baseline","submit-harness-report"]);class ControlPlaneRequestFailure extends TaggedErrorClass()("@punks/cli/control-plane/ControlPlaneRequestFailure",{cause:Defect(),operation:ControlPlaneOperation,transport:Boolean3}){}var isHttpTransportFailure=(cause)=>isHttpClientError(cause)&&cause.reason._tag==="TransportError";var normalizeControlPlaneFailure=(operation,effect2)=>effect2.pipe(catchIf2((cause)=>isHttpClientError(cause)||isSchemaError(cause),(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation,transport:isHttpTransportFailure(cause)}))));var makeControlPlaneClient=({baseUrl:baseUrl2,headers})=>exports_HttpApiClient.make(HarnessApi,{baseUrl:baseUrl2,...headers===undefined?{}:{transformClient:(client)=>client.pipe(exports_HttpClient.mapRequest(exports_HttpClientRequest.setHeaders(headers)))}});var resolveBaselineMetadata=(options4)=>normalizeControlPlaneFailure("resolve-stable-baseline",gen2(function*requestBaselineMetadata(){const client=yield*makeControlPlaneClient(options4);return yield*client.baseline.resolve({params:{channel:options4.request.channel},query:options4.request.version===undefined?{}:{version:options4.request.version}})}));var recordProductTelemetryEvent=(options4)=>normalizeControlPlaneFailure("record-product-telemetry",gen2(function*sendProductTelemetryEvent(){const client=yield*makeControlPlaneClient(options4);return yield*client.telemetry.record({payload:options4.event})}));var submitHarnessReport=(options4)=>normalizeControlPlaneFailure("submit-harness-report",gen2(function*sendHarnessReport(){const client=yield*makeControlPlaneClient(options4);return yield*client.reports.submit({payload:options4.report})}));var BundledControlPlaneConfig=Struct({defaultUrl:optional(Unknown2)});var trimTrailingSlashes=(value5)=>value5.trim().replace(/\/+$/u,"");var bundledControlPlaneUrl=({disableBundledUrl=false}={})=>{if(disableBundledUrl){return}const config=decodeUnknownSync(BundledControlPlaneConfig)(JSON.parse(readDataFile("control-plane.json")));return typeof config.defaultUrl==="string"&&config.defaultUrl.trim().length>0?trimTrailingSlashes(config.defaultUrl):undefined};var resolveControlPlaneUrl=(explicitUrl,configuration={})=>{const baseUrl2=explicitUrl?.trim()??configuration.baseUrl?.trim()??bundledControlPlaneUrl(configuration);return baseUrl2===undefined||baseUrl2.length===0?undefined:trimTrailingSlashes(baseUrl2)};class BaselineResolutionFailure extends TaggedErrorClass()("@punks/cli/baseline-resolution/BaselineResolutionFailure",{cause:Defect(),message:String4,operation:Literal2("resolve-stable-baseline"),reason:Literals(["corrupt-artifact","remote-access","unsafe-artifact","invalid-artifact"])}){}import{randomUUID}from"node:crypto";import{execFileSync as execFileSync4}from"node:child_process";var disabledTelemetryConfig={disableBundledUrl:true};var git=(cwd,args2)=>{try{return execFileSync4("git",args2,{cwd,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};var redactRemote=(remote)=>remote.replace(/\/\/[^/@]+@/u,"//");var safeRemoteParts=(remote)=>{const redacted4=redactRemote(remote);const ssh=/^git@(?<host>[^:]+):(?<path>.+)$/u.exec(redacted4);const sshGroups=ssh?.groups;if(sshGroups!==undefined){return{remoteHost:sshGroups.host,remotePath:sshGroups.path.replace(/\.git$/u,""),remoteUrl:redacted4}}try{const url=new URL(redacted4);return{remoteHost:url.hostname,remotePath:url.pathname.replaceAll(/^\/|\.git$/gu,""),remoteUrl:redacted4}}catch{return{remoteUrl:redacted4}}};var observedRepository=(cwd)=>{const remote=git(cwd,["config","--get","remote.origin.url"]);const commitSha=git(cwd,["rev-parse","HEAD"])??undefined;const status2=git(cwd,["status","--short"]);const name2=git(cwd,["config","--local","--get","user.name"])??undefined;const email=git(cwd,["config","--local","--get","user.email"])??undefined;return{...remote===null?{}:safeRemoteParts(remote),...commitSha===undefined?{}:{commitSha},...status2===null?{}:{dirty:status2.length>0},...name2===undefined&&email===undefined?{}:{gitIdentity:{...name2===undefined?{}:{name:name2},...email===undefined?{}:{email}}}}};var isLocalControlPlaneUrl=(value5)=>{if(value5===undefined||value5.trim().length===0){return false}try{const{hostname}=new URL(value5);return hostname==="localhost"||hostname.endsWith(".localhost")||hostname.startsWith("127.")||hostname==="0.0.0.0"||hostname==="::1"||hostname==="[::1]"}catch{return value5.includes("localhost")||value5.includes(".localhost")}};var telemetrySource=(configuration={})=>{if(configuration.telemetrySource==="ci"){return"ci"}if(configuration.telemetrySource==="debug"){return"debug"}if(configuration.telemetrySource==="test"){return"test"}if(isLocalControlPlaneUrl(configuration.baseUrl)){return"local-dev"}return"normal"};var makeProductTelemetryEvent=({name:name2,cwd,baseline,controlPlaneUrl,configuration})=>{const repository=observedRepository(cwd);return{cliVersion:version2,eventId:randomUUID(),name:name2,occurredAt:new Date().toISOString(),...repository===undefined?{}:{repository},source:telemetrySource(configuration??(controlPlaneUrl===undefined?{}:{baseUrl:controlPlaneUrl})),...baseline===undefined?{}:{baseline}}};var telemetryBaseUrl=(controlPlaneUrl,configuration=disabledTelemetryConfig)=>resolveControlPlaneUrl(controlPlaneUrl,configuration);var submitProductTelemetryEffect=(event,options4={})=>{const baseUrl2=telemetryBaseUrl(options4.controlPlaneUrl,options4.configuration);if(baseUrl2===undefined){return void_3}return recordProductTelemetryEvent({baseUrl:baseUrl2,event}).pipe(catchTags2({"@punks/cli/control-plane/ControlPlaneRequestFailure":()=>void_3,"@punks/contract/errors/Forbidden":()=>void_3,"@punks/contract/errors/TelemetryEventRejected":()=>void_3,"@punks/contract/errors/TelemetryPersistenceUnavailable":()=>void_3,HttpApiDecodeError:()=>void_3}),asVoid2)};var telemetryTransportEnabled=(controlPlaneUrl,configuration)=>telemetryBaseUrl(controlPlaneUrl,configuration)!==undefined;var makeCliEvent=(name2,options4={})=>makeProductTelemetryEvent({cwd:options4.cwd??process.cwd(),name:name2,...options4.baseline===undefined?{}:{baseline:options4.baseline},...options4.controlPlaneUrl===undefined?{}:{controlPlaneUrl:options4.controlPlaneUrl},...options4.configuration===undefined?{}:{configuration:options4.configuration}});var submitCliEventEffect=(name2,options4={})=>telemetryTransportEnabled(options4.controlPlaneUrl,options4.configuration)?submitProductTelemetryEffect(makeCliEvent(name2,options4),options4):void_3;var assetArchiveName="scaffold-baseline.tgz";var cachedArtifactName=".verified-artifact.tgz";var maximumArchiveRedirects=20;var defaultRemoteBaselineTimeoutMs=5000;var archiveRedirectStatuses=new Set([301,302,303,307,308]);var bundledFallbackAvailability=new Set(["authority-unconfigured","network","unavailable-status"]);var BaselineArchiveEndpointFailure=Union2([BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable]);var isBaselineReleaseTag=(tag4)=>tag4.startsWith("baseline/stable/")&&!/^v\d+\.\d+\.\d+(?:$|-)/u.test(tag4);var normalizeBaselineRequest=(value5)=>{const requested=value5?.trim();if(requested===undefined||requested.length===0||requested==="stable"){return{channel:"stable"}}return requested==="bundled"?{channel:"bundled"}:{channel:"stable",version:requested}};var sha256File=(filePath)=>createHash5("sha256").update(readFileSync8(filePath)).digest("hex");var isSafeTarPath=(entry)=>entry.length>0&&!path18.isAbsolute(entry)&&!entry.split("/").includes("..");var isSafePathSegment=(value5)=>value5.length>0&&value5!=="."&&value5!==".."&&!value5.includes("/")&&!value5.includes("\\");var integrityFailure=(resolution,message,actualDigest)=>new BaselineIntegrityFailure({...actualDigest===undefined?{}:{actualDigest},expectedDigest:resolution.digest,message,request:resolution.requested,resolvedVersion:resolution.resolvedVersion});var verifyEmbeddedBaselineMetadata=(root,resolution,retrieval)=>{let metadata;try{metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync8(path18.join(root,"baseline.json"),"utf-8")))}catch{throw integrityFailure(resolution,`${retrieval} baseline metadata is invalid.`)}if(metadata.channel!==resolution.requested.channel||metadata.version!==resolution.resolvedVersion||resolution.provenance!==`release:${resolution.resolvedVersion}`||metadata.tag!==`baseline/stable/${resolution.resolvedVersion}`||metadata.sha256!==undefined&&metadata.sha256!==null&&metadata.sha256!==resolution.digest||metadata.compatibility!==undefined&&metadata.compatibility.cliVersionRange!==resolution.compatibility.cliVersionRange){throw integrityFailure(resolution,`${retrieval} baseline metadata disagrees with selected authority.`)}};class BaselineArchiveUnavailableError extends Error{name="BaselineArchiveUnavailableError"}var baselineFailureMessage=(cause)=>{if(cause instanceof ControlPlaneRequestFailure||isTimeoutError2(cause)){return"The baseline authority request failed."}if(cause instanceof Error&&typeof cause.message==="string"&&cause.message.trim().length>0){return cause.message}return"Baseline resolution failed."};var parseArchiveUrl=(value5)=>{let url;try{url=new URL(value5)}catch{throw new Error("Authority returned an invalid baseline archive URL.")}if(url.protocol!=="http:"&&url.protocol!=="https:"){throw new Error("Authority returned an invalid baseline archive URL.")}return url};var fetchArchiveResponse=async(url,signal,redirects=0)=>{const response=await fetch(url,{redirect:"manual",signal}).catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to download baseline artifact.",{cause:error2})});if(!archiveRedirectStatuses.has(response.status)){return response}const location2=response.headers.get("location");if(location2===null||redirects>=maximumArchiveRedirects){throw new Error("Authority returned an invalid baseline archive URL.")}const redirectedUrl=parseArchiveUrl(location2).toString();return await fetchArchiveResponse(redirectedUrl,signal,redirects+1)};var decodeArchiveEndpointFailure=async(response)=>{const body=await response.json().catch(()=>null);if(body===null){return}try{return decodeUnknownSync(BaselineArchiveEndpointFailure)(body)}catch{return}};var bundledFallbackEligible=(cause)=>cause instanceof BaselineArchiveUnavailableError||isTimeoutError2(cause)||cause instanceof BaselineUnavailable&&bundledFallbackAvailability.has(cause.availability)||cause instanceof ControlPlaneRequestFailure&&cause.transport;var classifyFailure=(cause)=>{let reason="invalid-artifact";if(cause instanceof BaselineIntegrityFailure){reason="corrupt-artifact"}else if(bundledFallbackEligible(cause)){reason="remote-access"}return new BaselineResolutionFailure({cause,message:baselineFailureMessage(cause),operation:"resolve-stable-baseline",reason})};var extractSafeTgz=(archivePath,targetDirectory)=>{const entries=execFileSync5("tar",["-tzf",archivePath],{encoding:"utf-8"}).split(/\r?\n/u).filter(Boolean);const unsafe=entries.find((entry)=>!isSafeTarPath(entry));if(unsafe!==undefined){throw new Error(`Unsafe path in baseline archive: ${unsafe}`)}mkdirSync4(targetDirectory,{recursive:true});execFileSync5("tar",["-xzf",archivePath,"-C",targetDirectory],{stdio:"ignore"})};var download=async(url,targetPath,timeoutMs)=>{const controller=new AbortController;const timeout3=setTimeout(()=>{controller.abort()},timeoutMs);try{const response=await fetchArchiveResponse(parseArchiveUrl(url).toString(),controller.signal);if(!response.ok){const endpointFailure=await decodeArchiveEndpointFailure(response);if(endpointFailure!==undefined){if(endpointFailure instanceof BaselineUnavailable&&response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw endpointFailure}if(response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw new BaselineArchiveUnavailableError(`Failed to download baseline artifact: ${response.status}`)}const bytes=await response.arrayBuffer().catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to read baseline artifact response.",{cause:error2})});writeFileSync4(targetPath,new Uint8Array(bytes))}finally{clearTimeout(timeout3)}};var summaryMetadata=(resolution,retrieval)=>({authoritySource:resolution.source,channel:resolution.requested.channel,commit:null,compatibility:resolution.compatibility,digest:resolution.digest,provenance:resolution.provenance,requested:resolution.requested,resolvedVersion:resolution.resolvedVersion,retrieval,sha256:resolution.digest,source:"remote",tag:isBaselineReleaseTag(resolution.provenance)?resolution.provenance:null,version:resolution.resolvedVersion});var decodeLocalCompatibility=(metadata)=>{if(!Object.hasOwn(metadata,"compatibility")){return"*"}const{compatibility}=metadata;if(typeof compatibility!=="object"||compatibility===null||!("cliVersionRange"in compatibility)){throw new Error("Local baseline metadata has invalid CLI compatibility.")}const{cliVersionRange}=compatibility;if(typeof cliVersionRange!=="string"||cliVersionRange.trim().length===0){throw new Error("Local baseline metadata has invalid CLI compatibility.")}return cliVersionRange};var resolveLocalBaseline=(url,request)=>{if(!url.startsWith("file://")){return null}const root=fileURLToPath2(new URL(url));const metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync8(path18.join(root,"baseline.json"),"utf-8")));if(typeof metadata.version!=="string"||metadata.version.length===0){throw new Error("Local baseline metadata has no version.")}const cliVersionRange=decodeLocalCompatibility(metadata);if(metadata.tag!==undefined&&metadata.tag!==null&&typeof metadata.tag!=="string"){throw new Error("Local baseline metadata has an invalid tag.")}if(metadata.commit!==undefined&&metadata.commit!==null&&typeof metadata.commit!=="string"){throw new Error("Local baseline metadata has an invalid commit.")}const tag4=metadata.tag??null;const commit=metadata.commit??null;const digest3=digestContentRoots([{prefix:"baseline",root}]);if(request.version!==undefined&&request.version!==metadata.version){throw new BaselineIntegrityFailure({expectedDigest:digest3,message:"Local baseline metadata does not match the exact requested version.",request,resolvedVersion:metadata.version})}if(!satisfiesCliCompatibilityRange(cliVersionRange,version2)){throw new BaselineIntegrityFailure({expectedDigest:digest3,message:`Local baseline requires CLI ${cliVersionRange}; current CLI is ${version2}.`,request,resolvedVersion:metadata.version})}return loadBaselineFromDirectory(root,{authoritySource:"local",channel:request.channel,commit,compatibility:{cliVersionRange},digest:digest3,provenance:tag4??"local-file",requested:request,resolvedVersion:metadata.version,retrieval:"available",sha256:digest3,source:"local",tag:tag4,version:metadata.version})};var loadExactCachedBaseline=(targetDirectory,resolution)=>{if(!existsSync7(targetDirectory)){return{baseline:null}}try{if(!existsSync7(path18.join(targetDirectory,"baseline.json"))){throw integrityFailure(resolution,"Cached baseline is incomplete.")}const artifactPath=path18.join(targetDirectory,cachedArtifactName);if(!existsSync7(artifactPath)||sha256File(artifactPath)!==resolution.digest){throw integrityFailure(resolution,"Cached artifact does not match authority.")}const verificationDirectory=mkdtempSync(path18.join(tmpdir4(),"punks-cache-verify-"));try{extractSafeTgz(artifactPath,verificationDirectory);const expected=digestContentRoots([{prefix:"baseline",root:verificationDirectory}]);const actual=digestContentRoots([{include:(relativePath)=>relativePath!==cachedArtifactName,prefix:"baseline",root:targetDirectory}]);if(actual!==expected){throw integrityFailure(resolution,"Cached baseline content changed.")}verifyEmbeddedBaselineMetadata(targetDirectory,resolution,"Cached")}finally{rmSync(verificationDirectory,{force:true,recursive:true})}return{baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"cached"))}}catch(error2){rmSync(targetDirectory,{force:true,recursive:true});return{baseline:null,integrityFailure:error2 instanceof BaselineIntegrityFailure?error2:integrityFailure(resolution,"Cached baseline failed integrity verification.")}}};var materializeBaseline=async(resolution,refresh,timeoutMs,cacheDirectory)=>{if(resolution.source!=="control-plane"){throw integrityFailure(resolution,"Baseline authority source must be control-plane.")}if(!isSafePathSegment(resolution.resolvedVersion)){throw integrityFailure(resolution,"Authority returned an unsafe baseline version.")}parseArchiveUrl(resolution.archive.url);if(!satisfiesCliCompatibilityRange(resolution.compatibility.cliVersionRange,version2)){throw integrityFailure(resolution,`Baseline requires CLI ${resolution.compatibility.cliVersionRange}; current CLI is ${version2}.`)}const targetDirectory=path18.join(cacheDirectory,"devpunks","baselines","verified",resolution.resolvedVersion);const targetParentDirectory=path18.dirname(targetDirectory);let cacheIntegrityFailure;if(!refresh){const cached3=loadExactCachedBaseline(targetDirectory,resolution);if(cached3.baseline!==null){return{artifactPulled:false,baseline:cached3.baseline}}cacheIntegrityFailure=cached3.integrityFailure}mkdirSync4(targetParentDirectory,{recursive:true});const temporaryDirectory=mkdtempSync(path18.join(targetParentDirectory,".punks-verified-baseline-"));try{const archivePath=path18.join(temporaryDirectory,assetArchiveName);await download(resolution.archive.url,archivePath,timeoutMs).catch((error2)=>{if(cacheIntegrityFailure!==undefined&&bundledFallbackEligible(error2)){throw cacheIntegrityFailure}if(error2 instanceof Error){throw error2}throw new Error("Baseline archive download failed.")});const actualDigest=sha256File(archivePath);if(actualDigest!==resolution.digest||actualDigest!==resolution.archive.sha256){throw integrityFailure(resolution,"Downloaded baseline archive checksum mismatch.",actualDigest)}const extractedDirectory=path18.join(temporaryDirectory,"extracted");extractSafeTgz(archivePath,extractedDirectory);verifyEmbeddedBaselineMetadata(extractedDirectory,resolution,"Downloaded");rmSync(targetDirectory,{force:true,recursive:true});renameSync2(extractedDirectory,targetDirectory);copyFileSync(archivePath,path18.join(targetDirectory,cachedArtifactName));return{artifactPulled:true,baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"retrieved"))}}finally{rmSync(temporaryDirectory,{force:true,recursive:true})}};var resolveBaseline=(options4)=>gen2(function*executeBaselineResolution(){const selectedBaseline=options4.baseline??options4.configuration.release.baseline;const request=normalizeBaselineRequest(selectedBaseline);const isImplicitStable=selectedBaseline===undefined;if(request.channel==="bundled"){return yield*try_3({catch:classifyFailure,try:resolveVerifiedBundledBaseline})}const local=yield*try_3({catch:classifyFailure,try:()=>options4.configuration.release.baselineUrl===undefined?null:resolveLocalBaseline(options4.configuration.release.baselineUrl,request)});if(local!==null){return local}return yield*gen2(function*resolveRemoteBaseline(){const baseUrl2=resolveControlPlaneUrl(undefined,options4.configuration.controlPlane);if(baseUrl2===undefined){return yield*fail6(classifyFailure(new BaselineUnavailable({availability:"authority-unconfigured",message:"The control plane URL is unavailable; baseline authority cannot be resolved.",request})))}const timeoutMs=options4.timeoutMs??defaultRemoteBaselineTimeoutMs;const resolution=yield*resolveBaselineMetadata({baseUrl:baseUrl2,request}).pipe(timeout2(timeoutMs),mapError3(classifyFailure));const materialized=yield*tryPromise2({catch:classifyFailure,try:async()=>await materializeBaseline(resolution,options4.refresh??options4.configuration.release.refreshBaseline,timeoutMs,options4.configuration.release.cacheDirectory)});if(materialized.artifactPulled){yield*submitCliEventEffect("cli.artifact.pull.completed",{...options4.cwd===undefined?{}:{cwd:options4.cwd},baseline:{channel:materialized.baseline.summary.channel,version:materialized.baseline.summary.version},configuration:options4.configuration.controlPlane})}return materialized.baseline}).pipe(catchTag2("@punks/cli/baseline-resolution/BaselineResolutionFailure",(failure)=>isImplicitStable&&bundledFallbackEligible(failure.cause)?try_3({catch:classifyFailure,try:()=>resolveVerifiedBundledBaseline(request,"fallback")}):fail6(failure)))});var baselineResolveOptions=(baseline,refresh,cwd,configuration)=>{const selectedBaseline=isSome2(baseline)?baseline.value:configuration.release.baseline;return{...selectedBaseline===undefined?{}:{baseline:selectedBaseline},configuration,refresh:refresh||configuration.release.refreshBaseline,...cwd===undefined?{}:{cwd}}};class ScopedScaffoldOperationFailure extends TaggedErrorClass()("ScopedScaffoldOperationFailure",{cause:Defect(),message:String4,operation:Literals(["inspect","materialize","plan"])}){}var ScopedScaffoldOperation=Service("@punks/cli/scaffold-operation/ScopedScaffoldOperation");import path19 from"node:path";var baselineToolIds2=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills2=(skillIds,baseline=bundledBaseline)=>[...new Set([...baselineToolIds2,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var defaultPackIds2=defaultPackIdsForBaseline();var detectedPackIds2=detectedPackIdsForBaseline();var knownPackIds2=knownPackIdsForBaseline();var languagePackIds2=languagePackIdsForBaseline();var surfacePackIds2=surfacePackIdsForBaseline();var packRegistryForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map(({id,category,triggerPackages,description})=>({category,description,id,triggerPackages}));var packRegistry=packRegistryForBaseline();class UnknownPackIds extends TaggedErrorClass()("@punks/cli/repository-analysis/UnknownPackIds",{cause:Defect(),invalidPackIds:ArraySchema(String4),operation:Literal2("validate-pack-selection")}){}class RepositoryScanError extends TaggedErrorClass("@punks/cli/features/repository-analysis/RepositoryScanError")("RepositoryScanError",{cause:Defect(),operation:Literal2("scan-repository"),rootDirectory:String4}){}var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var pathSegments=(relativePath)=>relativePath.split(/[\\/]+/u);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>{const relativePath=pathSegments(manifest.relativePath).join("/");return![...wikiRootPaths].some((wikiRoot)=>relativePath===wikiRoot||relativePath.startsWith(`${wikiRoot}/`))});var hasFrontendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="nextjs"||technology==="react");var backendWorkspacePathSegments=new Set(["api","backend","server","services"]);var backendPackageNameSegments=new Set(["api","backend","server","service"]);var hasBackendWorkspaceName=(manifest)=>{const workspaceSegments=pathSegments(manifest.relativePath).slice(0,-1);if(workspaceSegments.some((segment)=>backendWorkspacePathSegments.has(segment))){return true}if(manifest.packageName===undefined||manifest.packageName===null||manifest.packageName.length===0){return false}const packageNameSegments=manifest.packageName.replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).filter((segment)=>segment.length>0).map((segment)=>segment.toLowerCase());return packageNameSegments.some((segment)=>backendPackageNameSegments.has(segment))};var hasBackendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="better-auth"||technology==="drizzle"||technology==="elysia"||technology==="trpc")||result4.manifests.some(hasBackendWorkspaceName);var detectionToPackId={"better-auth":"better-auth",drizzle:"drizzle",effect:"effect",elysia:"elysia",nextjs:"nextjs",react:"react","tanstack-query":"tanstack-query",trpc:"trpc",turborepo:"turborepo"};var toSortedUnique=(values)=>[...new Set(values)].toSorted();var isDetectedLanguage=(value5)=>value5==="python"||value5==="typescript";var detectLanguagePacks=(detection,baseline)=>{const packages=new Set(packDetectionManifests(detection.manifests).flatMap((manifest)=>manifest.dependencies));const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="language").filter((pack)=>isDetectedLanguage(pack.id)&&detection.detectedLanguages.includes(pack.id)||pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id).filter((packId)=>languagePackIdsForBaseline(baseline).includes(packId))};var detectSurfacePacks=(detection,baseline)=>[...hasBackendSurface(detection)?["backend"]:[],...hasFrontendSurface(detection)?["frontend"]:[]].filter((packId)=>surfacePackIdsForBaseline(baseline).includes(packId));var detectPackageTriggeredPacks=(detection,baseline)=>{const packages=new Set([...packDetectionManifests(detection.manifests).flatMap((manifest)=>manifest.dependencies),...detection.detectedPackages??[]]);const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="detected").filter((pack)=>pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id)};var resolvePackSelection=(detection,baseline=bundledBaseline)=>{const languagePacks=detectLanguagePacks(detection,baseline);const technologyPacks=detection.detectedTechnologies.flatMap((technology)=>{const packId=detectionToPackId[technology];return packId===undefined?[]:[packId]}).filter((packId)=>knownPackIdsForBaseline(baseline).includes(packId));const packageTriggeredPacks=detectPackageTriggeredPacks(detection,baseline);const surfacePacks=detectSurfacePacks(detection,baseline);const defaultPackIds3=defaultPackIdsForBaseline(baseline);const knownPackIds3=knownPackIdsForBaseline(baseline);const detectedPacks=toSortedUnique([...technologyPacks,...packageTriggeredPacks]);const preselectedPacks=toSortedUnique([...defaultPackIds3,...languagePacks,...detectedPacks,...surfacePacks]);const optionalPacks=knownPackIds3.filter((packId)=>!preselectedPacks.includes(packId));return{defaultPacks:defaultPackIds3,detectedPacks:toSortedUnique(detectedPacks),languagePacks:toSortedUnique(languagePacks),optionalPacks,preselectedPacks,surfacePacks:toSortedUnique(surfacePacks)}};var finalizePackSelection=(resolved,additions,removals)=>{const withAdditions=new Set([...resolved.preselectedPacks,...additions]);for(const removal of removals){if(resolved.defaultPacks.includes(removal)){continue}withAdditions.delete(removal)}return[...withAdditions].toSorted()};var canRemovePack=(resolved,packId)=>resolved.preselectedPacks.includes(packId)&&!resolved.defaultPacks.includes(packId);var inspectRepository=fn2("RepositoryAnalysis.inspect")(function*inspectRepository2({baseline,repoShapeMode,rootDirectory,scanner}){const scanned=yield*scanner.scan(rootDirectory);const detection=repoShapeMode==="auto"?scanned:{...scanned,monorepo:repoShapeMode==="monorepo"};return{detection,packs:resolvePackSelection(detection,baseline)}});var scaffoldValidationError=(cause,fallback)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:fallback});var selectedSkills=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var deepFreeze=(value5)=>{if(typeof value5!=="object"||value5===null||Object.isFrozen(value5)){return value5}for(const nested of Object.values(value5)){deepFreeze(nested)}return Object.freeze(value5)};var operationFailure=(cause)=>{if(cause instanceof ScopedScaffoldOperationFailure){return scaffoldValidationError(cause.cause,cause.message)}return cause};var runScaffold=({scanDirectory,emitJson=false,repoShapeMode="auto",interaction,outputDirectory,displayOutputDirectory,ensureTools:ensureTools2=true,baseline=bundledBaseline,assumeYes=false,toolStdio=emitJson?"ignore":"inherit",toolRuntime,clipboardRuntime,configuration={disableBundledUrl:true},scriptRuntimePath,scriptEnvironment})=>gen2(function*executeScaffold(){const resolvedOutputDirectory=path19.resolve(outputDirectory??scanDirectory);const ownedBaseline=deepFreeze(structuredClone(baseline));const capabilities=yield*ScaffoldCapabilities;const operation=yield*ScopedScaffoldOperation;const inspection=yield*operation.inspect({baseline:ownedBaseline,outputDirectory:resolvedOutputDirectory,repoShapeMode,scanDirectory}).pipe(mapError3(operationFailure));const{detection,packs:resolved}=inspection;const ownedResolved=structuredClone(resolved);for(const packIds of Object.values(ownedResolved)){Object.freeze(packIds)}Object.freeze(ownedResolved);const effectiveScriptRuntimePath=scriptRuntimePath??capabilities.scriptRuntimePath;const effectiveScriptEnvironment=scriptEnvironment??capabilities.scriptEnvironment;const baseRequiredTools=requiredToolsForSkills2([],ownedBaseline);let toolBootstrapStatuses=[];yield*interaction.emit({_tag:"SetupStarted"});if(ensureTools2&&baseRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"base",toolIds:baseRequiredTools});toolBootstrapStatuses=capabilities.ensureTools(baseRequiredTools,ownedBaseline,toolRuntime,{stdio:toolStdio});yield*interaction.emit({_tag:"ToolBootstrap",phase:"base",statuses:toolBootstrapStatuses})}yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"ResolvedPacks",baseline:ownedBaseline,resolved:ownedResolved});let additions=Object.freeze([]);let removals=Object.freeze([]);let finalPacks=ownedResolved.preselectedPacks;const selectPacksInteractively=()=>gen2(function*selectScaffoldPacks(){while(true){const shouldEditSelection=!(yield*interaction.keepPrefilledSelection());additions=Object.freeze([]);if(shouldEditSelection&&ownedResolved.optionalPacks.length>0){additions=Object.freeze([...yield*interaction.selectPacks({allowed:ownedResolved.optionalPacks,kind:"add"})])}const removablePacks=[...new Set([...ownedResolved.preselectedPacks,...additions])].filter((packId)=>canRemovePack(ownedResolved,packId)).toSorted();removals=Object.freeze([]);if(shouldEditSelection&&removablePacks.length>0){removals=Object.freeze([...yield*interaction.selectPacks({allowed:removablePacks,kind:"remove"})])}finalPacks=Object.freeze(finalizePackSelection(ownedResolved,additions,removals));if(shouldEditSelection){yield*interaction.emit({_tag:"SelectionPreview",addedPacks:additions,baseline:ownedBaseline,finalPacks,outputDirectory:resolvedOutputDirectory,preselectedPacks:ownedResolved.preselectedPacks,removedPacks:removals})}if(yield*interaction.confirmSelection()){return}yield*interaction.emit({_tag:"SelectionReopened"})}});yield*assumeYes?interaction.emit({_tag:"SelectionAccepted"}):selectPacksInteractively();const skillIds=selectedSkills(finalPacks,ownedBaseline);const requiredTools=requiredToolsForSkills2(skillIds,ownedBaseline);const checkedToolIds=new Set(toolBootstrapStatuses.map((entry)=>entry.toolId));const remainingRequiredTools=requiredTools.filter((toolId)=>!checkedToolIds.has(toolId));if(ensureTools2&&remainingRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"selected",toolIds:remainingRequiredTools});const remainingToolBootstrapStatuses=capabilities.ensureTools(remainingRequiredTools,ownedBaseline,toolRuntime,{stdio:toolStdio});toolBootstrapStatuses=[...toolBootstrapStatuses,...remainingToolBootstrapStatuses].toSorted((left,right)=>left.toolId.localeCompare(right.toolId));yield*interaction.emit({_tag:"ToolBootstrap",phase:"selected",statuses:remainingToolBootstrapStatuses})}const plan=yield*operation.plan({_tag:"PlanRepositoryScaffold",addedPacks:additions,...displayOutputDirectory===undefined?{}:{displayOutputDirectory},finalPacks,inspection,removedPacks:removals,requiredTools,scriptEnvironment:effectiveScriptEnvironment,scriptRuntimePath:effectiveScriptRuntimePath,toolBootstrapStatuses}).pipe(mapError3(operationFailure));const materialized=yield*operation.materialize(plan).pipe(mapError3(operationFailure));if(materialized._tag!=="MaterializedRepositoryScaffold"){return yield*new CliValidationError({message:"Repository scaffold operation returned staged materialization."})}const{agentSystemPrompt,result:result4}=materialized;const clipboardResult=capabilities.copyToClipboard(agentSystemPrompt,{...clipboardRuntime,env:clipboardRuntime?.env??effectiveScriptEnvironment});const completionResult=deepFreeze(structuredClone(result4));yield*interaction.emit({_tag:"SetupComplete",baseline:ownedBaseline,clipboard:clipboardResult,emitJson,result:completionResult});yield*submitCliEventEffect("cli.scaffold.setup.completed",{baseline:{version:ownedBaseline.summary.version},configuration,cwd:scanDirectory});return result4});import{execFileSync as execFileSync6}from"node:child_process";import{existsSync as existsSync8,lstatSync as lstatSync3,readFileSync as readFileSync9,realpathSync as realpathSync4}from"node:fs";import path21 from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{spawn as spawn2}from"node:child_process";import{lstatSync as lstatSync2,mkdtempSync as mkdtempSync2,readlinkSync as readlinkSync2,realpathSync as realpathSync3,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir5}from"node:os";import path20 from"node:path";import{createInterface as createInterface3}from"node:readline";var isOutsideRoot=(relativePath)=>relativePath===".."||relativePath.startsWith(`..${path20.sep}`)||path20.isAbsolute(relativePath);class ConfinedArchiveRecoveryError extends Error{_tag="ConfinedArchiveRecoveryError";evidence;constructor({cause,evidence}){super(`Confined archive replacement could not restore ${evidence.targetPath}. Retained archive: ${evidence.archivePath}.`,{cause});this.name="ConfinedArchiveRecoveryError";this.evidence=evidence}}var unsafeParentError=(directoryPath)=>new CliValidationError({message:`Refusing to mutate scaffold content through changed parent ${directoryPath}.`});var captureLeafExpectation=(targetPath)=>{const target=lstatSync2(targetPath,{throwIfNoEntry:false});if(target===undefined){return{kind:"absent"}}let kind="other";if(target.isSymbolicLink()){kind="symlink"}else if(target.isFile()){kind="file"}else if(target.isDirectory()){kind="directory"}return{device:target.dev,inode:target.ino,kind}};var confinedMutationScript=String.raw`
308
+ `));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption2=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption2,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path12 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String4,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var isRecord6=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:{...isRecord6(result4.machinePayload)?result4.machinePayload:{},operation:operationResult},operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path12.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json2,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json2||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path12.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({changes:operation.changes,degradations:operation.degradations,facts:operation.facts,issues:operation.issues,nextActions:operation.nextActions,status:operation.status,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(SelectedOutputMode.pipe(flatMap3((mode)=>executeOperatorCommand("migrate",undefined,mode)),map6(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path13 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String4,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path13.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path14 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check2,write:write2,yes,json:json2,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;if(check2&&(write2||yes)){return yield*new CliValidationError({message:"--check cannot be combined with --write or --yes."})}return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check2,emitJson:json2||selectedOutputMode==="json",refreshBaseline,rootDirectory:path14.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync5,realpathSync as realpathSync2}from"node:fs";var parseSemver=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u.exec(value5);if(match8===null){return null}return{major:Math.trunc(Number(match8[1])),minor:Math.trunc(Number(match8[2])),patch:Math.trunc(Number(match8[3])),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index=0;index<maxLength;index+=1){const candidatePart=candidateParts[index];const currentPart=currentParts[index];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&&currentIsNumeric){return Math.trunc(Number(candidatePart))>Math.trunc(Number(currentPart))?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>{controller.abort()},timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload==="object"&&payload!==null&&"version"in payload&&typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync5(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync2(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check2=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check2===null){return{check:check2,status:"unavailable"}}if(!check2.updateAvailable){return{check:check2,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check2,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check2,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check2=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check2===null){return{check:check2,status:"unavailable"}}if(!check2.updateAvailable&&!force){return{check:check2,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check2,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check2,command,environment,packageManager,status:"upgraded"}}return{check:check2,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path15 from"node:path";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_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String4),COLORFGBG:optional(String4),DP_SCRIPT_RUNTIME:optional(NonEmptyString),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(NumberFromString.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=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CODEX_HOME","DISPLAY","DP_SCRIPT_RUNTIME","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","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map6((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),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},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",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,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map6((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.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)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path15.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var safeEnvironmentKey=/^[A-Za-z_][A-Za-z0-9_]*$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var redactedEnvironmentValue="<redacted>";var redactCommandEnvironment=(environment)=>Object.fromEntries(Object.keys(environment).filter((key)=>safeEnvironmentKey.test(key)).map((key)=>[key,redactedEnvironmentValue]));var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=/\\+$/u.exec(value5)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}const safeCommandComponents=commandComponents.filter((component)=>component!==undefined);return`cmd.exe /d /v:off /s /c "${[...assignments,...safeCommandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:redactCommandEnvironment(result4.environment),kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}case"available":case"failed":case"manager-not-detected":case"unavailable":{return}default:{return result4}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:result4.packageManager===null?{}:minimumReleaseAgeEnvironmentForPackageManager(result4.packageManager),platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:async()=>await operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}const operationResult=upgradeOperationResult(result4);if(operationResult===undefined){return yield*fail6(new CliValidationError({message:"CLI upgrade failed."}))}return operationResult}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();function registration(command,commandMetadata,children=[]){return{children,command,metadata:commandMetadata}}var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(commitGateCommand,commitGateCommandMetadata,[registration(commitGateVerifyCommand,commitGateVerifyCommandMetadata)]),registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path16=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path16),command:node.command,metadata:commandMetadataFromDeclaration(path16,node.metadata)}});function buildRegisteredCommand(node){const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)}function buildCommandRegistry(rootCommand,registrations){const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}}var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync3}from"node:child_process";import{homedir as homedir2}from"node:os";var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");var clipboardWorkingDirectory=homedir2();var tryClipboardCommand=({command,args:args2,text:text3,runtime})=>{if(!runtime.commandExists(command)){return{ok:false}}try{runtime.execFile(command,args2,{cwd:clipboardWorkingDirectory,input:text3});return{command,ok:true}}catch{return{ok:false}}};var copyToClipboard=(text3,runtime)=>{const environment=runtime.env??{};if(!shouldUseClipboard(environment)){return{ok:false}}const commandRuntime={commandExists:runtime.commandExists??((command)=>commandExistsOnPath(command,environment)),execFile:runtime.execFile??((command,args2,options4)=>execFileSync3(command,[...args2],{cwd:options4.cwd,env:environment,input:options4.input,stdio:["pipe","ignore","ignore"]}))};const platform=runtime.platform??process.platform;if(platform==="darwin"){return tryClipboardCommand({args:[],command:"pbcopy",runtime:commandRuntime,text:text3})}if(platform==="win32"){return tryClipboardCommand({args:[],command:"clip",runtime:commandRuntime,text:text3})}const candidates=[{args:[],command:"wl-copy"},{args:["-selection","clipboard"],command:"xclip"},{args:["--clipboard","--input"],command:"xsel"}];for(const candidate of candidates){const result4=tryClipboardCommand({...candidate,runtime:commandRuntime,text:text3});if(result4.ok){return result4}}return{ok:false}};var makeScaffoldCapabilities=(runtime)=>({copyToClipboard:(text3,override={})=>copyToClipboard(text3,{...override,env:override.env??runtime.commandEnvironment}),ensureTools:(toolIds,baseline,override,options4)=>ensureToolsInstalledBestEffort(toolIds,baseline,override??makeToolCommandRuntime(runtime.commandEnvironment),options4),readSettings:readRepoSettings,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath});var scaffoldCapabilitiesLayer=effect(ScaffoldCapabilities,CliRuntimeConfig.pipe(map6(makeScaffoldCapabilities)));import{readFileSync as readFileSync6}from"node:fs";import path16 from"node:path";var isMissingFile=(cause)=>cause instanceof Error&&("code"in cause)&&cause.code==="ENOENT";var makeRepositoryCheckCapabilities=(runtime,projectSettings)=>({assessSettings:(rootDirectory)=>projectSettings.read(rootDirectory).pipe(map6(({settings,upgrade})=>({settings:{...settings.baselineVersion===undefined?{}:{baselineVersion:settings.baselineVersion},...settings.cliVersion===undefined?{}:{cliVersion:settings.cliVersion},commitGate:settings.commitGate??"enabled"},upgrade})),catchTag2("ProjectSettingsMissing",()=>succeed6(null)),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:"Failed to assess project settings.",operation:"assess-project-settings"}))),checkCli:(tag4)=>promise2(async()=>await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:tag4})),commitGateDesiredStateHash,isCommitGateApplicable,observeCommitGate,readCommitGateLifecycleReceipt:(rootDirectory)=>{try{const content=readFileSync6(path16.join(rootDirectory,commitGateLifecycleReceiptFile),"utf-8");return decodeCommitGateLifecycleReceipt(JSON.parse(content))}catch{return null}},readTextFile:(filePath)=>try_3({catch:(cause)=>new RepositoryCheckOperationFailure({cause,message:`Failed to read changelog: ${filePath}`,operation:"read-changelog"}),try:()=>readFileSync6(filePath,"utf-8")}).pipe(catchIf2((failure)=>isMissingFile(failure.cause),()=>succeed6(null)))});var repositoryCheckCapabilitiesLayer=effect(RepositoryCheckCapabilities,gen2(function*repositoryCheckCapabilitiesLayer2(){const runtime=yield*CliRuntimeConfig;const projectSettings=yield*ProjectSettings;return makeRepositoryCheckCapabilities(runtime,projectSettings)}));import{createHash as createHash5}from"node:crypto";import{execFileSync as execFileSync5}from"node:child_process";import{copyFileSync,existsSync as existsSync7,mkdirSync as mkdirSync4,mkdtempSync,readFileSync as readFileSync8,renameSync as renameSync2,rmSync,writeFileSync as writeFileSync4}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path18 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var BaselineChannel2=Literals(["stable","bundled"]);var BaselineSource2=Literals(["bundled","remote","local","control-plane"]);var SharedPromptCapability=Struct({path:Literal2("data/shared-agents.md"),sha256:String4.check(isPattern2(/^[0-9a-f]{64}$/u)),version:Literal2(1)});var SkillAuthoringContract=Struct({activationRevision:NonEmptyString,authoringRevision:NonEmptyString,id:NonEmptyString});var ScopedAuthoringCapability=Struct({revision:NonEmptyString,skills:ArraySchema(SkillAuthoringContract),version:Literal2(1)});var BaselineCapabilities=Struct({scopedAuthoring:optionalKey2(ScopedAuthoringCapability),sharedPrompt:optionalKey2(SharedPromptCapability)});var ArtifactObligation=Struct({contentAuthority:Literals(["scaffold","repository","mixed","unknown"]),dependencies:ArraySchema(NonEmptyString),presence:Literals(["required","optional"]),producer:NonEmptyString,validity:Literals(["managed-bytes","authored-content","structured-entries","presence"])});var SharedPromptIdentity=Struct({baselineDigest:NonEmptyString,baselineVersion:NonEmptyString,capabilityVersion:Literal2(1),templateDigest:NonEmptyString});var ScaffoldArtifactKind=Literals(["manifest","archive"]);class ScaffoldArtifactMetadata extends Class4("ScaffoldArtifactMetadata")(orderedSchemaFields(["kind",ScaffoldArtifactKind],["fileName",String4],["contentType",String4],["url",String4],["sha256",String4],["sizeBytes",optional(Number6)])){}var ScaffoldManagedFileKind=Literals(["agent-prompt","context-plan","handoff","harness","hook","lint-spec","manifest","prompt-spec","projection-receipt","required-tools","script","skill","source-guide","subagent"]);var Sha256Digest=String4.check(isPattern2(/^[0-9a-f]{64}$/u));var FileMode=Number6.check(isInt(),isGreaterThanOrEqualTo3(0),isLessThanOrEqualTo4(511));var ManagedFileFingerprint=TaggedUnion({File:{mode:FileMode,sha256:Sha256Digest},Symlink:{sha256:Sha256Digest,target:NonEmptyString}});var ProjectGeneratedAuthority=TaggedUnion({RepositoryMirror:{sourcePath:NonEmptyString}});var ProjectGeneratedOwnership=Struct(orderedSchemaFields(["producer",NonEmptyString],["revision",optionalKey2(NonEmptyString)],["authority",ProjectGeneratedAuthority],["outputFingerprint",ManagedFileFingerprint]));var ManagedFileOwnership=TaggedUnion({ProjectGenerated:{evidence:ProjectGeneratedOwnership},ScaffoldManaged:{}});var scaffoldManagedOwnership=ManagedFileOwnership.cases.ScaffoldManaged.make({});class ScaffoldManagedFileSummary extends Class4("ScaffoldManagedFileSummary")(orderedSchemaFields(["path",String4],["sha256",String4],["kind",ScaffoldManagedFileKind],["obligation",optionalKey2(ArtifactObligation)],["sharedPromptIdentity",optionalKey2(SharedPromptIdentity)],["ownership",optionalKey2(ManagedFileOwnership).pipe(decodeTo2(ManagedFileOwnership,{decode:withDefault(succeed6(scaffoldManagedOwnership)),encode:transformOptional(filter((ownership)=>ownership._tag!=="ScaffoldManaged"))}),withConstructorDefault2(succeed6(scaffoldManagedOwnership)))])){}class ScaffoldProvenance extends Class4("ScaffoldProvenance")(orderedSchemaFields(["source",BaselineSource2],["channel",BaselineChannel2],["version",String4],["tag",optional(NullOr(String4))],["commit",optional(NullOr(String4))],["sha256",optional(NullOr(String4))])){}class ScaffoldBaselineManifest extends Class4("ScaffoldBaselineManifest")(orderedSchemaFields(["channel",BaselineChannel2],["version",String4],["tag",optional(NullOr(String4))],["commit",optional(NullOr(String4))],["sha256",optional(NullOr(String4))])){}var CliVersionRange=String4.check(isTrimmed(),isNonEmpty());var EmbeddedBaselineFields=[["capabilities",optionalKey2(BaselineCapabilities)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["sha256",optionalKey2(NullOr(NonEmptyString))],["generatedAt",optionalKey2(NonEmptyString)]];var EmbeddedScaffoldBaselineMetadataV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],...EmbeddedBaselineFields,["compatibility",optionalKey2(Struct({cliVersionRange:CliVersionRange}))]));var EmbeddedScaffoldBaselineMetadataV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],...EmbeddedBaselineFields,["compatibility",Struct({cliVersionRange:CliVersionRange})]));var EmbeddedScaffoldBaselineMetadata=Union2([EmbeddedScaffoldBaselineMetadataV1,EmbeddedScaffoldBaselineMetadataV2]);var PublishedScaffoldBaselineManifestV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString]));var PublishedScaffoldBaselineManifestV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString],["compatibility",Struct({cliVersionRange:CliVersionRange})]));var PublishedScaffoldBaselineManifest=Union2([PublishedScaffoldBaselineManifestV1,PublishedScaffoldBaselineManifestV2]);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 versionPattern=new RegExp(String.raw`^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?$`,"u");var constraintPattern=new RegExp(String.raw`^(?<operator>>=|<=|>|<|=)?(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?)?)?$`,"u");var numericIdentifierPattern=/^\d+$/u;var parseVersion=(value5)=>{const groups=versionPattern.exec(value5)?.groups;return groups===undefined?null:[Number(groups.major),Number(groups.minor),Number(groups.patch),groups.prerelease?.split(".")??[]]};var comparePrereleaseIdentifiers=(left,right)=>{const leftNumeric=numericIdentifierPattern.test(left);const rightNumeric=numericIdentifierPattern.test(right);if(leftNumeric&&rightNumeric){if(BigInt(left)<BigInt(right)){return-1}return BigInt(left)>BigInt(right)?1:0}if(leftNumeric!==rightNumeric){return leftNumeric?-1:1}if(left<right){return-1}return left>right?1:0};var comparePrereleases=(left,right)=>{if(left.length===0||right.length===0){if(left.length===right.length){return 0}return left.length===0?1:-1}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){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}const compared=comparePrereleaseIdentifiers(leftIdentifier,rightIdentifier);if(compared!==0){return compared}}return 0};var compareCoreVersions=(left,right)=>left[0]-right[0]||left[1]-right[1]||left[2]-right[2];var compareVersions2=(left,right)=>compareCoreVersions(left,right)||comparePrereleases(left[3],right[3]);var nextPartialVersion=(version3,precision)=>precision===1?[version3[0]+1,0,0,[]]:[version3[0],version3[1]+1,0,[]];var constraintPrecision=(groups)=>{if(groups.patch!==undefined){return 3}return groups.minor===undefined?1:2};var parseCompatibilityRange=(range2)=>{const normalized=range2.trim();if(normalized==="*"){return[]}return normalized.split(/\s+/u).map((constraint)=>{const groups=constraintPattern.exec(constraint)?.groups;if(groups===undefined){return null}return{operator:groups.operator??"=",precision:constraintPrecision(groups),target:[Number(groups.major),Number(groups.minor??0),Number(groups.patch??0),groups.prerelease?.split(".")??[]]}})};var satisfiesCliCompatibilityRange=(range2,version3)=>{if(range2.trim()==="*"){return true}const constraints=parseCompatibilityRange(range2);const current=parseVersion(version3);if(current===null||constraints.some((constraint)=>constraint===null)){return false}return constraints.every(({operator,precision,target})=>{const compare=precision===3?compareVersions2:compareCoreVersions;const compared=compare(current,target);const next=precision===3?undefined:nextPartialVersion(target,precision);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}}})};import{existsSync as existsSync6,readFileSync as readFileSync7}from"node:fs";import path17 from"node:path";function readJson(filePath){const value5=JSON.parse(readFileSync7(filePath,"utf-8"));return value5}var validateBaselineAssets=({root,skills,skillIdAliases})=>{for(const skill of skills){if(!existsSync6(path17.join(root,skill.sourceDirectory))){throw new Error(`Baseline skill asset missing: ${skill.sourceDirectory}`)}}for(const alias of skillIdAliases??[]){if(alias.compatibilitySourceDirectory!==undefined&&!existsSync6(path17.join(root,alias.compatibilitySourceDirectory))){throw new Error(`Baseline skill compatibility asset missing: ${alias.compatibilitySourceDirectory}`)}}};var loadBaselineFromDirectory=(root,verifiedSummary)=>{const metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(readJson(path17.join(root,"baseline.json")));if(metadata.version!==verifiedSummary.resolvedVersion){throw new Error("Baseline metadata does not match the verified version.")}const dataRoot2=path17.join(root,"data");const aliasesPath=path17.join(dataRoot2,"catalog","skill-id-aliases.json");const aliases=existsSync6(aliasesPath)?readJson(aliasesPath):[];const skills=stripSkillIdCompatibilityProjectionRows(readJson(path17.join(dataRoot2,"catalog","skills.json")),aliases);const skillIdAliases=validateSkillIdAliases(aliases,skills);const baseline={...metadata.capabilities===undefined?{}:{capabilities:metadata.capabilities},dataRoot:dataRoot2,hooks:readJson(path17.join(dataRoot2,"catalog","hooks.json")),lintAssets:validateLintCatalog(readJson(path17.join(dataRoot2,"catalog","lint-assets.json"))),packs:readJson(path17.join(dataRoot2,"catalog","packs.json")),root,skillIdAliases,skills,skillsRoot:path17.join(root,"skills"),summary:verifiedSummary,tools:readJson(path17.join(dataRoot2,"catalog","tools.json"))};validateBaselineAssets(baseline);return baseline};var defaultMessage3=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BackofficeAccessRole=Literals(["admin","member"]);var BackofficeAccessStatus=Literals(["invited","active","revoked"]);var BackofficeAccessSummary=Struct({email:String4,role:BackofficeAccessRole,status:BackofficeAccessStatus,userId:optionalKey2(String4),invitedBy:optionalKey2(String4),revokedBy:optionalKey2(String4),invitedAt:optionalKey2(String4),activatedAt:optionalKey2(String4),revokedAt:optionalKey2(String4),createdAt:String4,updatedAt:String4}).annotate({identifier:"BackofficeAccessSummary"});var BackofficeAccessList=Struct({users:ArraySchema(BackofficeAccessSummary)}).annotate({identifier:"BackofficeAccessList"});var BackofficeAccessInviteRequest=Struct({email:String4,role:BackofficeAccessRole}).annotate({identifier:"BackofficeAccessInviteRequest"});var BackofficeOperatorSummary=Struct({operatorId:optionalKey2(String4),email:optionalKey2(String4),name:optionalKey2(String4)}).annotate({identifier:"BackofficeOperatorSummary"});var ObservedRepositorySummary=Struct({id:String4,projectUsageId:String4,remoteHost:optionalKey2(String4),remotePath:optionalKey2(String4),remoteUrl:optionalKey2(String4),branch:optionalKey2(String4),lastCommitSha:optionalKey2(String4),dirty:optionalKey2(Boolean3),gitIdentity:optionalKey2(GitIdentity),firstSeenAt:optionalKey2(IsoDateTimeString),lastSeenAt:optionalKey2(IsoDateTimeString)}).annotate({identifier:"ObservedRepositorySummary"});var ProjectUsageEventSummary=Struct({id:String4,eventId:String4,name:String4,source:String4,counted:Boolean3,cliVersion:String4,baseline:optionalKey2(Struct({channel:optionalKey2(String4),version:optionalKey2(String4)})),occurredAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageEventSummary"});var HarnessReportSummary=Struct({id:String4,projectUsageId:optionalKey2(String4),observedRepositoryId:optionalKey2(String4),title:String4,body:optionalKey2(String4),type:String4,severity:String4,status:String4,githubUrl:optionalKey2(String4),createdAt:IsoDateTimeString,updatedAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"HarnessReportSummary"});var ProjectUsageSummary=Struct({id:String4,name:optionalKey2(String4),repositoryCount:Finite,countedEventCount:Finite,openReportCount:Finite,latestCliVersion:optionalKey2(String4),latestBaselineChannel:optionalKey2(String4),latestBaselineVersion:optionalKey2(String4),lastActivityAt:optionalKey2(IsoDateTimeString),initializedBy:optionalKey2(BackofficeOperatorSummary),lastUpdatedBy:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageSummary"});var ProjectUsageList=Struct({projects:ArraySchema(ProjectUsageSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageList"});var ProjectUsageDetail=Struct({project:ProjectUsageSummary,repositories:ArraySchema(ObservedRepositorySummary),events:ArraySchema(ProjectUsageEventSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageDetail"});var BackofficeRepositoryMappingRequest=Struct({observedRepositoryId:String4}).annotate({identifier:"BackofficeRepositoryMappingRequest"});var BackofficeReportUpdateRequest=Struct({status:optionalKey2(HarnessReportStatus),githubUrl:optionalKey2(NullOr(String4))}).annotate({identifier:"BackofficeReportUpdateRequest"});class Unauthorized extends TaggedErrorClass()("@punks/contract/errors/Unauthorized",{message:defaultMessage3("Backoffice session is required.")},{httpApiStatus:401,title:"Unauthorized"}){}class BackofficeRequestRejected extends TaggedErrorClass()("@punks/contract/errors/BackofficeRequestRejected",{message:String4},{httpApiStatus:400,title:"Backoffice Request Rejected"}){}class BackofficePersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficePersistenceUnavailable",{message:defaultMessage3("Backoffice persistence is unavailable.")},{httpApiStatus:503,title:"Backoffice Persistence Unavailable"}){}class BackofficeDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficeDependencyUnavailable",{message:defaultMessage3("Backoffice dependency is unavailable.")},{httpApiStatus:503,title:"Backoffice Dependency Unavailable"}){}var listErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficePersistenceUnavailable];var rejectedErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficeRequestRejected,BackofficePersistenceUnavailable];var projectUsageListErrors=[...listErrors,BackofficeDependencyUnavailable];var projectUsageDetailErrors=[...rejectedErrors,BackofficeDependencyUnavailable];var BackofficeApi=exports_HttpApiGroup.make("backoffice").add(exports_HttpApiEndpoint.get("currentAccess","/access/current",{success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("accessList","/access-users",{success:BackofficeAccessList,error:listErrors}),exports_HttpApiEndpoint.post("inviteAccess","/access-users",{payload:BackofficeAccessInviteRequest,success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.post("revokeAccess","/access-users/:email/revoke",{params:{email:String4},success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("projectUsageList","/project-usages",{success:ProjectUsageList,error:projectUsageListErrors}),exports_HttpApiEndpoint.get("projectUsageDetail","/project-usages/:projectUsageId",{params:{projectUsageId:String4},success:ProjectUsageDetail,error:projectUsageDetailErrors}),exports_HttpApiEndpoint.post("mapRepository","/project-usages/:projectUsageId/repositories",{params:{projectUsageId:String4},payload:BackofficeRepositoryMappingRequest,success:ObservedRepositorySummary,error:rejectedErrors}),exports_HttpApiEndpoint.patch("updateReport","/reports/:reportId",{params:{reportId:String4},payload:BackofficeReportUpdateRequest,success:HarnessReportSummary,error:rejectedErrors})).prefix("/backoffice").annotateMerge(exports_OpenApi.annotations({title:"Backoffice project usage"}));var defaultMessage4=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var HarnessReportType=Literals(["bug","docs","workflow","tooling","other"]);var HarnessReportSeverity=Literals(["low","medium","high"]);var HarnessReportLabel=String4.check(isTrimmed(),isNonEmpty(),isMaxLength(50));var HarnessReportLabels=ArraySchema(HarnessReportLabel).check(isMaxLength(10));var HarnessReportInput=Struct({title:optionalKey2(String4),body:optionalKey2(String4),type:HarnessReportType,severity:HarnessReportSeverity,createdAt:IsoDateTimeString,cliVersion:String4,area:optionalKey2(String4),skillPack:optionalKey2(String4),command:optionalKey2(String4),expected:optionalKey2(String4),actual:optionalKey2(String4),steps:optionalKey2(String4),labels:optionalKey2(HarnessReportLabels),projectUsageId:optionalKey2(String4),repository:optionalKey2(ObservedRepositoryInput),githubUrl:optionalKey2(String4)}).annotate({identifier:"HarnessReportInput"});var HarnessReportCreated=Struct({reportId:String4,status:HarnessReportStatus,githubUrl:optionalKey2(String4),title:optionalKey2(String4),deduplicated:optionalKey2(Boolean3),duplicateOf:optionalKey2(String4)}).annotate({identifier:"HarnessReportCreated"});class HarnessReportRejected extends TaggedErrorClass()("@punks/contract/errors/HarnessReportRejected",{message:String4},{httpApiStatus:400,title:"Harness Report Rejected"}){}class HarnessReportPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportPersistenceUnavailable",{message:defaultMessage4("Harness report persistence is unavailable.")},{httpApiStatus:503,title:"Harness Report Persistence Unavailable"}){}class HarnessReportDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportDependencyUnavailable",{message:defaultMessage4("Harness report submission dependency is unavailable.")},{httpApiStatus:503,title:"Harness Report Dependency Unavailable"}){}var ReportsApi=exports_HttpApiGroup.make("reports").add(exports_HttpApiEndpoint.post("submit","/",{payload:HarnessReportInput,success:HarnessReportCreated,error:[HttpApiDecodeError,Forbidden2,HarnessReportRejected,HarnessReportDependencyUnavailable,HarnessReportPersistenceUnavailable]})).prefix("/reports").annotateMerge(exports_OpenApi.annotations({title:"Harness reports"}));var defaultMessage5=(message)=>String4.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ProductTelemetryEventName=Literals(["cli.artifact.pull.completed","cli.scaffold.init.completed","cli.scaffold.setup.completed","cli.scaffold.update.applied","cli.harness.report.submitted"]);var TelemetrySource=Literals(["normal","local-dev","ci","debug","test"]);var TelemetryBaselineContext=Struct({channel:optionalKey2(BaselineChannel),version:optionalKey2(String4)}).annotate({identifier:"TelemetryBaselineContext"});var ProductTelemetryEventInput=Struct({eventId:String4,name:ProductTelemetryEventName,occurredAt:IsoDateTimeString,cliVersion:String4,source:TelemetrySource,projectUsageId:optionalKey2(String4),repository:optionalKey2(ObservedRepositoryInput),baseline:optionalKey2(TelemetryBaselineContext)}).annotate({identifier:"ProductTelemetryEventInput"});var ProductTelemetryEventAccepted=Struct({eventId:String4,accepted:Boolean3,counted:Boolean3}).annotate({identifier:"ProductTelemetryEventAccepted"});class TelemetryEventRejected extends TaggedErrorClass()("@punks/contract/errors/TelemetryEventRejected",{message:String4},{httpApiStatus:400,title:"Telemetry Event Rejected"}){}class TelemetryPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/TelemetryPersistenceUnavailable",{message:defaultMessage5("Telemetry persistence is unavailable.")},{httpApiStatus:503,title:"Telemetry Persistence Unavailable"}){}var TelemetryApi=exports_HttpApiGroup.make("telemetry").add(exports_HttpApiEndpoint.post("record","/events",{payload:ProductTelemetryEventInput,success:ProductTelemetryEventAccepted,error:[HttpApiDecodeError,Forbidden2,TelemetryEventRejected,TelemetryPersistenceUnavailable]})).prefix("/telemetry").annotateMerge(exports_OpenApi.annotations({title:"Product telemetry"}));var HealthApi=exports_HttpApiGroup.make("health",{topLevel:true}).add(exports_HttpApiEndpoint.get("healthz","/healthz",{success:exports_HttpApiSchema.NoContent.annotate({description:"Empty health response"}),error:[HttpApiDecodeError,Forbidden2]}));var HarnessApi=exports_HttpApi.make("harness").add(HealthApi,BaselineApi,TelemetryApi,ReportsApi,BackofficeApi).prefix("/api").annotateMerge(exports_OpenApi.annotations({title:"Harness Intelligence Control Plane",summary:"Shared typed contract for Devpunks CLI/backend control-plane calls."}));var ControlPlaneOperation=Literals(["record-product-telemetry","resolve-stable-baseline","submit-harness-report"]);class ControlPlaneRequestFailure extends TaggedErrorClass()("@punks/cli/control-plane/ControlPlaneRequestFailure",{cause:Defect(),operation:ControlPlaneOperation,transport:Boolean3}){}var isHttpTransportFailure=(cause)=>isHttpClientError(cause)&&cause.reason._tag==="TransportError";var normalizeControlPlaneFailure=(operation,effect2)=>effect2.pipe(catchIf2((cause)=>isHttpClientError(cause)||isSchemaError(cause),(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation,transport:isHttpTransportFailure(cause)}))));var makeControlPlaneClient=({baseUrl:baseUrl2,headers})=>exports_HttpApiClient.make(HarnessApi,{baseUrl:baseUrl2,...headers===undefined?{}:{transformClient:(client)=>client.pipe(exports_HttpClient.mapRequest(exports_HttpClientRequest.setHeaders(headers)))}});var resolveBaselineMetadata=(options4)=>normalizeControlPlaneFailure("resolve-stable-baseline",gen2(function*requestBaselineMetadata(){const client=yield*makeControlPlaneClient(options4);return yield*client.baseline.resolve({params:{channel:options4.request.channel},query:options4.request.version===undefined?{}:{version:options4.request.version}})}));var recordProductTelemetryEvent=(options4)=>normalizeControlPlaneFailure("record-product-telemetry",gen2(function*sendProductTelemetryEvent(){const client=yield*makeControlPlaneClient(options4);return yield*client.telemetry.record({payload:options4.event})}));var submitHarnessReport=(options4)=>normalizeControlPlaneFailure("submit-harness-report",gen2(function*sendHarnessReport(){const client=yield*makeControlPlaneClient(options4);return yield*client.reports.submit({payload:options4.report})}));var BundledControlPlaneConfig=Struct({defaultUrl:optional(Unknown2)});var trimTrailingSlashes=(value5)=>value5.trim().replace(/\/+$/u,"");var bundledControlPlaneUrl=({disableBundledUrl=false}={})=>{if(disableBundledUrl){return}const config=decodeUnknownSync(BundledControlPlaneConfig)(JSON.parse(readDataFile("control-plane.json")));return typeof config.defaultUrl==="string"&&config.defaultUrl.trim().length>0?trimTrailingSlashes(config.defaultUrl):undefined};var resolveControlPlaneUrl=(explicitUrl,configuration={})=>{const baseUrl2=explicitUrl?.trim()??configuration.baseUrl?.trim()??bundledControlPlaneUrl(configuration);return baseUrl2===undefined||baseUrl2.length===0?undefined:trimTrailingSlashes(baseUrl2)};class BaselineResolutionFailure extends TaggedErrorClass()("@punks/cli/baseline-resolution/BaselineResolutionFailure",{cause:Defect(),message:String4,operation:Literal2("resolve-stable-baseline"),reason:Literals(["corrupt-artifact","remote-access","unsafe-artifact","invalid-artifact"])}){}import{randomUUID}from"node:crypto";import{execFileSync as execFileSync4}from"node:child_process";var disabledTelemetryConfig={disableBundledUrl:true};var git=(cwd,args2)=>{try{return execFileSync4("git",args2,{cwd,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};var redactRemote=(remote)=>remote.replace(/\/\/[^/@]+@/u,"//");var safeRemoteParts=(remote)=>{const redacted4=redactRemote(remote);const ssh=/^git@(?<host>[^:]+):(?<path>.+)$/u.exec(redacted4);const sshGroups=ssh?.groups;if(sshGroups!==undefined){return{remoteHost:sshGroups.host,remotePath:sshGroups.path.replace(/\.git$/u,""),remoteUrl:redacted4}}try{const url=new URL(redacted4);return{remoteHost:url.hostname,remotePath:url.pathname.replaceAll(/^\/|\.git$/gu,""),remoteUrl:redacted4}}catch{return{remoteUrl:redacted4}}};var observedRepository=(cwd)=>{const remote=git(cwd,["config","--get","remote.origin.url"]);const commitSha=git(cwd,["rev-parse","HEAD"])??undefined;const status2=git(cwd,["status","--short"]);const name2=git(cwd,["config","--local","--get","user.name"])??undefined;const email=git(cwd,["config","--local","--get","user.email"])??undefined;return{...remote===null?{}:safeRemoteParts(remote),...commitSha===undefined?{}:{commitSha},...status2===null?{}:{dirty:status2.length>0},...name2===undefined&&email===undefined?{}:{gitIdentity:{...name2===undefined?{}:{name:name2},...email===undefined?{}:{email}}}}};var isLocalControlPlaneUrl=(value5)=>{if(value5===undefined||value5.trim().length===0){return false}try{const{hostname}=new URL(value5);return hostname==="localhost"||hostname.endsWith(".localhost")||hostname.startsWith("127.")||hostname==="0.0.0.0"||hostname==="::1"||hostname==="[::1]"}catch{return value5.includes("localhost")||value5.includes(".localhost")}};var telemetrySource=(configuration={})=>{if(configuration.telemetrySource==="ci"){return"ci"}if(configuration.telemetrySource==="debug"){return"debug"}if(configuration.telemetrySource==="test"){return"test"}if(isLocalControlPlaneUrl(configuration.baseUrl)){return"local-dev"}return"normal"};var makeProductTelemetryEvent=({name:name2,cwd,baseline,controlPlaneUrl,configuration})=>{const repository=observedRepository(cwd);return{cliVersion:version2,eventId:randomUUID(),name:name2,occurredAt:new Date().toISOString(),...repository===undefined?{}:{repository},source:telemetrySource(configuration??(controlPlaneUrl===undefined?{}:{baseUrl:controlPlaneUrl})),...baseline===undefined?{}:{baseline}}};var telemetryBaseUrl=(controlPlaneUrl,configuration=disabledTelemetryConfig)=>resolveControlPlaneUrl(controlPlaneUrl,configuration);var submitProductTelemetryEffect=(event,options4={})=>{const baseUrl2=telemetryBaseUrl(options4.controlPlaneUrl,options4.configuration);if(baseUrl2===undefined){return void_3}return recordProductTelemetryEvent({baseUrl:baseUrl2,event}).pipe(catchTags2({"@punks/cli/control-plane/ControlPlaneRequestFailure":()=>void_3,"@punks/contract/errors/Forbidden":()=>void_3,"@punks/contract/errors/TelemetryEventRejected":()=>void_3,"@punks/contract/errors/TelemetryPersistenceUnavailable":()=>void_3,HttpApiDecodeError:()=>void_3}),asVoid2)};var telemetryTransportEnabled=(controlPlaneUrl,configuration)=>telemetryBaseUrl(controlPlaneUrl,configuration)!==undefined;var makeCliEvent=(name2,options4={})=>makeProductTelemetryEvent({cwd:options4.cwd??process.cwd(),name:name2,...options4.baseline===undefined?{}:{baseline:options4.baseline},...options4.controlPlaneUrl===undefined?{}:{controlPlaneUrl:options4.controlPlaneUrl},...options4.configuration===undefined?{}:{configuration:options4.configuration}});var submitCliEventEffect=(name2,options4={})=>telemetryTransportEnabled(options4.controlPlaneUrl,options4.configuration)?submitProductTelemetryEffect(makeCliEvent(name2,options4),options4):void_3;var assetArchiveName="scaffold-baseline.tgz";var cachedArtifactName=".verified-artifact.tgz";var maximumArchiveRedirects=20;var defaultRemoteBaselineTimeoutMs=5000;var archiveRedirectStatuses=new Set([301,302,303,307,308]);var bundledFallbackAvailability=new Set(["authority-unconfigured","network","unavailable-status"]);var BaselineArchiveEndpointFailure=Union2([BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable]);var isBaselineReleaseTag=(tag4)=>tag4.startsWith("baseline/stable/")&&!/^v\d+\.\d+\.\d+(?:$|-)/u.test(tag4);var normalizeBaselineRequest=(value5)=>{const requested=value5?.trim();if(requested===undefined||requested.length===0||requested==="stable"){return{channel:"stable"}}return requested==="bundled"?{channel:"bundled"}:{channel:"stable",version:requested}};var sha256File=(filePath)=>createHash5("sha256").update(readFileSync8(filePath)).digest("hex");var isSafeTarPath=(entry)=>entry.length>0&&!path18.isAbsolute(entry)&&!entry.split("/").includes("..");var isSafePathSegment=(value5)=>value5.length>0&&value5!=="."&&value5!==".."&&!value5.includes("/")&&!value5.includes("\\");var integrityFailure=(resolution,message,actualDigest)=>new BaselineIntegrityFailure({...actualDigest===undefined?{}:{actualDigest},expectedDigest:resolution.digest,message,request:resolution.requested,resolvedVersion:resolution.resolvedVersion});var verifyEmbeddedBaselineMetadata=(root,resolution,retrieval)=>{let metadata;try{metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync8(path18.join(root,"baseline.json"),"utf-8")))}catch{throw integrityFailure(resolution,`${retrieval} baseline metadata is invalid.`)}if(metadata.channel!==resolution.requested.channel||metadata.version!==resolution.resolvedVersion||resolution.provenance!==`release:${resolution.resolvedVersion}`||metadata.tag!==`baseline/stable/${resolution.resolvedVersion}`||metadata.sha256!==undefined&&metadata.sha256!==null&&metadata.sha256!==resolution.digest||metadata.compatibility!==undefined&&metadata.compatibility.cliVersionRange!==resolution.compatibility.cliVersionRange){throw integrityFailure(resolution,`${retrieval} baseline metadata disagrees with selected authority.`)}};class BaselineArchiveUnavailableError extends Error{name="BaselineArchiveUnavailableError"}var baselineFailureMessage=(cause)=>{if(cause instanceof ControlPlaneRequestFailure||isTimeoutError2(cause)){return"The baseline authority request failed."}if(cause instanceof Error&&typeof cause.message==="string"&&cause.message.trim().length>0){return cause.message}return"Baseline resolution failed."};var parseArchiveUrl=(value5)=>{let url;try{url=new URL(value5)}catch{throw new Error("Authority returned an invalid baseline archive URL.")}if(url.protocol!=="http:"&&url.protocol!=="https:"){throw new Error("Authority returned an invalid baseline archive URL.")}return url};var fetchArchiveResponse=async(url,signal,redirects=0)=>{const response=await fetch(url,{redirect:"manual",signal}).catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to download baseline artifact.",{cause:error2})});if(!archiveRedirectStatuses.has(response.status)){return response}const location2=response.headers.get("location");if(location2===null||redirects>=maximumArchiveRedirects){throw new Error("Authority returned an invalid baseline archive URL.")}const redirectedUrl=parseArchiveUrl(location2).toString();return await fetchArchiveResponse(redirectedUrl,signal,redirects+1)};var decodeArchiveEndpointFailure=async(response)=>{const body=await response.json().catch(()=>null);if(body===null){return}try{return decodeUnknownSync(BaselineArchiveEndpointFailure)(body)}catch{return}};var bundledFallbackEligible=(cause)=>cause instanceof BaselineArchiveUnavailableError||isTimeoutError2(cause)||cause instanceof BaselineUnavailable&&bundledFallbackAvailability.has(cause.availability)||cause instanceof ControlPlaneRequestFailure&&cause.transport;var classifyFailure=(cause)=>{let reason="invalid-artifact";if(cause instanceof BaselineIntegrityFailure){reason="corrupt-artifact"}else if(bundledFallbackEligible(cause)){reason="remote-access"}return new BaselineResolutionFailure({cause,message:baselineFailureMessage(cause),operation:"resolve-stable-baseline",reason})};var extractSafeTgz=(archivePath,targetDirectory)=>{const entries=execFileSync5("tar",["-tzf",archivePath],{encoding:"utf-8"}).split(/\r?\n/u).filter(Boolean);const unsafe=entries.find((entry)=>!isSafeTarPath(entry));if(unsafe!==undefined){throw new Error(`Unsafe path in baseline archive: ${unsafe}`)}mkdirSync4(targetDirectory,{recursive:true});execFileSync5("tar",["-xzf",archivePath,"-C",targetDirectory],{stdio:"ignore"})};var download=async(url,targetPath,timeoutMs)=>{const controller=new AbortController;const timeout3=setTimeout(()=>{controller.abort()},timeoutMs);try{const response=await fetchArchiveResponse(parseArchiveUrl(url).toString(),controller.signal);if(!response.ok){const endpointFailure=await decodeArchiveEndpointFailure(response);if(endpointFailure!==undefined){if(endpointFailure instanceof BaselineUnavailable&&response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw endpointFailure}if(response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw new BaselineArchiveUnavailableError(`Failed to download baseline artifact: ${response.status}`)}const bytes=await response.arrayBuffer().catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to read baseline artifact response.",{cause:error2})});writeFileSync4(targetPath,new Uint8Array(bytes))}finally{clearTimeout(timeout3)}};var summaryMetadata=(resolution,retrieval)=>({authoritySource:resolution.source,channel:resolution.requested.channel,commit:null,compatibility:resolution.compatibility,digest:resolution.digest,provenance:resolution.provenance,requested:resolution.requested,resolvedVersion:resolution.resolvedVersion,retrieval,sha256:resolution.digest,source:"remote",tag:isBaselineReleaseTag(resolution.provenance)?resolution.provenance:null,version:resolution.resolvedVersion});var decodeLocalCompatibility=(metadata)=>{if(!Object.hasOwn(metadata,"compatibility")){return"*"}const{compatibility}=metadata;if(typeof compatibility!=="object"||compatibility===null||!("cliVersionRange"in compatibility)){throw new Error("Local baseline metadata has invalid CLI compatibility.")}const{cliVersionRange}=compatibility;if(typeof cliVersionRange!=="string"||cliVersionRange.trim().length===0){throw new Error("Local baseline metadata has invalid CLI compatibility.")}return cliVersionRange};var resolveLocalBaseline=(url,request)=>{if(!url.startsWith("file://")){return null}const root=fileURLToPath2(new URL(url));const metadata=decodeUnknownSync(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync8(path18.join(root,"baseline.json"),"utf-8")));if(typeof metadata.version!=="string"||metadata.version.length===0){throw new Error("Local baseline metadata has no version.")}const cliVersionRange=decodeLocalCompatibility(metadata);if(metadata.tag!==undefined&&metadata.tag!==null&&typeof metadata.tag!=="string"){throw new Error("Local baseline metadata has an invalid tag.")}if(metadata.commit!==undefined&&metadata.commit!==null&&typeof metadata.commit!=="string"){throw new Error("Local baseline metadata has an invalid commit.")}const tag4=metadata.tag??null;const commit=metadata.commit??null;const digest3=digestContentRoots([{prefix:"baseline",root}]);if(request.version!==undefined&&request.version!==metadata.version){throw new BaselineIntegrityFailure({expectedDigest:digest3,message:"Local baseline metadata does not match the exact requested version.",request,resolvedVersion:metadata.version})}if(!satisfiesCliCompatibilityRange(cliVersionRange,version2)){throw new BaselineIntegrityFailure({expectedDigest:digest3,message:`Local baseline requires CLI ${cliVersionRange}; current CLI is ${version2}.`,request,resolvedVersion:metadata.version})}return loadBaselineFromDirectory(root,{authoritySource:"local",channel:request.channel,commit,compatibility:{cliVersionRange},digest:digest3,provenance:tag4??"local-file",requested:request,resolvedVersion:metadata.version,retrieval:"available",sha256:digest3,source:"local",tag:tag4,version:metadata.version})};var loadExactCachedBaseline=(targetDirectory,resolution)=>{if(!existsSync7(targetDirectory)){return{baseline:null}}try{if(!existsSync7(path18.join(targetDirectory,"baseline.json"))){throw integrityFailure(resolution,"Cached baseline is incomplete.")}const artifactPath=path18.join(targetDirectory,cachedArtifactName);if(!existsSync7(artifactPath)||sha256File(artifactPath)!==resolution.digest){throw integrityFailure(resolution,"Cached artifact does not match authority.")}const verificationDirectory=mkdtempSync(path18.join(tmpdir4(),"punks-cache-verify-"));try{extractSafeTgz(artifactPath,verificationDirectory);const expected=digestContentRoots([{prefix:"baseline",root:verificationDirectory}]);const actual=digestContentRoots([{include:(relativePath)=>relativePath!==cachedArtifactName,prefix:"baseline",root:targetDirectory}]);if(actual!==expected){throw integrityFailure(resolution,"Cached baseline content changed.")}verifyEmbeddedBaselineMetadata(targetDirectory,resolution,"Cached")}finally{rmSync(verificationDirectory,{force:true,recursive:true})}return{baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"cached"))}}catch(error2){rmSync(targetDirectory,{force:true,recursive:true});return{baseline:null,integrityFailure:error2 instanceof BaselineIntegrityFailure?error2:integrityFailure(resolution,"Cached baseline failed integrity verification.")}}};var materializeBaseline=async(resolution,refresh,timeoutMs,cacheDirectory)=>{if(resolution.source!=="control-plane"){throw integrityFailure(resolution,"Baseline authority source must be control-plane.")}if(!isSafePathSegment(resolution.resolvedVersion)){throw integrityFailure(resolution,"Authority returned an unsafe baseline version.")}parseArchiveUrl(resolution.archive.url);if(!satisfiesCliCompatibilityRange(resolution.compatibility.cliVersionRange,version2)){throw integrityFailure(resolution,`Baseline requires CLI ${resolution.compatibility.cliVersionRange}; current CLI is ${version2}.`)}const targetDirectory=path18.join(cacheDirectory,"devpunks","baselines","verified",resolution.resolvedVersion);const targetParentDirectory=path18.dirname(targetDirectory);let cacheIntegrityFailure;if(!refresh){const cached3=loadExactCachedBaseline(targetDirectory,resolution);if(cached3.baseline!==null){return{artifactPulled:false,baseline:cached3.baseline}}cacheIntegrityFailure=cached3.integrityFailure}mkdirSync4(targetParentDirectory,{recursive:true});const temporaryDirectory=mkdtempSync(path18.join(targetParentDirectory,".punks-verified-baseline-"));try{const archivePath=path18.join(temporaryDirectory,assetArchiveName);await download(resolution.archive.url,archivePath,timeoutMs).catch((error2)=>{if(cacheIntegrityFailure!==undefined&&bundledFallbackEligible(error2)){throw cacheIntegrityFailure}if(error2 instanceof Error){throw error2}throw new Error("Baseline archive download failed.")});const actualDigest=sha256File(archivePath);if(actualDigest!==resolution.digest||actualDigest!==resolution.archive.sha256){throw integrityFailure(resolution,"Downloaded baseline archive checksum mismatch.",actualDigest)}const extractedDirectory=path18.join(temporaryDirectory,"extracted");extractSafeTgz(archivePath,extractedDirectory);verifyEmbeddedBaselineMetadata(extractedDirectory,resolution,"Downloaded");rmSync(targetDirectory,{force:true,recursive:true});renameSync2(extractedDirectory,targetDirectory);copyFileSync(archivePath,path18.join(targetDirectory,cachedArtifactName));return{artifactPulled:true,baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"retrieved"))}}finally{rmSync(temporaryDirectory,{force:true,recursive:true})}};var resolveBaseline=(options4)=>gen2(function*executeBaselineResolution(){const selectedBaseline=options4.baseline??options4.configuration.release.baseline;const request=normalizeBaselineRequest(selectedBaseline);const isImplicitStable=selectedBaseline===undefined;if(request.channel==="bundled"){return yield*try_3({catch:classifyFailure,try:resolveVerifiedBundledBaseline})}const local=yield*try_3({catch:classifyFailure,try:()=>options4.configuration.release.baselineUrl===undefined?null:resolveLocalBaseline(options4.configuration.release.baselineUrl,request)});if(local!==null){return local}return yield*gen2(function*resolveRemoteBaseline(){const baseUrl2=resolveControlPlaneUrl(undefined,options4.configuration.controlPlane);if(baseUrl2===undefined){return yield*fail6(classifyFailure(new BaselineUnavailable({availability:"authority-unconfigured",message:"The control plane URL is unavailable; baseline authority cannot be resolved.",request})))}const timeoutMs=options4.timeoutMs??defaultRemoteBaselineTimeoutMs;const resolution=yield*resolveBaselineMetadata({baseUrl:baseUrl2,request}).pipe(timeout2(timeoutMs),mapError3(classifyFailure));const materialized=yield*tryPromise2({catch:classifyFailure,try:async()=>await materializeBaseline(resolution,options4.refresh??options4.configuration.release.refreshBaseline,timeoutMs,options4.configuration.release.cacheDirectory)});if(materialized.artifactPulled){yield*submitCliEventEffect("cli.artifact.pull.completed",{...options4.cwd===undefined?{}:{cwd:options4.cwd},baseline:{channel:materialized.baseline.summary.channel,version:materialized.baseline.summary.version},configuration:options4.configuration.controlPlane})}return materialized.baseline}).pipe(catchTag2("@punks/cli/baseline-resolution/BaselineResolutionFailure",(failure)=>isImplicitStable&&bundledFallbackEligible(failure.cause)?try_3({catch:classifyFailure,try:()=>resolveVerifiedBundledBaseline(request,"fallback")}):fail6(failure)))});var baselineResolveOptions=(baseline,refresh,cwd,configuration)=>{const selectedBaseline=isSome2(baseline)?baseline.value:configuration.release.baseline;return{...selectedBaseline===undefined?{}:{baseline:selectedBaseline},configuration,refresh:refresh||configuration.release.refreshBaseline,...cwd===undefined?{}:{cwd}}};class ScopedScaffoldOperationFailure extends TaggedErrorClass()("ScopedScaffoldOperationFailure",{cause:Defect(),message:String4,operation:Literals(["inspect","materialize","plan"])}){}var ScopedScaffoldOperation=Service("@punks/cli/scaffold-operation/ScopedScaffoldOperation");import path19 from"node:path";var baselineToolIds2=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills2=(skillIds,baseline=bundledBaseline)=>[...new Set([...baselineToolIds2,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var defaultPackIds2=defaultPackIdsForBaseline();var detectedPackIds2=detectedPackIdsForBaseline();var knownPackIds2=knownPackIdsForBaseline();var languagePackIds2=languagePackIdsForBaseline();var surfacePackIds2=surfacePackIdsForBaseline();var packRegistryForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map(({id,category,triggerPackages,description})=>({category,description,id,triggerPackages}));var packRegistry=packRegistryForBaseline();class UnknownPackIds extends TaggedErrorClass()("@punks/cli/repository-analysis/UnknownPackIds",{cause:Defect(),invalidPackIds:ArraySchema(String4),operation:Literal2("validate-pack-selection")}){}class RepositoryScanError extends TaggedErrorClass("@punks/cli/features/repository-analysis/RepositoryScanError")("RepositoryScanError",{cause:Defect(),operation:Literal2("scan-repository"),rootDirectory:String4}){}var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var pathSegments=(relativePath)=>relativePath.split(/[\\/]+/u);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>{const relativePath=pathSegments(manifest.relativePath).join("/");return![...wikiRootPaths].some((wikiRoot)=>relativePath===wikiRoot||relativePath.startsWith(`${wikiRoot}/`))});var hasFrontendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="nextjs"||technology==="react");var backendWorkspacePathSegments=new Set(["api","backend","server","services"]);var backendPackageNameSegments=new Set(["api","backend","server","service"]);var hasBackendWorkspaceName=(manifest)=>{const workspaceSegments=pathSegments(manifest.relativePath).slice(0,-1);if(workspaceSegments.some((segment)=>backendWorkspacePathSegments.has(segment))){return true}if(manifest.packageName===undefined||manifest.packageName===null||manifest.packageName.length===0){return false}const packageNameSegments=manifest.packageName.replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).filter((segment)=>segment.length>0).map((segment)=>segment.toLowerCase());return packageNameSegments.some((segment)=>backendPackageNameSegments.has(segment))};var hasBackendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="better-auth"||technology==="drizzle"||technology==="elysia"||technology==="trpc")||result4.manifests.some(hasBackendWorkspaceName);var detectionToPackId={"better-auth":"better-auth",drizzle:"drizzle",effect:"effect",elysia:"elysia",nextjs:"nextjs",react:"react","tanstack-query":"tanstack-query",trpc:"trpc",turborepo:"turborepo"};var toSortedUnique=(values)=>[...new Set(values)].toSorted();var isDetectedLanguage=(value5)=>value5==="python"||value5==="typescript";var detectLanguagePacks=(detection,baseline)=>{const packages=new Set(packDetectionManifests(detection.manifests).flatMap((manifest)=>manifest.dependencies));const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="language").filter((pack)=>isDetectedLanguage(pack.id)&&detection.detectedLanguages.includes(pack.id)||pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id).filter((packId)=>languagePackIdsForBaseline(baseline).includes(packId))};var detectSurfacePacks=(detection,baseline)=>[...hasBackendSurface(detection)?["backend"]:[],...hasFrontendSurface(detection)?["frontend"]:[]].filter((packId)=>surfacePackIdsForBaseline(baseline).includes(packId));var detectPackageTriggeredPacks=(detection,baseline)=>{const packages=new Set([...packDetectionManifests(detection.manifests).flatMap((manifest)=>manifest.dependencies),...detection.detectedPackages??[]]);const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="detected").filter((pack)=>pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id)};var resolvePackSelection=(detection,baseline=bundledBaseline)=>{const languagePacks=detectLanguagePacks(detection,baseline);const technologyPacks=detection.detectedTechnologies.flatMap((technology)=>{const packId=detectionToPackId[technology];return packId===undefined?[]:[packId]}).filter((packId)=>knownPackIdsForBaseline(baseline).includes(packId));const packageTriggeredPacks=detectPackageTriggeredPacks(detection,baseline);const surfacePacks=detectSurfacePacks(detection,baseline);const defaultPackIds3=defaultPackIdsForBaseline(baseline);const knownPackIds3=knownPackIdsForBaseline(baseline);const detectedPacks=toSortedUnique([...technologyPacks,...packageTriggeredPacks]);const preselectedPacks=toSortedUnique([...defaultPackIds3,...languagePacks,...detectedPacks,...surfacePacks]);const optionalPacks=knownPackIds3.filter((packId)=>!preselectedPacks.includes(packId));return{defaultPacks:defaultPackIds3,detectedPacks:toSortedUnique(detectedPacks),languagePacks:toSortedUnique(languagePacks),optionalPacks,preselectedPacks,surfacePacks:toSortedUnique(surfacePacks)}};var finalizePackSelection=(resolved,additions,removals)=>{const withAdditions=new Set([...resolved.preselectedPacks,...additions]);for(const removal of removals){if(resolved.defaultPacks.includes(removal)){continue}withAdditions.delete(removal)}return[...withAdditions].toSorted()};var canRemovePack=(resolved,packId)=>resolved.preselectedPacks.includes(packId)&&!resolved.defaultPacks.includes(packId);var inspectRepository=fn2("RepositoryAnalysis.inspect")(function*inspectRepository2({baseline,repoShapeMode,rootDirectory,scanner}){const scanned=yield*scanner.scan(rootDirectory);const detection=repoShapeMode==="auto"?scanned:{...scanned,monorepo:repoShapeMode==="monorepo"};return{detection,packs:resolvePackSelection(detection,baseline)}});var scaffoldValidationError=(cause,fallback)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:fallback});var selectedSkills=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var deepFreeze=(value5)=>{if(typeof value5!=="object"||value5===null||Object.isFrozen(value5)){return value5}for(const nested of Object.values(value5)){deepFreeze(nested)}return Object.freeze(value5)};var operationFailure=(cause)=>{if(cause instanceof ScopedScaffoldOperationFailure){return scaffoldValidationError(cause.cause,cause.message)}return cause};var runScaffold=({scanDirectory,emitJson=false,repoShapeMode="auto",interaction,outputDirectory,displayOutputDirectory,ensureTools:ensureTools2=true,baseline=bundledBaseline,assumeYes=false,toolStdio=emitJson?"ignore":"inherit",toolRuntime,clipboardRuntime,configuration={disableBundledUrl:true},scriptRuntimePath,scriptEnvironment})=>gen2(function*executeScaffold(){const resolvedOutputDirectory=path19.resolve(outputDirectory??scanDirectory);const ownedBaseline=deepFreeze(structuredClone(baseline));const capabilities=yield*ScaffoldCapabilities;const operation=yield*ScopedScaffoldOperation;const inspection=yield*operation.inspect({baseline:ownedBaseline,outputDirectory:resolvedOutputDirectory,repoShapeMode,scanDirectory}).pipe(mapError3(operationFailure));const{detection,packs:resolved}=inspection;const ownedResolved=structuredClone(resolved);for(const packIds of Object.values(ownedResolved)){Object.freeze(packIds)}Object.freeze(ownedResolved);const effectiveScriptRuntimePath=scriptRuntimePath??capabilities.scriptRuntimePath;const effectiveScriptEnvironment=scriptEnvironment??capabilities.scriptEnvironment;const baseRequiredTools=requiredToolsForSkills2([],ownedBaseline);let toolBootstrapStatuses=[];yield*interaction.emit({_tag:"SetupStarted"});if(ensureTools2&&baseRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"base",toolIds:baseRequiredTools});toolBootstrapStatuses=capabilities.ensureTools(baseRequiredTools,ownedBaseline,toolRuntime,{stdio:toolStdio});yield*interaction.emit({_tag:"ToolBootstrap",phase:"base",statuses:toolBootstrapStatuses})}yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"ResolvedPacks",baseline:ownedBaseline,resolved:ownedResolved});let additions=Object.freeze([]);let removals=Object.freeze([]);let finalPacks=ownedResolved.preselectedPacks;const selectPacksInteractively=()=>gen2(function*selectScaffoldPacks(){while(true){const shouldEditSelection=!(yield*interaction.keepPrefilledSelection());additions=Object.freeze([]);if(shouldEditSelection&&ownedResolved.optionalPacks.length>0){additions=Object.freeze([...yield*interaction.selectPacks({allowed:ownedResolved.optionalPacks,kind:"add"})])}const removablePacks=[...new Set([...ownedResolved.preselectedPacks,...additions])].filter((packId)=>canRemovePack(ownedResolved,packId)).toSorted();removals=Object.freeze([]);if(shouldEditSelection&&removablePacks.length>0){removals=Object.freeze([...yield*interaction.selectPacks({allowed:removablePacks,kind:"remove"})])}finalPacks=Object.freeze(finalizePackSelection(ownedResolved,additions,removals));if(shouldEditSelection){yield*interaction.emit({_tag:"SelectionPreview",addedPacks:additions,baseline:ownedBaseline,finalPacks,outputDirectory:resolvedOutputDirectory,preselectedPacks:ownedResolved.preselectedPacks,removedPacks:removals})}if(yield*interaction.confirmSelection()){return}yield*interaction.emit({_tag:"SelectionReopened"})}});yield*assumeYes?interaction.emit({_tag:"SelectionAccepted"}):selectPacksInteractively();const skillIds=selectedSkills(finalPacks,ownedBaseline);const requiredTools=requiredToolsForSkills2(skillIds,ownedBaseline);const checkedToolIds=new Set(toolBootstrapStatuses.map((entry)=>entry.toolId));const remainingRequiredTools=requiredTools.filter((toolId)=>!checkedToolIds.has(toolId));if(ensureTools2&&remainingRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"selected",toolIds:remainingRequiredTools});const remainingToolBootstrapStatuses=capabilities.ensureTools(remainingRequiredTools,ownedBaseline,toolRuntime,{stdio:toolStdio});toolBootstrapStatuses=[...toolBootstrapStatuses,...remainingToolBootstrapStatuses].toSorted((left,right)=>left.toolId.localeCompare(right.toolId));yield*interaction.emit({_tag:"ToolBootstrap",phase:"selected",statuses:remainingToolBootstrapStatuses})}const plan=yield*operation.plan({_tag:"PlanRepositoryScaffold",addedPacks:additions,...displayOutputDirectory===undefined?{}:{displayOutputDirectory},finalPacks,inspection,removedPacks:removals,requiredTools,scriptEnvironment:effectiveScriptEnvironment,scriptRuntimePath:effectiveScriptRuntimePath,toolBootstrapStatuses}).pipe(mapError3(operationFailure));const materialized=yield*operation.materialize(plan).pipe(mapError3(operationFailure));if(materialized._tag!=="MaterializedRepositoryScaffold"){return yield*new CliValidationError({message:"Repository scaffold operation returned staged materialization."})}const{agentSystemPrompt,result:result4}=materialized;const clipboardResult=capabilities.copyToClipboard(agentSystemPrompt,{...clipboardRuntime,env:clipboardRuntime?.env??effectiveScriptEnvironment});const completionResult=deepFreeze(structuredClone(result4));yield*interaction.emit({_tag:"SetupComplete",baseline:ownedBaseline,clipboard:clipboardResult,emitJson,result:completionResult});yield*submitCliEventEffect("cli.scaffold.setup.completed",{baseline:{version:ownedBaseline.summary.version},configuration,cwd:scanDirectory});return result4});import{execFileSync as execFileSync6}from"node:child_process";import{existsSync as existsSync8,lstatSync as lstatSync3,readFileSync as readFileSync9,realpathSync as realpathSync4}from"node:fs";import path21 from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{spawn as spawn2}from"node:child_process";import{lstatSync as lstatSync2,mkdtempSync as mkdtempSync2,readlinkSync as readlinkSync2,realpathSync as realpathSync3,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir5}from"node:os";import path20 from"node:path";import{createInterface as createInterface3}from"node:readline";var isOutsideRoot=(relativePath)=>relativePath===".."||relativePath.startsWith(`..${path20.sep}`)||path20.isAbsolute(relativePath);class ConfinedArchiveRecoveryError extends Error{_tag="ConfinedArchiveRecoveryError";evidence;constructor({cause,evidence}){super(`Confined archive replacement could not restore ${evidence.targetPath}. Retained archive: ${evidence.archivePath}.`,{cause});this.name="ConfinedArchiveRecoveryError";this.evidence=evidence}}var unsafeParentError=(directoryPath)=>new CliValidationError({message:`Refusing to mutate scaffold content through changed parent ${directoryPath}.`});var captureLeafExpectation=(targetPath)=>{const target=lstatSync2(targetPath,{throwIfNoEntry:false});if(target===undefined){return{kind:"absent"}}let kind="other";if(target.isSymbolicLink()){kind="symlink"}else if(target.isFile()){kind="file"}else if(target.isDirectory()){kind="directory"}return{device:target.dev,inode:target.ino,kind}};var confinedMutationScript=String.raw`
309
309
  import { createHash } from "node:crypto";
310
310
  import {
311
311
  closeSync,
@@ -2451,7 +2451,7 @@ When the generated init output matches the repo, the next CLI step is:
2451
2451
  - \`hi scaffold\``,skills:["docs-onboarding","requirements-grill","write-backlog","create-spec"],summary:"Docs onboarding, requirements grill, spec reconstruction, backlog authoring, and wiki docs seed."}];var stageScaffoldById={init:stageScaffoldCatalog[0]};import path22 from"node:path";var harnessDirectories=new Set([".agents",".claude",".codex",".cursor",".opencode"]);var normalizeGitignorePattern=(line)=>{const trimmed=line.trim();if(trimmed===""||trimmed.startsWith("#")||trimmed.startsWith("!")){return null}return trimmed.replace(/^\//u,"").replace(/\/\*\*?$/u,"").replace(/\/$/u,"")};var isHarnessDirectoryIgnore=(line)=>{const normalized=normalizeGitignorePattern(line);return normalized!==null&&harnessDirectories.has(normalized)};var removeHarnessDirectoriesFromGitignore=async(rootDirectory,writer,session)=>{const gitignorePath=path22.join(rootDirectory,".gitignore");assertConfinedWrite({outputDirectory:rootDirectory,...session===undefined?{}:{session},targetPath:gitignorePath});const originalBytes=await readConfinedRegularFile({allowMissing:true,outputDirectory:rootDirectory,...session===undefined?{}:{session},targetPath:gitignorePath});if(originalBytes===null){return{gitignorePath,removedPatterns:[]}}const original=originalBytes.toString("utf-8");const hadFinalNewline=original.endsWith(`
2452
2452
  `);const removedPatterns=[];const keptLines=original.split(/\r?\n/u).filter((line,index,lines2)=>{if(index===lines2.length-1&&line===""){return false}if(!isHarnessDirectoryIgnore(line)){return true}removedPatterns.push(line.trim());return false});if(removedPatterns.length===0){return{gitignorePath,removedPatterns}}const write2=writer??(async({content,gitignorePath:targetPath})=>{await writeConfinedFile({content,outputDirectory:rootDirectory,replace:true,...session===undefined?{}:{session},targetPath})});await write2({content:`${keptLines.join(`
2453
2453
  `)}${hadFinalNewline?`
2454
- `:""}`,gitignorePath});return{gitignorePath,removedPatterns}};class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String4}){}var ScaffoldApplicationItem=Literals(["dependency","file","receipt","structured-entry"]);var ScaffoldApplicationOperation=Literals(["create","persist","remove","update"]);class ScaffoldApplicationFailure extends TaggedErrorClass()("@punks/cli/scaffold-state/ScaffoldApplicationFailure",{cause:Defect(),identity:String4,item:ScaffoldApplicationItem,message:String4,operation:ScaffoldApplicationOperation}){}var isScaffoldApplicationResult=(input2)=>typeof input2==="object"&&input2!==null&&("outcomes"in input2)&&Array.isArray(input2.outcomes)&&("receipt"in input2)&&typeof input2.receipt==="object"&&input2.receipt!==null&&("receiptPersisted"in input2)&&typeof input2.receiptPersisted==="boolean";var ScaffoldApplicationResultSchema=declare(isScaffoldApplicationResult,{identifier:"ScaffoldApplicationResult"});class ScaffoldApplicationFailures extends TaggedErrorClass()("@punks/cli/scaffold-state/ScaffoldApplicationFailures",{cause:Defect(),failures:ArraySchema(ScaffoldApplicationFailure),message:String4,operation:Literal2("apply-reconciliation"),partialResult:ScaffoldApplicationResultSchema}){}var desiredScaffoldStateConflict=({identity:identity3,item})=>({_tag:"DesiredScaffoldStateConflict",identity:identity3,item,message:`Desired scaffold state contains duplicate ${item} identity: ${identity3}`});var compare=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var dependencyIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredEntryIdentity=({file:file5,kind,path:path23})=>JSON.stringify([file5,kind,path23]);var advanceManagedScaffoldReceipt=({degradations,priorReceipt,successes})=>{const dependencies=new Map(priorReceipt.dependencies.map((entry)=>[dependencyIdentity(entry),entry]));const files=new Map(priorReceipt.files.map((entry)=>[entry.path,entry]));const structuredEntries=new Map(priorReceipt.structuredEntries.map((entry)=>[structuredEntryIdentity(entry),entry]));for(const success of successes){if(success.item==="dependency"){if(success.receiptEntry===null){dependencies.delete(success.identity)}else{dependencies.set(success.identity,success.receiptEntry.entry)}}else if(success.item==="file"){if(success.receiptEntry===null){files.delete(success.identity)}else{files.set(success.identity,success.receiptEntry.entry)}}else if(success.receiptEntry===null){structuredEntries.delete(success.identity)}else{structuredEntries.set(success.identity,success.receiptEntry.entry)}}return{degradations:[...degradations].toSorted((left,right)=>compare(left.identity,right.identity)),dependencies:[...dependencies.values()].toSorted((left,right)=>compare(dependencyIdentity(left),dependencyIdentity(right))),files:[...files.values()].toSorted((left,right)=>compare(left.path,right.path)),structuredEntries:[...structuredEntries.values()].toSorted((left,right)=>compare(structuredEntryIdentity(left),structuredEntryIdentity(right))),version:"1"}};var planningFailureItem=(source)=>{if(source._tag==="DesiredProjectionReconciliationFailure"){return"projection"}if(source._tag==="CrossFamilyScaffoldOwnershipFailure"){return"ownership"}return source.item};var scaffoldReconciliationPlanOutcomes=(plan)=>[...plan.skips.map((source)=>({_tag:"ScaffoldEntrySkipped",identity:source.identity,item:source.item})),...plan.degradations.map((source)=>({_tag:"ScaffoldDegradationRecorded",identity:source.identity,item:"projection",status:source.status})),...plan.conflicts.map((source)=>({_tag:"ScaffoldConflictPreserved",identity:source.identity,item:source.item,message:source.message,operation:source.operation})),...plan.failures.map((source)=>({_tag:"ScaffoldPlanningFailed",identity:source.identity,item:planningFailureItem(source),message:source.message}))];var itemRank={dependency:0,file:1,"structured-entry":2};var compare2=(left,right)=>{if(left<right){return-1}if(left>right){return 1}return 0};var actionReferenceKey=({identity:identity3,item})=>JSON.stringify([item,identity3]);var operation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}if(action2._tag==="SafeUpdateScaffoldEntry"){return"update"}if(action2._tag==="ArchiveAndReplaceScaffoldFile"){return"update"}return"remove"};var messageFromCause=(cause)=>cause instanceof Error?cause.message:"Scaffold application operation failed.";var actionFailure=(action2,cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:action2.item,message:messageFromCause(cause),operation:operation(action2)});var failureOutcome=(failure)=>({_tag:"ScaffoldActionFailed",failure,identity:failure.identity,item:failure.item,message:failure.message,operation:failure.operation});var applyAction=(adapters,action2)=>{if(action2._tag==="ArchiveAndReplaceScaffoldFile"){const apply2=adapters.archiveAndReplaceFile;const application=apply2===undefined?fail6(actionFailure(action2,new Error("Fixed managed recovery applicator is unavailable."))):apply2(action2);return application.pipe(tap2(()=>adapters.verifyFile?.(action2)??void_3),map6((observed)=>({identity:action2.identity,item:action2.item,receiptEntry:{entry:{...action2.desired.obligation===undefined?{}:{obligation:action2.desired.obligation},...action2.desired.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:action2.desired.sharedPromptIdentity},kind:action2.desired.kind,mode:observed.mode,ownership:{_tag:"ScaffoldManaged"},path:action2.identity,sha256:observed.sha256,type:observed.type},item:"file"}})))}if(action2.item==="dependency"){return adapters.applyDependency(action2).pipe(map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"dependency"}})))}if(action2.item==="file"){return adapters.applyFile(action2).pipe(tap2(()=>adapters.verifyFile?.(action2)??void_3),map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"file"}})))}return adapters.applyStructuredEntry(action2).pipe(map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"structured-entry"}})))};var applyScaffoldReconciliation=fn2("ScaffoldState.applyReconciliation")(function*applyReconciliation({adapters,plan,priorReceipt}){const failures=[];const outcomes=[...scaffoldReconciliationPlanOutcomes(plan)];const successes=plan.skips.map((skip)=>{if(skip.item==="dependency"){return{identity:skip.identity,item:"dependency",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"dependency"}}}if(skip.item==="file"){return{identity:skip.identity,item:"file",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"file"}}}return{identity:skip.identity,item:"structured-entry",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"structured-entry"}}});const dependenciesByAction=new Map;for(const dependency of plan.dependencies){const key=actionReferenceKey(dependency.action);dependenciesByAction.set(key,[...dependenciesByAction.get(key)??[],dependency])}const sortedActions=[...plan.actions].toSorted((left,right)=>itemRank[left.item]-itemRank[right.item]||compare2(left.identity,right.identity));const actionsByKey=new Map(sortedActions.map((action2)=>[actionReferenceKey(action2),action2]));const actions=[];const ordered=new Set;const ordering=new Set;const orderAction=(action2)=>{const key=actionReferenceKey(action2);if(ordered.has(key)||ordering.has(key)){return}ordering.add(key);for(const{prerequisite}of dependenciesByAction.get(key)??[]){const prerequisiteAction=actionsByKey.get(actionReferenceKey(prerequisite));if(prerequisiteAction!==undefined){orderAction(prerequisiteAction)}}ordering.delete(key);ordered.add(key);actions.push(action2)};for(const action2 of sortedActions){orderAction(action2)}const failedActions=new Set;for(const action2 of actions){const blockedBy=(dependenciesByAction.get(actionReferenceKey(action2))??[]).map(({prerequisite})=>prerequisite).filter((prerequisite)=>failedActions.has(actionReferenceKey(prerequisite)));if(blockedBy.length>0){failedActions.add(actionReferenceKey(action2));outcomes.push({_tag:"ScaffoldActionBlocked",blockedBy,identity:action2.identity,item:action2.item,message:`Scaffold action was blocked by ${blockedBy.map(({identity:identity3})=>identity3).join(", ")}.`,operation:operation(action2)});continue}const applied=yield*applyAction(adapters,action2).pipe(result2);if(isSuccess2(applied)){successes.push(applied.success);outcomes.push({_tag:"ScaffoldActionSucceeded",identity:action2.identity,item:action2.item,operation:operation(action2)})}else{failedActions.add(actionReferenceKey(action2));failures.push(applied.failure);outcomes.push(failureOutcome(applied.failure))}}const receipt=advanceManagedScaffoldReceipt({degradations:plan.degradations,priorReceipt,successes});const persisted=yield*adapters.persistReceipt(receipt).pipe(result2);let receiptPersisted=true;if(isFailure2(persisted)){failures.push(persisted.failure);outcomes.push(failureOutcome(persisted.failure));receiptPersisted=false}const partialResult={outcomes,receipt,receiptPersisted};if(failures.length>0){const[firstFailure]=failures;return yield*new ScaffoldApplicationFailures({cause:failures.length===1&&firstFailure!==undefined?firstFailure.cause:failures,failures,message:`${failures.length} scaffold application operation${failures.length===1?"":"s"} failed.`,operation:"apply-reconciliation",partialResult})}return partialResult});var producerContracts={baseline:["scaffold","managed-bytes"],"context-plan":["scaffold","managed-bytes"],"harness-projection":["mixed","structured-entries"],lint:["scaffold","managed-bytes"],"project-local-skill":["repository","authored-content"],"project-settings":["mixed","structured-entries"],prompt:["repository","authored-content"],"scaffold-handoff":["scaffold","managed-bytes"],"scaffold-manifest":["scaffold","managed-bytes"],"source-guide":["scaffold","managed-bytes"],subagent:["repository","authored-content"]};var producerObligation=(producer,dependencies=[])=>{const contract=Object.entries(producerContracts).find(([name2])=>name2===producer)?.[1];return{contentAuthority:contract?.[0]??"unknown",dependencies,presence:"required",producer,validity:contract?.[1]??"authored-content"}};var legacyArtifactObligation=(artifactPath)=>{switch(artifactPath){case"AGENTS.md":{return producerObligation("prompt")}case".agents/AGENTS.md":{return producerObligation("baseline")}case".devpunks/context-plan.json":{return producerObligation("context-plan")}case".devpunks/settings.json":{return producerObligation("project-settings")}default:{return producerObligation("undeclared-artifact")}}};import{createHash as createHash6}from"node:crypto";var encodePrettyJson2=(value5)=>`${JSON.stringify(value5,null,2)}
2454
+ `:""}`,gitignorePath});return{gitignorePath,removedPatterns}};class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String4}){}var ScaffoldApplicationItem=Literals(["dependency","file","receipt","structured-entry"]);var ScaffoldApplicationOperation=Literals(["create","persist","remove","update"]);class ScaffoldApplicationFailure extends TaggedErrorClass()("@punks/cli/scaffold-state/ScaffoldApplicationFailure",{cause:Defect(),identity:String4,item:ScaffoldApplicationItem,message:String4,operation:ScaffoldApplicationOperation}){}var isScaffoldApplicationResult=(input2)=>typeof input2==="object"&&input2!==null&&("outcomes"in input2)&&Array.isArray(input2.outcomes)&&("receipt"in input2)&&typeof input2.receipt==="object"&&input2.receipt!==null&&("receiptPersisted"in input2)&&typeof input2.receiptPersisted==="boolean";var ScaffoldApplicationResultSchema=declare(isScaffoldApplicationResult,{identifier:"ScaffoldApplicationResult"});class ScaffoldApplicationFailures extends TaggedErrorClass()("@punks/cli/scaffold-state/ScaffoldApplicationFailures",{cause:Defect(),failures:ArraySchema(ScaffoldApplicationFailure),message:String4,operation:Literal2("apply-reconciliation"),partialResult:ScaffoldApplicationResultSchema}){}var desiredScaffoldStateConflict=({identity:identity3,item})=>({_tag:"DesiredScaffoldStateConflict",identity:identity3,item,message:`Desired scaffold state contains duplicate ${item} identity: ${identity3}`});var compare=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var dependencyIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredEntryIdentity=({file:file5,kind,path:path23})=>JSON.stringify([file5,kind,path23]);var advanceManagedScaffoldReceipt=({degradations,priorReceipt,successes})=>{const dependencies=new Map(priorReceipt.dependencies.map((entry)=>[dependencyIdentity(entry),entry]));const files=new Map(priorReceipt.files.map((entry)=>[entry.path,entry]));const structuredEntries=new Map(priorReceipt.structuredEntries.map((entry)=>[structuredEntryIdentity(entry),entry]));for(const success of successes){if(success.item==="dependency"){if(success.receiptEntry===null){dependencies.delete(success.identity)}else{dependencies.set(success.identity,success.receiptEntry.entry)}}else if(success.item==="file"){if(success.receiptEntry===null){files.delete(success.identity)}else{files.set(success.identity,success.receiptEntry.entry)}}else if(success.receiptEntry===null){structuredEntries.delete(success.identity)}else{structuredEntries.set(success.identity,success.receiptEntry.entry)}}return{degradations:[...degradations].toSorted((left,right)=>compare(left.identity,right.identity)),dependencies:[...dependencies.values()].toSorted((left,right)=>compare(dependencyIdentity(left),dependencyIdentity(right))),files:[...files.values()].toSorted((left,right)=>compare(left.path,right.path)),structuredEntries:[...structuredEntries.values()].toSorted((left,right)=>compare(structuredEntryIdentity(left),structuredEntryIdentity(right))),version:"1"}};var planningFailureItem=(source)=>{if(source._tag==="DesiredProjectionReconciliationFailure"){return"projection"}if(source._tag==="CrossFamilyScaffoldOwnershipFailure"){return"ownership"}return source.item};var scaffoldReconciliationPlanOutcomes=(plan)=>[...plan.skips.map((source)=>({_tag:"ScaffoldEntrySkipped",identity:source.identity,item:source.item})),...plan.degradations.map((source)=>({_tag:"ScaffoldDegradationRecorded",identity:source.identity,item:"projection",status:source.status})),...plan.conflicts.map((source)=>({_tag:"ScaffoldConflictPreserved",identity:source.identity,item:source.item,message:source.message,operation:source.operation})),...plan.failures.map((source)=>({_tag:"ScaffoldPlanningFailed",identity:source.identity,item:planningFailureItem(source),message:source.message}))];var itemRank={dependency:0,file:1,"structured-entry":2};var compare2=(left,right)=>{if(left<right){return-1}if(left>right){return 1}return 0};var actionReferenceKey=({identity:identity3,item})=>JSON.stringify([item,identity3]);var operation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}if(action2._tag==="SafeUpdateScaffoldEntry"){return"update"}if(action2._tag==="ArchiveAndReplaceScaffoldFile"){return"update"}return"remove"};var messageFromCause=(cause)=>cause instanceof Error?cause.message:"Scaffold application operation failed.";var actionFailure=(action2,cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:action2.item,message:messageFromCause(cause),operation:operation(action2)});var failureOutcome=(failure)=>({_tag:"ScaffoldActionFailed",failure,identity:failure.identity,item:failure.item,message:failure.message,operation:failure.operation});var applyAction=(adapters,action2)=>{if(action2._tag==="ArchiveAndReplaceScaffoldFile"){const apply2=adapters.archiveAndReplaceFile;const application=apply2===undefined?fail6(actionFailure(action2,new Error("Fixed managed recovery applicator is unavailable."))):apply2(action2);return application.pipe(tap2(()=>adapters.verifyFile?.(action2)??void_3),map6((observed)=>({identity:action2.identity,item:action2.item,receiptEntry:{entry:{...action2.desired.obligation===undefined?{}:{obligation:action2.desired.obligation},...action2.desired.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:action2.desired.sharedPromptIdentity},kind:action2.desired.kind,mode:observed.mode,ownership:{_tag:"ScaffoldManaged"},path:action2.identity,sha256:observed.sha256,type:observed.type},item:"file"}})))}if(action2.item==="dependency"){return adapters.applyDependency(action2).pipe(map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"dependency"}})))}if(action2.item==="file"){return adapters.applyFile(action2).pipe(tap2(()=>adapters.verifyFile?.(action2)??void_3),map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"file"}})))}return adapters.applyStructuredEntry(action2).pipe(map6((entry)=>({identity:action2.identity,item:action2.item,receiptEntry:entry===null?null:{entry,item:"structured-entry"}})))};var applyScaffoldReconciliation=fn2("ScaffoldState.applyReconciliation")(function*applyReconciliation({adapters,plan,priorReceipt}){const failures=[];const outcomes=[...scaffoldReconciliationPlanOutcomes(plan)];const successes=plan.skips.map((skip)=>{if(skip.item==="dependency"){return{identity:skip.identity,item:"dependency",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"dependency"}}}if(skip.item==="file"){return{identity:skip.identity,item:"file",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"file"}}}return{identity:skip.identity,item:"structured-entry",receiptEntry:skip.receiptEntry===null?null:{entry:skip.receiptEntry,item:"structured-entry"}}});const dependenciesByAction=new Map;for(const dependency of plan.dependencies){const key=actionReferenceKey(dependency.action);dependenciesByAction.set(key,[...dependenciesByAction.get(key)??[],dependency])}const sortedActions=[...plan.actions].toSorted((left,right)=>itemRank[left.item]-itemRank[right.item]||compare2(left.identity,right.identity));const actionsByKey=new Map(sortedActions.map((action2)=>[actionReferenceKey(action2),action2]));const actions=[];const ordered=new Set;const ordering=new Set;const orderAction=(action2)=>{const key=actionReferenceKey(action2);if(ordered.has(key)||ordering.has(key)){return}ordering.add(key);for(const{prerequisite}of dependenciesByAction.get(key)??[]){const prerequisiteAction=actionsByKey.get(actionReferenceKey(prerequisite));if(prerequisiteAction!==undefined){orderAction(prerequisiteAction)}}ordering.delete(key);ordered.add(key);actions.push(action2)};for(const action2 of sortedActions){orderAction(action2)}const failedActions=new Set;for(const action2 of actions){const blockedBy=(dependenciesByAction.get(actionReferenceKey(action2))??[]).map(({prerequisite})=>prerequisite).filter((prerequisite)=>failedActions.has(actionReferenceKey(prerequisite)));if(blockedBy.length>0){failedActions.add(actionReferenceKey(action2));outcomes.push({_tag:"ScaffoldActionBlocked",blockedBy,identity:action2.identity,item:action2.item,message:`Scaffold action was blocked by ${blockedBy.map(({identity:identity3})=>identity3).join(", ")}.`,operation:operation(action2)});continue}const applied=yield*applyAction(adapters,action2).pipe(result2);if(isSuccess2(applied)){successes.push(applied.success);outcomes.push({_tag:"ScaffoldActionSucceeded",identity:action2.identity,item:action2.item,operation:operation(action2)})}else{failedActions.add(actionReferenceKey(action2));failures.push(applied.failure);outcomes.push(failureOutcome(applied.failure))}}const receipt=advanceManagedScaffoldReceipt({degradations:plan.degradations,priorReceipt,successes});const persisted=yield*adapters.persistReceipt(receipt).pipe(result2);let receiptPersisted=true;if(isFailure2(persisted)){failures.push(persisted.failure);outcomes.push(failureOutcome(persisted.failure));receiptPersisted=false}const partialResult={outcomes,receipt,receiptPersisted};if(failures.length>0){const[firstFailure]=failures;return yield*new ScaffoldApplicationFailures({cause:failures.length===1&&firstFailure!==undefined?firstFailure.cause:failures,failures,message:`${failures.length} scaffold application operation${failures.length===1?"":"s"} failed.`,operation:"apply-reconciliation",partialResult})}return partialResult});var producerContracts={baseline:["scaffold","managed-bytes"],"context-plan":["scaffold","managed-bytes"],"harness-projection":["mixed","structured-entries"],lint:["scaffold","managed-bytes"],"project-local-skill":["repository","authored-content"],"project-settings":["mixed","structured-entries"],prompt:["repository","authored-content"],"scaffold-handoff":["scaffold","managed-bytes"],"scaffold-manifest":["scaffold","managed-bytes"],"source-guide":["scaffold","managed-bytes"],subagent:["repository","authored-content"],"wiki-starter":["repository","authored-content"]};var producerObligation=(producer,dependencies=[])=>{const contract=Object.entries(producerContracts).find(([name2])=>name2===producer)?.[1];return{contentAuthority:contract?.[0]??"unknown",dependencies,presence:"required",producer,validity:contract?.[1]??"authored-content"}};var legacyArtifactObligation=(artifactPath)=>{switch(artifactPath){case"AGENTS.md":{return producerObligation("prompt")}case".agents/AGENTS.md":{return producerObligation("baseline")}case".devpunks/context-plan.json":{return producerObligation("context-plan")}case".devpunks/settings.json":{return producerObligation("project-settings")}default:{return producerObligation("undeclared-artifact")}}};import{createHash as createHash6}from"node:crypto";var encodePrettyJson2=(value5)=>`${JSON.stringify(value5,null,2)}
2455
2455
  `;var compareKeys=(left,right)=>Number(left>right)-Number(left<right);var canonicalJsonStringify=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(canonicalJsonStringify).join(",")}]`}if(value5!==null&&typeof value5==="object"){return`{${Object.entries(value5).toSorted(([left],[right])=>compareKeys(left,right)).map(([key,child])=>`${JSON.stringify(key)}:${canonicalJsonStringify(child)}`).join(",")}}`}return JSON.stringify(value5)??"null"};var hashJsonContent=(content)=>{try{const parsed=JSON.parse(content.toString("utf-8"));return createHash6("sha256").update(canonicalJsonStringify(parsed)).digest("hex")}catch{return null}};var semanticManagedJsonPaths=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);var hashManagedFileContent=(relativePath,content,{semanticJson=true}={})=>{const semanticHash=semanticJson&&semanticManagedJsonPaths.has(relativePath)?hashJsonContent(content):null;return semanticHash??createHash6("sha256").update(content).digest("hex")};var compare3=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var encodeContextPlan=encodeSync2(ContextPlan);var contributionIdentity=(contribution)=>`${contribution.order}:${contribution.kind}:${contribution.identity.id}:${contribution.identity.version}`;var normalizeScope=(scope3)=>({...scope3,...scope3.authoring===undefined?{}:{authoring:{...scope3.authoring,contracts:[...scope3.authoring.contracts].toSorted((left,right)=>compare3(left.id,right.id)||compare3(left.activationRevision,right.activationRevision)||compare3(left.authoringRevision,right.authoringRevision)),missingContracts:[...scope3.authoring.missingContracts].toSorted(compare3)}},contributions:[...scope3.contributions].map((contribution)=>({...contribution,compatibility:[...contribution.compatibility].toSorted((left,right)=>compare3(`${left.id}:${left.versionRange}`,`${right.id}:${right.versionRange}`)),references:[...contribution.references].toSorted(compare3)})).toSorted((left,right)=>compare3(contributionIdentity(left),contributionIdentity(right))),packs:[...scope3.packs].toSorted((left,right)=>compare3(`${left.order}:${left.id}`,`${right.order}:${right.id}`))});var fileObligation=(file5)=>{if(file5.obligation!==undefined){return file5.obligation}if(file5.projectProducer!==undefined){return producerObligation("project-local-skill",[file5.projectProducer.producer])}return producerObligation(file5.provenance?.source??"undeclared-artifact",file5.provenance===undefined?[]:[file5.provenance.revision])};var fileIdentity=(file5)=>file5.path;var dependencyIdentity2=(dependency)=>`${dependency.workspace}:${dependency.section}:${dependency.name}`;var structuredEntryIdentity2=(entry)=>JSON.stringify([entry.file,entry.kind,entry.path]);var normalizeJson=(value5)=>{if(Array.isArray(value5)){return value5.map(normalizeJson)}if(typeof value5==="object"&&value5!==null){return Object.fromEntries(Object.entries(value5).toSorted(([left],[right])=>compare3(left,right)).map(([key,entry])=>[key,normalizeJson(entry)]))}return value5};var duplicateIdentities=(values,identity3)=>{const seen=new Set;const duplicates=new Set;for(const value5 of values){const key=identity3(value5);if(seen.has(key)){duplicates.add(key)}seen.add(key)}return[...duplicates].toSorted(compare3)};var structuralIdentity=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(structuralIdentity).join(",")}]`}if(typeof value5==="object"&&value5!==null){return`{${Object.entries(value5).toSorted(([left],[right])=>compare3(left,right)).map(([key,entry])=>`${JSON.stringify(key)}:${structuralIdentity(entry)}`).join(",")}}`}return JSON.stringify(value5)??String(value5)};var normalizeSummaryValues=(values)=>[...values].toSorted((left,right)=>compare3(structuralIdentity(left),structuralIdentity(right)));var normalizeNonEmptySummaryValues=(values)=>{const[first,...rest]=values;const normalized=[first,...rest];normalized.sort((left,right)=>compare3(structuralIdentity(left),structuralIdentity(right)));return normalized};var normalizeSummary=(summary)=>{switch(summary._tag){case"HarnessProjectionSuccess":{return{...summary,applied:normalizeSummaryValues(summary.applied)}}case"HarnessProjectionPartial":{return{...summary,applied:normalizeSummaryValues(summary.applied),omissions:normalizeNonEmptySummaryValues(summary.omissions)}}case"HarnessProjectionFailure":{return{...summary,completed:normalizeSummaryValues(summary.completed),errors:normalizeNonEmptySummaryValues(summary.errors),omissions:normalizeSummaryValues(summary.omissions)}}default:{return summary}}};var normalizeHarnessProjection=({matrix,result:result4})=>({actions:[...result4.actions].toSorted((left,right)=>compare3(left.id,right.id)),matrix:{...matrix,capabilities:[...matrix.capabilities].toSorted((left,right)=>compare3(left.family,right.family))},summary:normalizeSummary(result4.summary)});var compileDesiredScaffoldState=(input2)=>{const duplicateFiles=duplicateIdentities(input2.baseline.files,fileIdentity);const duplicateDependencies=duplicateIdentities(input2.baseline.dependencies,dependencyIdentity2);const duplicateStructuredEntries=duplicateIdentities(input2.baseline.structuredEntries,structuredEntryIdentity2);const duplicateProjections=duplicateIdentities(input2.projections,({matrix})=>matrix.adapter.id);const errors3=[...duplicateFiles.map((identity3)=>desiredScaffoldStateConflict({identity:identity3,item:"file"})),...duplicateDependencies.map((identity3)=>desiredScaffoldStateConflict({identity:identity3,item:"dependency"})),...duplicateStructuredEntries.map((identity3)=>desiredScaffoldStateConflict({identity:identity3,item:"structured-entry"})),...duplicateProjections.map((identity3)=>desiredScaffoldStateConflict({identity:identity3,item:"projection"}))];if(errors3.length>0){return{_tag:"DesiredScaffoldStateCompilationFailure",errors:errors3}}const projections=input2.projections.map(normalizeHarnessProjection).toSorted((left,right)=>compare3(left.matrix.adapter.id,right.matrix.adapter.id));const projectionFailures=[];for(const projection of projections){if(projection.summary._tag==="HarnessProjectionFailure"){for(const error2 of projection.summary.errors){projectionFailures.push({adapter:projection.matrix.adapter,error:error2})}}}const contextPlan=decodeUnknownSync(ContextPlan)(Object.fromEntries([["version",input2.contextPlan.version],["scopes",[...input2.contextPlan.scopes].map(normalizeScope).toSorted((left,right)=>compare3(left.id,right.id))]]));return{_tag:"DesiredScaffoldStateCompiled",state:{baseline:{catalogRevision:input2.baseline.catalogRevision,provenance:{...input2.baseline.provenance}},contextPlan,degradations:[],dependencies:[...input2.baseline.dependencies].toSorted((left,right)=>compare3(dependencyIdentity2(left),dependencyIdentity2(right))),files:[...input2.baseline.files].map((file5)=>({...file5,content:file5.kind==="context-plan"?encodePrettyJson2(encodeContextPlan(contextPlan)):file5.content,encoding:file5.kind==="context-plan"?"utf-8":file5.encoding??"utf-8",obligation:fileObligation(file5),...file5.mode===undefined?{}:{mode:file5.mode%512}})).toSorted((left,right)=>compare3(fileIdentity(left),fileIdentity(right))),omissions:[],projectionFailures,projections,settings:{...input2.settings,requiredTools:[...input2.settings.requiredTools].toSorted(compare3)},structuredEntries:[...input2.baseline.structuredEntries].map((entry)=>({...entry,value:normalizeJson(entry.value)})).toSorted((left,right)=>compare3(structuredEntryIdentity2(left),structuredEntryIdentity2(right))),version:"1"}}};var provenance=(input2,catalogRevision)=>({revision:input2.revision??catalogRevision,source:input2.source});var desiredScaffoldStateInput=(input2)=>{const baseline={catalogRevision:input2.baseline.catalogRevision,dependencies:input2.dependencies.map((dependency)=>({...dependency,provenance:provenance(dependency,input2.baseline.catalogRevision)})),files:input2.files.map((file5)=>({...file5,provenance:provenance(file5,input2.baseline.catalogRevision)})),provenance:input2.baseline.provenance,structuredEntries:input2.structuredEntries.map((entry)=>({...entry,provenance:provenance(entry,input2.baseline.catalogRevision)}))};return{baseline,contextPlan:input2.contextPlan,projections:input2.projections,settings:input2.settings}};var compileDesiredScaffoldOutput=(input2)=>{if(input2.settings===undefined){return{_tag:"DesiredScaffoldOutputCompiled",catalog:{catalogRevision:input2.baseline.catalogRevision,dependencies:input2.dependencies.map((dependency)=>({...dependency,provenance:provenance(dependency,input2.baseline.catalogRevision)})),files:input2.files.map((file5)=>({...file5,provenance:provenance(file5,input2.baseline.catalogRevision)})),provenance:input2.baseline.provenance,structuredEntries:input2.structuredEntries.map((entry)=>({...entry,provenance:provenance(entry,input2.baseline.catalogRevision)}))}}}return compileDesiredScaffoldState(desiredScaffoldStateInput({...input2,settings:input2.settings}))};var missingObservedScaffoldState={_tag:"MissingObservedScaffoldState"};var compileLifecycleState=({compile,gather})=>map6(gather(),compile);var runInitScaffoldLifecycle=({apply:apply2,compile=compileDesiredScaffoldState,gather})=>gen2(function*executeInitScaffoldLifecycle(){const compilation=yield*compileLifecycleState({compile,gather});if(compilation._tag==="DesiredScaffoldStateCompilationFailure"){return{_tag:"ScaffoldLifecycleCompilationFailed",compilation}}const application=yield*apply2({desiredState:compilation.state,observedState:missingObservedScaffoldState});return{_tag:"ScaffoldInitLifecycleCompleted",application,desiredState:compilation.state,observedState:missingObservedScaffoldState}});var runCheckScaffoldLifecycle=({compare:compare4,compile=compileDesiredScaffoldState,gather,observe})=>gen2(function*executeCheckScaffoldLifecycle(){const compilation=yield*compileLifecycleState({compile,gather});if(compilation._tag==="DesiredScaffoldStateCompilationFailure"){return{_tag:"ScaffoldLifecycleCompilationFailed",compilation}}const observedState=yield*observe({desiredState:compilation.state});const comparison=yield*compare4({desiredState:compilation.state,observedState});return{_tag:"ScaffoldCheckLifecycleCompleted",comparison,desiredState:compilation.state,observedState}});var runUpdateScaffoldLifecycle=({compile=compileDesiredScaffoldState,gather,observe,reconcile})=>gen2(function*executeUpdateScaffoldLifecycle(){const compilation=yield*compileLifecycleState({compile,gather});if(compilation._tag==="DesiredScaffoldStateCompilationFailure"){return{_tag:"ScaffoldLifecycleCompilationFailed",compilation}}const observedState=yield*observe({desiredState:compilation.state});const reconciliation=yield*reconcile({desiredState:compilation.state,observedState});return{_tag:"ScaffoldUpdateLifecycleCompleted",desiredState:compilation.state,observedState,reconciliation}});var fingerprintsMatch=(desired,observed)=>{if(desired._tag!==observed._tag){return false}if(desired._tag==="File"&&observed._tag==="File"){return observed.mode===desired.mode&&observed.sha256===desired.sha256}return desired._tag==="Symlink"&&observed._tag==="Symlink"&&observed.target===desired.target&&observed.sha256===desired.sha256};var evidenceMatches=(desired,receipt)=>{const desiredEvidence=desired.evidence;const receiptEvidence=receipt.evidence;return desiredEvidence.producer===receiptEvidence.producer&&desiredEvidence.revision===receiptEvidence.revision&&desiredEvidence.authority._tag===receiptEvidence.authority._tag&&desiredEvidence.authority.sourcePath===receiptEvidence.authority.sourcePath&&fingerprintsMatch(desiredEvidence.outputFingerprint,receiptEvidence.outputFingerprint)};var resolveManagedFileOwnership=({desiredOwnership,observed,receiptOwnership,scope:scope3})=>{if(scope3==="semantic-overlap"||desiredOwnership?._tag!=="ProjectGenerated"){return"scaffold-managed"}if(observed._tag==="Missing"){return"project-generated-missing"}if(receiptOwnership?._tag==="ProjectGenerated"&&evidenceMatches(desiredOwnership,receiptOwnership)&&observed._tag==="Present"&&fingerprintsMatch(desiredOwnership.evidence.outputFingerprint,observed.fingerprint)){return"project-generated-current"}return"project-generated-stale"};var projectionTraceKey=(trace2)=>JSON.stringify([trace2.contextPlanVersion,trace2.adapter.id,trace2.adapter.version,trace2.matrixVersion,trace2.scopeId,trace2.kind,trace2.contribution.id,trace2.contribution.version]);var configurationFile=(action2)=>{if(typeof action2.file==="string"){return action2.file}if(action2.operation==="mirror"&&typeof action2.config==="object"&&action2.config!==null&&"path"in action2.config&&typeof action2.config.path==="string"){return action2.config.path}if(typeof action2.target==="string"){return action2.target.split("#",1)[0]}return};var configurationPaths=(action2)=>{if(Array.isArray(action2.path)&&action2.path.every((part)=>typeof part==="string")){return[action2.path]}if(action2.operation==="mirror"&&typeof action2.config==="object"&&action2.config!==null&&"event"in action2.config&&typeof action2.config.event==="string"){return[["hooks",action2.config.event]]}if(action2.operation==="merge-json"&&action2.target==="opencode.json"&&typeof action2.value==="object"&&action2.value!==null&&!Array.isArray(action2.value)){const formatter="formatter"in action2.value?action2.value.formatter:undefined;if(typeof formatter==="object"&&formatter!==null&&!Array.isArray(formatter)&&"harness-format-edited-file"in formatter){return[["formatter","harness-format-edited-file"]]}return Object.keys(action2.value).map((key)=>[key])}if(Array.isArray(action2.entries)){return action2.entries.flatMap((entry)=>typeof entry==="object"&&entry!==null&&("event"in entry)&&typeof entry.event==="string"?[["hooks",entry.event]]:[])}return[]};var hasConfigurationSemantics=(action2)=>action2.operation==="merge-json"||action2.operation==="merge-toml"||action2.operation==="mirror"&&typeof action2.config==="object"&&action2.config!==null&&("path"in action2.config)&&typeof action2.config.path==="string";var actionReferenceKey2=({identity:identity3,item})=>JSON.stringify([item,identity3]);var compare4=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var dependencyIdentity3=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredEntryIdentity3=({file:file5,kind,path:path23})=>JSON.stringify([file5,kind,path23]);var packageFileForDependency=({workspace})=>workspace==="."?"package.json":`${workspace}/package.json`;var packageWorkspace=(file5)=>{const normalized=file5.replaceAll("\\","/");if(normalized==="package.json"){return"."}return normalized.endsWith("/package.json")?normalized.slice(0,-"/package.json".length):undefined};var workspaceContains=(parent,child)=>parent==="."||child===parent||child.startsWith(`${parent}/`);var catalogPrerequisiteDependencies=(actions,desiredDependencies)=>{const catalogActions=actions.flatMap((action2)=>{if(action2.item!=="structured-entry"||action2._tag==="SafeRemoveScaffoldEntry"){return[]}const{desired}=action2;const workspace=packageWorkspace(desired.file);return desired.kind==="field"&&desired.path.length===3&&desired.path[0]==="workspaces"&&desired.path[1]==="catalog"&&desired.path[2]!==undefined&&workspace!==undefined?[{action:action2,name:desired.path[2],workspace}]:[]});const requiredCatalogs=catalogActions.filter((candidate)=>desiredDependencies.some((dependency)=>dependency.version==="catalog:"&&dependency.name===candidate.name&&workspaceContains(candidate.workspace,dependency.workspace)));return actions.flatMap((action2)=>{if(action2.item!=="dependency"){return[]}const workspace=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace;const prerequisites=requiredCatalogs.filter((candidate)=>workspaceContains(candidate.workspace,workspace)).toSorted((left,right)=>right.workspace.length-left.workspace.length||left.name.localeCompare(right.name));return prerequisites.map((prerequisite)=>({action:{identity:action2.identity,item:action2.item},prerequisite:{identity:prerequisite.action.identity,item:prerequisite.action.item}}))})};var stableJson2=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(stableJson2).join(",")}]`}if(typeof value5==="object"&&value5!==null){return`{${Object.entries(value5).toSorted(([left],[right])=>compare4(left,right)).map(([key,entry])=>`${JSON.stringify(key)}:${stableJson2(entry)}`).join(",")}}`}return JSON.stringify(value5)};var structuralIdentity2=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(structuralIdentity2).join(",")}]`}if(typeof value5==="object"&&value5!==null){return`{${Object.entries(value5).toSorted(([left],[right])=>compare4(left,right)).map(([key,entry])=>`${JSON.stringify(key)}:${structuralIdentity2(entry)}`).join(",")}}`}return JSON.stringify(value5)??String(value5)};var observedMatchesDesired=(observed,desired,hasher)=>observed!==undefined&&observed.sha256===hasher.sha256(desired)&&observed.type===(desired.encoding==="symlink"?"symlink":"file")&&(desired.mode===undefined||observed.mode===desired.mode%512);var observedMatchesReceipt=(observed,receipt)=>observed!==undefined&&observed.sha256===receipt.sha256&&observed.type===receipt.type&&(receipt.type==="file"?typeof receipt.mode==="number"&&observed.mode===receipt.mode:receipt.mode===null&&observed.mode===null);var indexEntries=(entries,identity3)=>{const duplicates=new Set;const values=new Map;for(const entry of entries){const entryIdentity=identity3(entry);if(values.has(entryIdentity)){duplicates.add(entryIdentity)}else{values.set(entryIdentity,entry)}}return{duplicates,values}};var indexDesiredEntries=({desiredEntries,desiredEquivalent,identity:identity3})=>{const conflictingIdentities=new Set;const values=new Map;for(const desired of desiredEntries){const entryIdentity=identity3(desired);const previous=values.get(entryIdentity);if(previous===undefined){values.set(entryIdentity,desired)}else if(!desiredEquivalent(previous,desired)){conflictingIdentities.add(entryIdentity)}}return{conflictingIdentities,values}};var invalidEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var duplicateInvalidEntryMessage=(item,identity3)=>`Observed state contains duplicate invalid ${item} identity: ${identity3}`;var shouldRestoreMissingFile=(item,observation,hasPriorReceipt)=>item==="file"&&observation._tag==="MissingEntryObservation"&&hasPriorReceipt;var reconcileEntries=({blockedIdentities,desiredEntries,desiredEquivalent,identity:identity3,item,matchesDesired,matchesReceipt,makeCreate,makeRemove,makeUnchanged,makeUpdate,noun,observe,receiptEntries,receiptFromObserved})=>{const actions=[];const conflicts=[];const failures=[];const skips=[];const{conflictingIdentities:conflictingDesiredIdentities,values:desiredByIdentity}=indexDesiredEntries({desiredEntries,desiredEquivalent,identity:identity3});failures.push(...[...conflictingDesiredIdentities].map((entryIdentity)=>({_tag:"InvalidDesiredScaffoldEntryFailure",identity:entryIdentity,item,message:`Desired state contains conflicting managed ${noun} values: ${entryIdentity}`})));const receiptIndex=indexEntries(receiptEntries,identity3);failures.push(...[...receiptIndex.duplicates].map((entryIdentity)=>({_tag:"InvalidScaffoldReceiptFailure",identity:entryIdentity,item,message:`Prior receipt contains duplicate managed ${noun} identity: ${entryIdentity}`})));for(const[entryIdentity,desired]of desiredByIdentity){if(blockedIdentities.has(entryIdentity)||conflictingDesiredIdentities.has(entryIdentity)){continue}const observation=observe(entryIdentity);if(observation._tag==="InvalidEntryObservation"){failures.push({_tag:"InvalidScaffoldObservationFailure",identity:entryIdentity,item,message:observation.message});continue}if(receiptIndex.duplicates.has(entryIdentity)){continue}if(observation._tag==="PresentEntryObservation"&&matchesDesired(observation.value,desired)){skips.push(makeUnchanged(entryIdentity,receiptFromObserved(observation.value,desired)));continue}const previous=receiptIndex.values.get(entryIdentity);if(previous===undefined&&observation._tag==="MissingEntryObservation"){actions.push(makeCreate(entryIdentity,desired))}else if(shouldRestoreMissingFile(item,observation,previous!==undefined)){actions.push(makeUpdate(entryIdentity,desired))}else if(previous!==undefined&&observation._tag==="PresentEntryObservation"&&matchesReceipt(observation.value,previous)){actions.push(makeUpdate(entryIdentity,desired))}else{conflicts.push({_tag:"UserModifiedScaffoldEntryConflict",identity:entryIdentity,item,message:`Managed ${noun} was modified after the prior successful receipt: ${entryIdentity}`,operation:"update"})}}const desiredIdentities=new Set(desiredByIdentity.keys());for(const[entryIdentity,previous]of receiptIndex.values){if(receiptIndex.duplicates.has(entryIdentity)){continue}if(desiredIdentities.has(entryIdentity)){continue}const observation=observe(entryIdentity);if(observation._tag==="InvalidEntryObservation"){failures.push({_tag:"InvalidScaffoldObservationFailure",identity:entryIdentity,item,message:observation.message})}else if(observation._tag==="MissingEntryObservation"){skips.push(makeUnchanged(entryIdentity,null))}else if(matchesReceipt(observation.value,previous)){actions.push(makeRemove(entryIdentity,previous))}else{conflicts.push({_tag:"StaleScaffoldOwnershipConflict",identity:entryIdentity,item,message:`Receipt-only managed ${noun} no longer matches its successful receipt: ${entryIdentity}`,operation:"remove"})}}return{actions,conflicts,failures,skips}};var planScaffoldReconciliation=({desiredState,observedState,priorReceipt:encodedPriorReceipt},hasher)=>{const priorReceipt={...encodedPriorReceipt,files:encodedPriorReceipt.files.map((file5)=>({...file5,ownership:file5.ownership??{_tag:"ScaffoldManaged"}}))};const wholeFilePaths=new Set(desiredState.files.map((file5)=>file5.path));const structuredOverlapPaths=new Set(desiredState.structuredEntries.map((entry)=>entry.file).filter((file5)=>wholeFilePaths.has(file5)));const dependencyOverlapPaths=new Set(desiredState.dependencies.map(packageFileForDependency).filter((file5)=>wholeFilePaths.has(file5)));const crossFamilyFailures=[...[...structuredOverlapPaths].map((file5)=>({_tag:"CrossFamilyScaffoldOwnershipFailure",identity:JSON.stringify([file5,"file","structured-entry"]),message:`Desired state assigns whole-file and structured-entry ownership to ${file5}`,owners:["file","structured-entry"],path:file5})),...[...dependencyOverlapPaths].map((file5)=>({_tag:"CrossFamilyScaffoldOwnershipFailure",identity:JSON.stringify([file5,"dependency","file"]),message:`Desired state assigns whole-file and dependency ownership to ${file5}`,owners:["dependency","file"],path:file5}))];const blockedFileIdentities=new Set([...structuredOverlapPaths,...dependencyOverlapPaths]);const blockedStructuredIdentities=new Set(desiredState.structuredEntries.filter((entry)=>structuredOverlapPaths.has(entry.file)).map(structuredEntryIdentity3));const blockedDependencyIdentities=new Set(desiredState.dependencies.filter((entry)=>dependencyOverlapPaths.has(packageFileForDependency(entry))).map(dependencyIdentity3));const invalidEntries=indexEntries(observedState.invalidEntries,(entry)=>invalidEntryKey(entry.item,entry.identity));const invalidObservationMessage=(item,identity3)=>{const key=invalidEntryKey(item,identity3);if(invalidEntries.duplicates.has(key)){return duplicateInvalidEntryMessage(item,identity3)}return invalidEntries.values.get(key)?.message};const duplicateInvalidEntryFailures=[...invalidEntries.duplicates].flatMap((key)=>{const entry=invalidEntries.values.get(key);return entry===undefined?[]:[{_tag:"InvalidScaffoldObservationFailure",identity:entry.identity,item:entry.item,message:duplicateInvalidEntryMessage(entry.item,entry.identity)}]});const desiredFileIdentities=new Set(desiredState.files.map((file5)=>file5.path));const unknownFileIdentities=new Set([...desiredState.files.filter((file5)=>fileObligation(file5).contentAuthority==="unknown").map((file5)=>file5.path),...priorReceipt.files.filter((file5)=>!desiredFileIdentities.has(file5.path)&&(file5.obligation?.contentAuthority??"unknown")==="unknown").map((file5)=>file5.path)]);const observedFiles=indexEntries(observedState.files,(file5)=>file5.path);const filePlan=reconcileEntries({blockedIdentities:blockedFileIdentities,desiredEntries:desiredState.files,desiredEquivalent:(left,right)=>structuralIdentity2(left)===structuralIdentity2(right),identity:(entry)=>entry.path,item:"file",makeCreate:(identity3,desired)=>({_tag:"SafeCreateScaffoldEntry",desired,identity:identity3,item:"file"}),makeRemove:(identity3,previous)=>({_tag:"SafeRemoveScaffoldEntry",identity:identity3,item:"file",previous}),makeUnchanged:(identity3,receiptEntry)=>({_tag:"UnchangedScaffoldEntry",identity:identity3,item:"file",receiptEntry}),makeUpdate:(identity3,desired)=>({_tag:"SafeUpdateScaffoldEntry",desired,identity:identity3,item:"file"}),matchesDesired:(observed,desired)=>observedMatchesDesired(observed,desired,hasher),matchesReceipt:observedMatchesReceipt,noun:"file",observe:(identity3)=>{if(unknownFileIdentities.has(identity3)){return{_tag:"InvalidEntryObservation",message:`Artifact ownership is unknown: ${identity3}`}}if(observedFiles.duplicates.has(identity3)){return{_tag:"InvalidEntryObservation",message:`Observed state contains duplicate managed file identity: ${identity3}`}}const invalidMessage=invalidObservationMessage("file",identity3);if(invalidMessage!==undefined){return{_tag:"InvalidEntryObservation",message:invalidMessage}}const observed=observedFiles.values.get(identity3);if(observed===undefined||observed.type==="missing"){return{_tag:"MissingEntryObservation"}}return observed.type==="other"?{_tag:"InvalidEntryObservation",message:`Managed file path is neither a file nor a symlink: ${identity3}`}:{_tag:"PresentEntryObservation",value:observed}},receiptEntries:priorReceipt.files,receiptFromObserved:(observed,desired)=>({...desired.obligation===undefined?{}:{obligation:desired.obligation},...desired.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:desired.sharedPromptIdentity},kind:desired.kind,mode:observed.mode,ownership:{_tag:"ScaffoldManaged"},path:desired.path,sha256:observed.sha256??hasher.sha256(desired),type:observed.type==="symlink"?"symlink":"file"})});const observedDependencies=indexEntries(observedState.dependencies,dependencyIdentity3);const dependencyPlan=reconcileEntries({blockedIdentities:blockedDependencyIdentities,desiredEntries:desiredState.dependencies,desiredEquivalent:(left,right)=>structuralIdentity2(left)===structuralIdentity2(right),identity:dependencyIdentity3,item:"dependency",makeCreate:(identity3,desired)=>({_tag:"SafeCreateScaffoldEntry",desired,identity:identity3,item:"dependency"}),makeRemove:(identity3,previous)=>({_tag:"SafeRemoveScaffoldEntry",identity:identity3,item:"dependency",previous}),makeUnchanged:(identity3,receiptEntry)=>({_tag:"UnchangedScaffoldEntry",identity:identity3,item:"dependency",receiptEntry}),makeUpdate:(identity3,desired)=>({_tag:"SafeUpdateScaffoldEntry",desired,identity:identity3,item:"dependency"}),matchesDesired:(observed,desired)=>observed.version===desired.version,matchesReceipt:(observed,previous)=>observed.version===previous.version,noun:"dependency",observe:(identity3)=>{if(observedDependencies.duplicates.has(identity3)){return{_tag:"InvalidEntryObservation",message:`Observed state contains duplicate managed dependency identity: ${identity3}`}}const invalidMessage=invalidObservationMessage("dependency",identity3);if(invalidMessage!==undefined){return{_tag:"InvalidEntryObservation",message:invalidMessage}}const observed=observedDependencies.values.get(identity3);return observed===undefined?{_tag:"MissingEntryObservation"}:{_tag:"PresentEntryObservation",value:observed}},receiptEntries:priorReceipt.dependencies,receiptFromObserved:(observed)=>observed});const observedStructuredEntries=indexEntries(observedState.structuredEntries,structuredEntryIdentity3);const structuredPlan=reconcileEntries({blockedIdentities:blockedStructuredIdentities,desiredEntries:desiredState.structuredEntries,desiredEquivalent:(left,right)=>structuralIdentity2(left)===structuralIdentity2(right),identity:structuredEntryIdentity3,item:"structured-entry",makeCreate:(identity3,desired)=>({_tag:"SafeCreateScaffoldEntry",desired,identity:identity3,item:"structured-entry"}),makeRemove:(identity3,previous)=>({_tag:"SafeRemoveScaffoldEntry",identity:identity3,item:"structured-entry",previous}),makeUnchanged:(identity3,receiptEntry)=>({_tag:"UnchangedScaffoldEntry",identity:identity3,item:"structured-entry",receiptEntry}),makeUpdate:(identity3,desired)=>({_tag:"SafeUpdateScaffoldEntry",desired,identity:identity3,item:"structured-entry"}),matchesDesired:(observed,desired)=>stableJson2(observed.value)===stableJson2(desired.value),matchesReceipt:(observed,previous)=>stableJson2(observed.value)===stableJson2(previous.value),noun:"structured entry",observe:(identity3)=>{if(observedStructuredEntries.duplicates.has(identity3)){return{_tag:"InvalidEntryObservation",message:`Observed state contains duplicate managed structured entry identity: ${identity3}`}}const invalidMessage=invalidObservationMessage("structured-entry",identity3);if(invalidMessage!==undefined){return{_tag:"InvalidEntryObservation",message:invalidMessage}}const observed=observedStructuredEntries.values.get(identity3);return observed===undefined?{_tag:"MissingEntryObservation"}:{_tag:"PresentEntryObservation",value:observed}},receiptEntries:priorReceipt.structuredEntries,receiptFromObserved:(observed)=>observed});const blockedFilePaths=new Set([...filePlan.conflicts.map(({identity:identity3})=>identity3),...filePlan.failures.map(({identity:identity3})=>identity3)]);const blockedLifecycleTraces=new Set(desiredState.projections.flatMap(({actions:actions2})=>actions2.flatMap((action2)=>action2.trace.kind==="lifecycle-hook"&&action2.operation==="mirror"&&typeof action2.target==="string"&&blockedFilePaths.has(action2.target)?[projectionTraceKey(action2.trace)]:[])));const blockedConfigurationActions=desiredState.projections.flatMap(({actions:actions2})=>actions2.filter((action2)=>blockedLifecycleTraces.has(projectionTraceKey(action2.trace))&&hasConfigurationSemantics(action2)));const matchingConfigurationEntries=(action2)=>{const file5=configurationFile(action2);if(file5===undefined){return[]}const paths=configurationPaths(action2);return desiredState.structuredEntries.filter((entry)=>entry.file===file5&&paths.some((entryPath)=>stableJson2(entry.path)===stableJson2(entryPath)))};const blockedConfigurationEntries=new Set(blockedConfigurationActions.flatMap((action2)=>matchingConfigurationEntries(action2).map(structuredEntryIdentity3)));const desiredFilePaths=new Set(desiredState.files.map(({path:path23})=>path23));const blockedWholeConfigurationFiles=new Set(blockedConfigurationActions.flatMap((action2)=>{const file5=configurationFile(action2);return file5!==undefined&&desiredFilePaths.has(file5)&&matchingConfigurationEntries(action2).length===0?[file5]:[]}));const actions=[...filePlan.actions.filter((action2)=>action2.item!=="file"||!blockedWholeConfigurationFiles.has(action2.identity)),...dependencyPlan.actions,...structuredPlan.actions.filter((action2)=>action2._tag==="SafeRemoveScaffoldEntry"||!blockedConfigurationEntries.has(action2.identity))];const actionReferences=new Set(actions.map((action2)=>actionReferenceKey2({identity:action2.identity,item:action2.item})));const dependencies=desiredState.projections.flatMap(({actions:projectionActions})=>{const mirrorsByTrace=new Map;for(const action2 of projectionActions){if(action2.trace.kind==="lifecycle-hook"&&action2.operation==="mirror"&&typeof action2.source==="string"&&typeof action2.target==="string"){const reference={identity:action2.target,item:"file"};if(actionReferences.has(actionReferenceKey2(reference))){mirrorsByTrace.set(projectionTraceKey(action2.trace),reference)}}}return projectionActions.flatMap((action2)=>{const prerequisite=mirrorsByTrace.get(projectionTraceKey(action2.trace));if(prerequisite===undefined||!hasConfigurationSemantics(action2)){return[]}const matchingEntries=matchingConfigurationEntries(action2).map((entry)=>({identity:structuredEntryIdentity3(entry),item:"structured-entry"}));const file5=configurationFile(action2);const matchingFiles=matchingEntries.length===0&&file5!==undefined&&desiredFilePaths.has(file5)?[{identity:file5,item:"file"}]:[];return[...matchingEntries,...matchingFiles].filter((reference)=>actionReferences.has(actionReferenceKey2(reference))).map((actionReference)=>({action:actionReference,prerequisite}))})});const catalogDependencies=catalogPrerequisiteDependencies(actions,desiredState.dependencies);const conflicts=[...filePlan.conflicts,...dependencyPlan.conflicts,...structuredPlan.conflicts];const failures=[...crossFamilyFailures,...desiredState.projectionFailures.map((evidence)=>({_tag:"DesiredProjectionReconciliationFailure",evidence,identity:structuralIdentity2(evidence),message:`Desired projection failed for adapter ${evidence.adapter.id}`})),...duplicateInvalidEntryFailures,...filePlan.failures,...dependencyPlan.failures,...structuredPlan.failures];const skips=[...filePlan.skips,...dependencyPlan.skips,...structuredPlan.skips];const byIdentity=(left,right)=>compare4(left.identity,right.identity);return{_tag:"ScaffoldReconciliationPlanned",actions:actions.toSorted(byIdentity),conflicts:conflicts.toSorted(byIdentity),degradations:[],dependencies:[...new Map([...dependencies,...catalogDependencies].map((dependency)=>[`${actionReferenceKey2(dependency.action)}:${actionReferenceKey2(dependency.prerequisite)}`,dependency])).values()],failures:[...new Map(failures.map((failure)=>[structuralIdentity2(failure),failure])).values()].toSorted(byIdentity),skips:skips.toSorted(byIdentity)}};import{createHash as createHash7}from"node:crypto";import{lstatSync as lstatSync4,readFileSync as readFileSync10}from"node:fs";import path23 from"node:path";var readSharedPrompt=(baseline)=>gen2(function*loadSelectedSharedPrompt(){const capability=baseline.capabilities?.sharedPrompt;if(capability===undefined){return yield*new CliValidationError({message:`unsupported-capability: baseline ${baseline.summary.resolvedVersion} does not declare sharedPrompt v1.`})}return yield*try_3({catch:(cause)=>new CliValidationError({cause,message:`baseline-integrity: sharedPrompt asset ${capability.path} in baseline ${baseline.summary.resolvedVersion} is missing or invalid.`}),try:()=>{const assetPath=path23.join(baseline.dataRoot,"shared-agents.md");if(!lstatSync4(assetPath).isFile()){throw new Error("asset must be a regular file")}const bytes=readFileSync10(assetPath);if(createHash7("sha256").update(bytes).digest("hex")!==capability.sha256){throw new Error("asset digest mismatch")}return{capability,content:bytes.toString("utf-8")}}})});import{createHash as createHash10}from"node:crypto";import{existsSync as existsSync10,lstatSync as lstatSync6,mkdtempSync as mkdtempSync4,readdirSync as readdirSync4,readFileSync as readFileSync12,readlinkSync as readlinkSync4,realpathSync as realpathSync6,rmSync as rmSync4,writeFileSync as writeFileSync6}from"node:fs";import{tmpdir as tmpdir7}from"node:os";import path27 from"node:path";import{runInNewContext}from"node:vm";import path24 from"node:path";var bulletList=(values,empty11)=>values.length===0?[empty11]:values.map((value5)=>`- \`${value5}\``);var rootPromptConcepts=[{invariants:["Name the real apps, packages, services, infra folders, docs/wiki roots, generated-code homes, and shared contract owners detected in this repository.","For each surface, say what belongs there and what should stay elsewhere.","Route single-surface implementation to the nearest scoped prompt.","For cross-surface work, name the owning surfaces before editing."],name:"Repo Surface Map",purpose:"Tell the agent where work belongs."},{invariants:["Start Finder only from an explicit human invocation of `business-finder` or `functional-finder`.","Unclear requirements or product decisions route to `requirements-phase`.","Product design work with existing evidence routes to explicit `design-phase`.","Scoped implementation from an accepted spec, issue, or plan routes to `delivery-phase`.","Runtime failures, crashes, broken local flows, and production-like symptoms route to `debugging-phase`.","Review requests, branch reviews, and PR reviews route to `review-phase`.","Docs or knowledge updates after proven changes route to `docs-ingest-phase`.","Readonly investigation that splits across independent surfaces or hypotheses routes to `parallel-research`."],name:"Workflow Routing",purpose:"Tell the agent which lifecycle entrypoint applies."},{invariants:["API contracts, generated clients, schemas, env/config, infra wiring, deployment assumptions, and docs stay aligned across owning surfaces.","Backend or service contract changes are reflected in generated clients and consumers.","Infra or deployment changes that affect runtime config, callbacks, CORS, queues, storage, or secrets are reflected in the owning app/service scope and docs.","Product logic does not move across surfaces just to finish a local task."],name:"Cross-Surface Contract Rules",purpose:"Tell the agent which boundaries must stay aligned."},{invariants:["Run the narrowest validation that proves the touched surface first.","Run contract generation or type checks when APIs or schemas change.","Run browser, simulator, or manual UI checks when user-facing behavior changes.","Run infra synth, plan, or dry-run checks when infrastructure changes.","Record blockers when an expected validation cannot run."],name:"Validation Routing",purpose:"Tell the agent how to prove cross-surface work."}];var rootPromptWideInvariants=["Author from real repo evidence: detected manifests, package/workspace names, docs/wiki roots, infra/config files, generated assets, existing prompts, and committed project conventions.","Do not copy a static scaffold root body or invent product-specific prose from examples.","Before working in any directory, inspect the nearest `AGENTS.md` files from the repo root down to each touched path.","Nested docs/workspace skill pointers are local trigger requirements: for matching work, read each named skill, apply it with root guidance, prefer the most specific directory guidance, and activate every touched scope.","For review requests, require findings-first review with precise file/line references, `autoreview` as the core runtime, and `simplify`, `improve-codebase-architecture`, plus scoped primary skills as review lenses.","When routed learning artifacts exist, consult relevant learnings during discovery, planning, debugging, and review.","Implementation work must be handed off to scoped workers in plan-derived waves; launch every currently unblocked task whose write scope is disjoint, and use a one-worker wave only when dependencies or ownership leave one task unblocked. The parent coordinates, reviews, validates, and advances the graph.","Before relying on subagents, verify active global/project agent settings, then `.agents/subagents/manifest.mjs` and the selected specialist's owned paths, guidance files, and skills."];var rootPromptSpecSections=(spec)=>["## Root Prompt Criteria","","- Materialize the final root prompt from real repo evidence. Do not copy this spec as the final prompt body.","- Keep the final root prompt concise: surface map, workflow routing, cross-surface contract rules, validation routing, then only short repo-wide source/URL/docs rules.",`- Include this autonomy pointer exactly once: ${handbackPointer}`,"- Do not add a root `Primary skills here` line. Root lifecycle skills are explicit workflow entrypoints, not always-on scoped defaults.","","## Root Prompt Concepts","",...rootPromptConcepts.flatMap((concept)=>[`### ${concept.name}`,"",`Purpose: ${concept.purpose}`,"","Invariants:",...concept.invariants.map((invariant)=>`- ${invariant}`),""]),"## Root-Wide Invariants","",...rootPromptWideInvariants.map((invariant)=>`- ${invariant}`),"","- Treat every authored `AGENTS.md` file as the neutral source of truth and create a sibling `CLAUDE.md` symlink mirror that points to it.","- Add `opensrc` / source-inspection guidance only when this repo actually needs it.","- Keep portless guidance repo-wide unless a scoped prompt directly owns local URL, origin, callback, CORS, or proxy configuration.","- End with the docs-update rule when work changes setup, workflow, contracts, architecture, deployment behavior, or non-obvious behavior.","","## Selected packs","",...bulletList(spec.packs,"- `(none)`"),"","## Available workflow entrypoints","","- `business-finder`","- `functional-finder`","- `requirements-phase`","- `design-phase`","- `delivery-phase`","- `debugging-phase`","- `review-phase`","- `docs-ingest-phase`","- `parallel-research`"];var sharedPromptSpecSections=(spec)=>["## House structure","","- Start with one `## <Scope> Guidance` heading.","- Put one `## Skills` table near the top with one exact task trigger per selected non-phase skill and its installed `SKILL.md` path.","- Keep `business-finder`, `functional-finder`, and lifecycle phases as global orchestration entrypoints rather than scoped table rows; `finder-phase` remains the wrappers' internal engine.","- Follow with one short paragraph defining the scope boundary: what belongs here vs elsewhere.",`- Follow the scope boundary immediately with this autonomy pointer: ${handbackPointer}`,"- Treat every authored `AGENTS.md` file as the neutral source of truth and create a sibling `CLAUDE.md` symlink mirror that points to it.","- Add `opensrc` / source-inspection guidance only when this scope actually needs it.","- Add portless guidance only to the root/handoff, or to a scoped prompt that directly owns local URL, origin, callback, CORS, or proxy configuration.","- End with the docs-update rule when work in this scope changes setup, workflow, contracts, or non-obvious behavior.","- Add extra focused sections only when the detected scope truly needs them.","","## Selected packs","",...bulletList(spec.packs,"- `(none)`"),"","## Primary skills","",...bulletList(spec.primarySkills,"- `simplify`")];var sourceGuideLinkForScope=(spec)=>{const relativePath=path24.posix.relative(spec.workspacePath??".","opensrc/README.md");return`[Source Guide](${relativePath})`};var scopedPromptSpecSections=(spec)=>{const selectedSkills2=scopedPrimarySkills(spec.primarySkills);return["## Scoped Authoring Contract","","- Author one compact coding standard for this docs or workspace root. Keep root policy inherited, preserve existing project-authored prompts below this root, and create no deeper `AGENTS.md` files.",`- Follow the scope boundary immediately with this autonomy pointer: ${handbackPointer}`,"- Treat the final `AGENTS.md` as the neutral source and create its sibling `CLAUDE.md` symlink mirror.","","## Repository Invariants","","- Inline only repository-specific structural invariants: semantic responsibilities, placement and dependency direction, entrypoints, composition, generated and colocation boundaries, and local coding or authoring conventions.","- Derive invariants from current repository behavior and enforced constraints. Omit unresolved conflicts instead of adding generic evidence instructions.","- Point conditional repository detail to scope-owned Markdown with an exact task trigger and relative target.","- End with the narrow validation and docs-update seams owned by this scope.","",...renderScopedSkillsTable(selectedSkills2),"","Preserve every selected non-phase skill ID once. Point to its installed source with the exact invocation trigger; keep skill semantics in the skill.","","## Source Guide","",`- Link ${sourceGuideLinkForScope(spec)} and read it when work depends on third-party library behavior; keep package commands and precedence there rather than repeating them here.`,"","## Selected packs","",...bulletList(spec.packs,"- `(none)`")]};var promptSpecSections=(spec)=>{if(spec.scope==="root"){return rootPromptSpecSections(spec)}if(spec.scope==="shared"){return sharedPromptSpecSections(spec)}return scopedPromptSpecSections(spec)};var promptAuthoringShape=(scope3)=>{if(scope3==="root"){return"- For root, preserve the router shape: guidance, surface map, workflow routing, cross-surface contracts, validation routing, optional `opensrc`, docs update rule."}if(scope3==="shared"){return"- For shared guidance, preserve the existing global prompt shape and keep repo-local coding standards in docs/workspace prompts."}return"- For docs/workspace prompts, follow the compact repository-invariant, skill-pointer, Source Guide, mirror, and validation contract above."};var sourceInspectionSections=(spec)=>spec.scope==="docs"||spec.scope==="workspace"?[]:["## Source inspection","","- No arbitrary concrete `opensrc` repositories are invented by scaffold.","- During post-scaffold setup, decide which detected core libraries materially affect prompt or lint authoring, then read any matching `opensrc/<package>.md` guide before running `opensrc path --cwd . <package>` or `opensrc path owner/repo`."];var renderPromptSpecMarkdown=(spec)=>["# Prompt Spec","",`Target file: \`${spec.targetFile}\``,`Scope: \`${spec.scope}\``,`Workspace: \`${spec.workspacePath??"."}\``,`Seed mode: \`${spec.source}\``,"",...promptSpecSections(spec),"",...sourceInspectionSections(spec),...spec.opensrcReferences.length===0?[]:["","## Curated opensrc examples","","- These maintained pack examples are for gathering real-world patterns and code architectures aligned with the selected pack skills.",...spec.opensrcReferences.map((repo)=>`- \`${repo}\`: \`opensrc path ${repo}\``)],"","## Authoring guidance","",`- Activate \`writing-for-agents\`, then \`rule-authoring\`, before editing \`${spec.specFile}\`, authoring \`${spec.targetFile}\`, or maintaining \`.agents/rules/index.md\`; keep detailed patterns in granular rule files.`,"- Keep the final prompt concise, imperative, and scope-first.",promptAuthoringShape(spec.scope),"- Keep phase skills out of every scoped `AGENTS.md`; Finder wrappers require explicit human invocation, while other phases run from the parent goal/handoff flow.","- Route broader monorepo concerns back to the root prompt instead of repeating them in every scope.","- If a seed prompt exists in the source repo, preserve repo-specific constraints while reconciling them with the detected pack set.","- Keep `$docs-ingest-phase` invocation in prompt files, not in generated docs pages."].join(`
2456
2456
  `);var shellArgument=(value5)=>`'${value5.replaceAll("'","'\\''")}'`;var renderScopedAuthoringHandoff=(actions)=>["# Post-Command Handoff","","Current structured scope and receipt evidence determine pending work. Run `hi check` to refresh this assessment before acting on retained handoff prose.","",...actions.length===0?["No scoped authoring actions are pending."]:["Activate `writing-for-agents`, then `rule-authoring`. Read each affected prompt spec and actual repository evidence; preserve valid repository-authored guidance and custom roles outside the named scope.",...actions.flatMap((action2)=>["",`## Scope: ${action2.scopeId}`,"",`- Trigger: \`${action2.trigger}\`.`,`- Input identity: \`${action2.inputIdentity}\`.`,`- Allowed outputs: ${action2.allowedOutputs.map((file5)=>`\`${file5}\``).join(", ")}.`,...action2.allowedAgentIds.length===0?[]:[`- Manifest changes are limited to roles: ${action2.allowedAgentIds.map((id)=>`\`${id}\``).join(", ")}; preserve all other roles.`],`- Completion evidence: \`${action2.completionEvidence}\`.`,...action2.trigger==="compatibility-unknown"?["- Completion is blocked until the selected baseline declares the missing authoring contracts; resolve compatibility before authoring."]:["- Deterministic completion: validate authored outputs, project native mirrors, and publish current-input proof through:","","```sh",`node .agents/scripts/sync-subagents.mjs --complete-authoring ${shellArgument(action2.scopeId)} ${shellArgument(action2.inputIdentity)}`,"```","","Run `hi check` after completion. The projection receipt must verify this exact input; handoff text alone is not evidence."]])],""].join(`
2457
2457
  `);var projectVerifierPreservationHandoff=["## Project Verifier","","- Preserve the current project-owned verifier references using the active `$hi-cli` skill rule at `references/post-command-flow.md#project-verifier-preservation`.",""];var hasScopedAuthoringActions=(actions)=>actions!==undefined;var renderAgentHandoffMarkdown=({repoShapeMode,monorepo,detectedTechnologies,finalPacks,promptOutputs,promptSpecFiles,lintSpecFiles,sourceGuideFiles,skillFiles,subagentFiles,scriptFiles,hookFiles,harnessFiles,scaffoldManifestFile,toolBootstrapStatuses,commitGateHandoff,scopedAuthoringActions})=>hasScopedAuthoringActions(scopedAuthoringActions)?[renderScopedAuthoringHandoff(scopedAuthoringActions),...projectVerifierPreservationHandoff,...commitGateHandoff===undefined?[]:["## Commit Gate Post-Command Handoff","",`- Status: \`${commitGateHandoff.status}\`.`,`- Action: \`${commitGateHandoff.action}\`.`,...commitGateHandoff.commands.map((command)=>`- Follow-through command: \`${command.join(" ")}\`.`),`- Stop condition: ${commitGateHandoff.stopCondition}`,""]].join(`
@@ -2470,17 +2470,17 @@ When the generated init output matches the repo, the next CLI step is:
2470
2470
  `].join("")};var sortSubagentSpecialists=(spec)=>({...spec,specialists:spec.specialists.toSorted((left,right)=>left.id.localeCompare(right.id))});import{createHash as createHash8}from"node:crypto";var readScopedAuthoringProofs=(receipt)=>{const proofs=receipt?.scopedAuthoring;if(!Array.isArray(proofs)){return[]}const scopes=new Set;for(const proof of proofs){if(proof===null||typeof proof!=="object"||typeof proof.scopeId!=="string"||proof.scopeId.length===0||typeof proof.inputIdentity!=="string"||!/^[a-f0-9]{64}$/u.test(proof.inputIdentity)||proof.status!=="verified"||scopes.has(proof.scopeId)){return[]}scopes.add(proof.scopeId)}return proofs};var scopeAuthoringIdentity=(scope3)=>JSON.stringify(scope3.authoring===undefined?{compatibility:"unknown",scopeId:scope3.id}:{contracts:[...scope3.authoring.contracts].toSorted((left,right)=>left.id.localeCompare(right.id)).map(({id,authoringRevision,activationRevision})=>({activationRevision,authoringRevision,id})),kind:scope3.authoring.kind,missingContracts:[...new Set(scope3.authoring.missingContracts)].toSorted(),path:scope3.authoring.path});var assessScopedAuthoring=({contextPlan,proofs})=>contextPlan.scopes.flatMap((scope3)=>{if(scope3.id==="shared"||scope3.id===".agents"||!scope3.contributions.some(({kind})=>kind==="scoped-prompt")){return[]}const inputIdentity=createHash8("sha256").update(scopeAuthoringIdentity(scope3)).digest("hex");const proof=proofs.find((entry)=>entry.scopeId===scope3.id);const compatible=scope3.authoring!==undefined&&scope3.authoring.missingContracts.length===0;if(compatible&&proof?.status==="verified"&&proof.inputIdentity===inputIdentity){return[]}let trigger;if(compatible){trigger=proof===undefined?"unverified":"inputs-changed"}else{trigger="compatibility-unknown"}const allowedAgentIds=scope3.contributions.filter(({kind})=>kind==="subagent-template").map(({identity:identity3})=>identity3.id).toSorted();return[{allowedAgentIds,allowedOutputs:[scope3.id==="root"?"AGENTS.md":`${scope3.id}/AGENTS.md`,...allowedAgentIds.length===0?[]:[".agents/subagents/manifest.mjs"]],completionEvidence:"validated-authored-output-and-native-projection",inputIdentity,scopeId:scope3.id,trigger}]});class ContextPlanCompilationFailure extends TaggedErrorClass()("@punks/cli/context-planning/ContextPlanCompilationFailure",{cause:Defect(),message:String4,operation:Literal2("compile-context-plan")}){}class IncompleteQualityCommandContract extends TaggedErrorClass()("IncompleteQualityCommandContract",{cause:Defect(),id:NonEmptyString,message:String4,missing:ArraySchema(Literals(["lint","formatCheck"])),operation:Literal2("compile-context-plan")}){}class ContextPlanResolutionFailure extends TaggedErrorClass()("@punks/cli/context-planning/ContextPlanResolutionFailure",{cause:Defect(),id:String4,kind:Literals(["capability-group","pack","resolved-skill","skill","tool"]),message:String4,operation:Literal2("resolve-context-plan-entry")}){}var uniqueSorted=(values)=>[...new Set(values)].toSorted();var resolutionFailure=(id,kind,message)=>new ContextPlanResolutionFailure({cause:new Error(message),id,kind,message,operation:"resolve-context-plan-entry"});var requireCatalogEntry=(entries,id,kind)=>{const entry=entries.get(id);if(entry===undefined){throw resolutionFailure(id,kind==="capability group"?"capability-group":kind,`Unknown ${kind}: ${id}`)}return entry};var requireResolvedSkill=(entries,id)=>{const entry=entries.get(id);if(entry===undefined){throw resolutionFailure(id,"resolved-skill",`Missing resolved skill metadata: ${id}`)}return entry};var scopePackSignals=({manifest,relativeWorkspacePath})=>{const dependencyNames=manifest?.dependencies??[];const dependencies=new Set(dependencyNames);const hasDependency=(name2)=>dependencies.has(name2);const hasDependencyPrefix=(prefix)=>dependencyNames.some((name2)=>name2.startsWith(prefix));const hasNamedSegment=({pathNames,packageNames=pathNames})=>{const packageSegments=manifest?.packageName?.replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).filter(Boolean).map((segment)=>segment.toLowerCase())??[];return relativeWorkspacePath.split("/").some((segment)=>pathNames.includes(segment))||packageSegments.some((segment)=>packageNames.includes(segment))};const hasBackendDependency=hasDependency("better-auth")||hasDependency("drizzle-orm")||hasDependency("drizzle-kit")||hasDependency("elysia")||hasDependencyPrefix("@trpc/");const hasFrontendDependency=hasDependency("next")||hasDependency("react")||hasDependency("react-dom")||hasDependency("@tanstack/react-query");return{hasDependency,hasDependencyPrefix,isBackend:hasBackendDependency||hasNamedSegment({packageNames:["api","backend","server","service"],pathNames:["api","backend","server","services"]}),isFrontend:hasFrontendDependency||hasNamedSegment({pathNames:["frontend","ui","web"]})}};var packsForScope=({kind,relativeWorkspacePath,manifest,finalPacks})=>{const selectedPacks=new Set(finalPacks);const{hasDependency,hasDependencyPrefix,isBackend,isFrontend}=scopePackSignals({manifest,relativeWorkspacePath});const packs=[];const add3=(pack,condition=true)=>{if(condition&&selectedPacks.has(pack)){packs.push(pack)}};add3("quality");add3("research");add3("typescript",relativeWorkspacePath!==".agents"&&relativeWorkspacePath!=="docs");if(relativeWorkspacePath===".agents"){add3("misc");add3("subagents");add3("docs");return uniqueSorted(packs)}if(relativeWorkspacePath==="."){return uniqueSorted([...packs,...finalPacks])}if(kind==="docs"){add3("docs");return uniqueSorted(packs)}add3("frontend",isFrontend);add3("react",isFrontend);add3("nextjs",isFrontend);add3("tanstack-query",isFrontend);add3("backend",isBackend&&!isFrontend);add3("elysia",isBackend&&!isFrontend);add3("effect",isBackend&&!isFrontend);add3("trpc",isBackend&&!isFrontend);add3("subagents",relativeWorkspacePath==="apps/cli");add3("turborepo",relativeWorkspacePath==="apps/cli");add3("better-auth",relativeWorkspacePath==="packages/auth");add3("effect",hasDependency("effect")||hasDependencyPrefix("@effect/"));add3("drizzle",hasDependency("drizzle-orm")||hasDependency("drizzle-kit"));add3("better-auth",hasDependency("better-auth"));add3("elysia",hasDependency("elysia"));add3("nextjs",hasDependency("next"));add3("react",hasDependency("react")||hasDependency("react-dom"));add3("tanstack-query",hasDependency("@tanstack/react-query")||hasDependency("@tanstack/query-core")||hasDependency("@tanstack/react-query-devtools")||hasDependency("@tanstack/react-query-persist-client")||hasDependency("@tanstack/query-persist-client-core"));add3("trpc",hasDependencyPrefix("@trpc/"));add3("turborepo",hasDependency("turbo"));return uniqueSorted(packs)};var resolveContextScopeSelectionSync=({baseline,finalPacks,scope:scope3})=>{const packsById=new Map(baseline.packs.map((pack)=>[pack.id,pack]));const skillsById=new Map(baseline.skills.map((skill)=>[skill.id,skill]));const packs=packsForScope({...scope3,finalPacks});const skillIds=uniqueSorted(packs.flatMap((packId)=>requireCatalogEntry(packsById,packId,"pack").skills));for(const skillId of skillIds){requireCatalogEntry(skillsById,skillId,"skill")}return{packs,skillIds}};var resolveContextScopeSelection=fn2("ContextPlanning.resolveScopeSelection")(function*resolveContextScopeSelection2(input2){return yield*try_3({catch:(cause)=>cause instanceof ContextPlanResolutionFailure?cause:new ContextPlanCompilationFailure({cause,message:"Context scope selection failed.",operation:"compile-context-plan"}),try:()=>resolveContextScopeSelectionSync(input2)})});var provenanceFor=(baseline)=>({revision:baseline.summary.commit??baseline.summary.tag??baseline.summary.version,source:baseline.summary.source});var contribution=({kind,id,references,compatibility,baseline,order,contract})=>{const base={compatibility,identity:{id,version:baseline.summary.version},kind,order,provenance:provenanceFor(baseline),references:uniqueSorted(references)};return decodeUnknownSync(ContextContribution)(contract===undefined?{...base,kind}:{...base,contract,kind})};var commitGateContributionFor=({scope:scope3})=>{const{manifest}=scope3;if(manifest?.packageManager===undefined){return null}const candidate=manifest.qualityCommandContract??{};const missing=["lint","formatCheck"].filter((key)=>candidate[key]===undefined||candidate[key]?.trim()==="");if(missing.length>0){throw new IncompleteQualityCommandContract({cause:new Error(`Missing Commit Gate commands: ${missing.join(", ")}.`),id:scope3.id,message:`Commit Gate Consumer ${scope3.id} has an incomplete Quality Command Contract.${candidate.unresolvedReason===undefined?"":` ${candidate.unresolvedReason}`}`,missing,operation:"compile-context-plan"})}const{formatCheck:formatCheck2,lint}=candidate;if(formatCheck2===undefined||lint===undefined){return null}const commandPrefix=(command)=>{if(manifest.packageManager!=="npm"){return`${manifest.packageManager} `}return command.startsWith("run ")?"npm ":"npm exec -- "};return{contract:{formatCheck:formatCheck2.startsWith("npm ")||formatCheck2.startsWith("npm exec ")?formatCheck2:`${commandPrefix(formatCheck2)}${formatCheck2}`,lint:lint.startsWith("npm ")||lint.startsWith("npm exec ")?lint:`${commandPrefix(lint)}${lint}`},id:`${scope3.id}:commit-gate`}};var promptSurfaceFor={docs:"docs-prompt-spec",root:"root-prompt-spec",shared:"shared-agents",workspace:"workspace-prompt-spec"};var contributionsForScope=({scope:scope3,packs,input:input2,onBlockedQualityConsumer})=>{const packsById=new Map(input2.baseline.packs.map((pack)=>[pack.id,pack]));const skillsById=new Map(input2.baseline.skills.map((skill)=>[skill.id,skill]));const resolvedSkillsById=new Map(input2.resolvedSkills.map((skill)=>[skill.id,skill]));const toolsById=new Map(input2.baseline.tools.map((tool)=>[tool.id,tool]));const capabilityGroupsById=new Map(input2.capabilityGroups.map((group2)=>[group2.id,group2.skills]));const scopePacks=packs.map((pack)=>requireCatalogEntry(packsById,pack,"pack"));const skillIds=uniqueSorted(scopePacks.flatMap((pack)=>pack.skills));const promptSurface=promptSurfaceFor[scope3.kind];const contributions=skillIds.map((id)=>{requireCatalogEntry(skillsById,id,"skill");const resolved=requireResolvedSkill(resolvedSkillsById,id);return{compatibility:resolved.compatibility,id,kind:"skill",references:resolved.references}});if(scopePacks.some((pack)=>pack.promptSurfaces.includes(promptSurface))){contributions.push({compatibility:[],id:`${scope3.id}:${promptSurface}`,kind:"scoped-prompt",references:[]})}if(scope3.kind==="root"){const includeFormatHook=input2.detection.detectedLanguages.includes("python")||input2.detection.manifests.some((manifest)=>manifest.dependencies.includes("oxfmt"));const hookIds=uniqueSorted(["scaffold-update-check",...scopePacks.flatMap((pack)=>pack.hooks)]).filter((id)=>id!=="format-edited-file"||includeFormatHook);contributions.push(...hookIds.map((id)=>({compatibility:[],id,kind:"lifecycle-hook",references:[]})));const toolIds=uniqueSorted(["agent-browser","opensrc","portless","skills",...skillIds.flatMap((id)=>requireCatalogEntry(skillsById,id,"skill").requiresTools)]).map((id)=>requireCatalogEntry(toolsById,id,"tool").id);contributions.push(...toolIds.map((id)=>({compatibility:[],id,kind:"tool-configuration",references:[]})))}let commitGate=null;try{commitGate=commitGateContributionFor({scope:scope3})}catch(error2){if(!(error2 instanceof IncompleteQualityCommandContract)||onBlockedQualityConsumer===undefined){throw error2}onBlockedQualityConsumer({cause:error2,contribution:{id:`${scope3.id}:commit-gate`,version:input2.baseline.summary.version},scopeId:scope3.id})}if(commitGate!==null){contributions.push({compatibility:[],contract:commitGate.contract,id:commitGate.id,kind:"commit-gate",references:[]})}contributions.push(...input2.subagentTemplates.filter((template)=>template.scopeId===scope3.id).map((template)=>({compatibility:[],id:template.id,kind:"subagent-template",references:uniqueSorted(template.capabilityGroups.flatMap((groupId)=>requireCatalogEntry(capabilityGroupsById,groupId,"capability group").map((skillId)=>{const resolved=resolvedSkillsById.get(skillId);if(!skillsById.has(skillId)&&resolved===undefined){throw resolutionFailure(skillId,"skill",`Unknown skill: ${skillId}`)}return requireResolvedSkill(resolvedSkillsById,skillId).id})))})));return contributions.map(({kind,id,references,compatibility,...rest},order)=>contribution({baseline:input2.baseline,compatibility,id,kind,order,references,..."contract"in rest?{contract:rest.contract}:{}}))};var scopeAuthoringIdentity2=({input:input2,scope:scope3,contributions})=>{const capability=input2.baseline.capabilities?.scopedAuthoring;const selected=uniqueSorted(contributions.flatMap((entry)=>{if(entry.kind==="skill"){return[entry.identity.id]}if(entry.kind==="subagent-template"){return entry.references}return[]}));const declarations=new Map(capability?.skills.map((entry)=>[entry.id,entry]));if(capability!==undefined&&declarations.size!==capability.skills.length){throw new Error("Duplicate scoped authoring skill contract declarations.")}const contracts=[];const missingContracts=[];if(capability===undefined){missingContracts.push("generated-authoring")}else{contracts.push({activationRevision:capability.revision,authoringRevision:capability.revision,id:"generated-authoring"})}for(const id of selected){const declared=declarations.get(id);if(declared===undefined){missingContracts.push(`skill:${id}`)}else{contracts.push({...declared,id:`skill:${id}`})}}return{contracts,kind:scope3.kind,missingContracts,path:scope3.relativeWorkspacePath}};var compileContextPlanSync=(input2,onBlockedQualityConsumer)=>({scopes:input2.scopes.map((scope3)=>{const{packs}=resolveContextScopeSelectionSync({baseline:input2.baseline,finalPacks:input2.finalPacks,scope:scope3});const contributions=contributionsForScope({input:input2,onBlockedQualityConsumer,packs,scope:scope3});return{authoring:scopeAuthoringIdentity2({contributions,input:input2,scope:scope3}),contributions,id:scope3.id,packs:packs.map((id,order)=>({id,order}))}}).toSorted((left,right)=>left.id.localeCompare(right.id)),version:"1"});var compileContextPlan=fn2("ContextPlanning.compile")(function*compileContextPlan2(input2){return yield*try_3({catch:(cause)=>cause instanceof ContextPlanResolutionFailure||cause instanceof IncompleteQualityCommandContract?cause:new ContextPlanCompilationFailure({cause,message:"Context plan compilation failed.",operation:"compile-context-plan"}),try:()=>compileContextPlanSync(input2)})});var assessContextPlan=fn2("ContextPlanning.assess")(function*assessContextPlan2(input2){return yield*try_3({catch:(cause)=>cause instanceof ContextPlanResolutionFailure?cause:new ContextPlanCompilationFailure({cause,message:"Context plan assessment failed.",operation:"compile-context-plan"}),try:()=>{const blockedQualityConsumers=[];const contextPlan=compileContextPlanSync(input2,(consumer)=>{blockedQualityConsumers.push(consumer)});return{_tag:"ContextPlanAssessment",blockedQualityConsumers,contextPlan}}})});var nonEmptyString2=(value5,fallback="unknown")=>typeof value5==="string"&&value5.length>0?value5:fallback;var adapterIdentity=(matrix)=>({id:nonEmptyString2(matrix?.adapter?.id),version:nonEmptyString2(matrix?.adapter?.version)});var traceFor=({adapter,contextPlan,scope:scope3,contribution:contribution2})=>({contextPlanVersion:nonEmptyString2(contextPlan?.version),scopeId:nonEmptyString2(scope3?.id),kind:nonEmptyString2(contribution2?.kind,"skill"),contribution:{id:nonEmptyString2(contribution2?.identity?.id,"context-plan"),version:nonEmptyString2(contribution2?.identity?.version)},adapter:adapterIdentity(adapter?.matrix),matrixVersion:nonEmptyString2(adapter?.matrix?.matrixVersion)});var capabilityFamilies=["skill","scoped-prompt","lifecycle-hook","tool-configuration","subagent-template"];var isObject2=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var capabilityRowIssue=(row)=>{const allowedKeys=row.support==="supported"?["family","support"]:["family","support","reason"];if(Object.keys(row).some((key)=>!allowedKeys.includes(key))){return`Adapter matrix capability for ${row.family} has unexpected fields`}if(row.support==="supported"){return}if((row.support==="degraded"||row.support==="unsupported")&&typeof row.reason==="string"&&row.reason.length>0){return}return`Adapter matrix capability for ${row.family} has invalid support`};var validateCapabilityMatrix=(matrix)=>{const metadataIssues=[];if(!isObject2(matrix)){metadataIssues.push("Adapter matrix must be an object")}else{if(typeof matrix.matrixVersion!=="string"||matrix.matrixVersion.length===0){metadataIssues.push("Adapter matrix version must be a non-empty string")}if(!isObject2(matrix.adapter)){metadataIssues.push("Adapter identity must be an object")}else{if(typeof matrix.adapter.id!=="string"||matrix.adapter.id.length===0){metadataIssues.push("Adapter id must be a non-empty string")}if(typeof matrix.adapter.version!=="string"||matrix.adapter.version.length===0){metadataIssues.push("Adapter version must be a non-empty string")}}}if(!isObject2(matrix)||!Array.isArray(matrix.capabilities)){return{capabilities:new Map,globalIssue:[...metadataIssues,"Adapter matrix capabilities must be an array"].join("; ")}}const unknownRows=matrix.capabilities.filter((row)=>!isObject2(row)||!capabilityFamilies.includes(row.family));if(unknownRows.length>0){return{capabilities:new Map,globalIssue:[...metadataIssues,"Adapter matrix contains an unknown or malformed capability row"].join("; ")}}const familyIssues=new Map;const validRows=[];for(const family of capabilityFamilies){const rows=matrix.capabilities.filter((row)=>row.family===family);if(rows.length!==1){familyIssues.set(family,`Adapter matrix must contain exactly one capability for ${family}; found ${rows.length}`);continue}const issue=capabilityRowIssue(rows[0]);if(issue===undefined){validRows.push(rows[0])}else{familyIssues.set(family,issue)}}const globalIssue=[...metadataIssues,...familyIssues.values()].join("; ")||undefined;return{capabilities:globalIssue===undefined?new Map(validRows.map((row)=>[row.family,row])):new Map,globalIssue}};function project({adapter,contextPlan}){const{capabilities,globalIssue}=validateCapabilityMatrix(adapter.matrix);const actions=[];const applied=[];const omissions=[];const errors3=[];let contributionCount=0;for(const scope3 of contextPlan.scopes){for(const contribution2 of scope3.contributions){if(contribution2.kind==="commit-gate"){continue}contributionCount+=1;const capability=capabilities.get(contribution2.kind);const trace2=traceFor({adapter,contextPlan,scope:scope3,contribution:contribution2});if(globalIssue!==undefined){errors3.push({_tag:"InvalidHarnessProjectionError",trace:trace2,message:globalIssue});continue}if(capability.support==="unsupported"){omissions.push({_tag:"HarnessProjectionOmission",support:"unsupported",trace:trace2,warning:{_tag:"UnsupportedHarnessCapabilityWarning",family:contribution2.kind,reason:capability.reason}});continue}let projected;try{projected=adapter.project({scopeId:scope3.id,contribution:contribution2,capability})}catch(error2){errors3.push({_tag:"HarnessAdapterDefectError",trace:trace2,message:error2 instanceof Error?error2.message:"Adapter defect"});continue}if(isObject2(projected)&&projected._tag==="HarnessProjectionUnsupported"&&typeof projected.reason==="string"&&projected.reason.length>0){if(capability.support!=="degraded"){errors3.push({_tag:"InvalidHarnessProjectionError",trace:trace2,message:"Adapter declared unsupported for a supported capability"});continue}omissions.push({_tag:"HarnessProjectionOmission",support:"unsupported",trace:trace2,warning:{_tag:"UnsupportedHarnessCapabilityWarning",family:contribution2.kind,reason:projected.reason}});continue}if(!Array.isArray(projected)||projected.length===0||projected.some((action2)=>typeof action2!=="object"||action2===null||typeof action2.id!=="string"||action2.id.length===0)){errors3.push({_tag:"InvalidHarnessProjectionError",trace:trace2,message:"Adapter must return at least one identified action"});continue}actions.push(...projected.map((action2)=>({...action2,trace:trace2})));applied.push({_tag:"HarnessProjectionApplied",support:capability.support,trace:trace2,...capability.support==="degraded"?{reason:capability.reason}:{}})}}if(globalIssue!==undefined&&contributionCount===0){errors3.push({_tag:"InvalidHarnessProjectionError",trace:traceFor({adapter,contextPlan}),message:globalIssue})}return{actions,summary:errors3.length>0?{_tag:"HarnessProjectionFailure",completed:applied,omissions,errors:errors3}:omissions.length===0?{_tag:"HarnessProjectionSuccess",applied}:{_tag:"HarnessProjectionPartial",applied,omissions}}}var promptPaths=(scopeId)=>scopeId===".agents"||scopeId==="shared"?{source:".agents/AGENTS.md",target:".claude/CLAUDE.md"}:scopeId==="root"?{source:"AGENTS.md",target:"CLAUDE.md"}:{source:`${scopeId}/AGENTS.md`,target:`${scopeId}/CLAUDE.md`};var hookConfiguration=(id)=>{if(id==="format-edited-file"){return{path:["hooks","PostToolUse"],value:{matcher:"Edit|Write|MultiEdit",hooks:[{type:"command",command:'node "$CLAUDE_PROJECT_DIR"/.claude/hooks/format-edited-file.mjs claude',timeout:30}]}}}if(id==="scaffold-update-check"){return{path:["hooks","SessionStart"],value:{hooks:[{type:"command",command:'node "$CLAUDE_PROJECT_DIR"/.claude/hooks/scaffold-update-check.mjs claude',timeout:60}]}}}};var projectContribution=({scopeId,contribution:contribution2})=>{const id=`claude:${contribution2.kind}:${scopeId}:${contribution2.identity.id}`;switch(contribution2.kind){case"skill":return[{id,operation:"use-native-mirror",canonicalPath:`.agents/skills/${contribution2.identity.id}`,nativePath:`.claude/skills/${contribution2.identity.id}`}];case"scoped-prompt":return[{id,operation:"mirror",...promptPaths(scopeId)}];case"lifecycle-hook":{const configuration=hookConfiguration(contribution2.identity.id);if(configuration===undefined){return{_tag:"HarnessProjectionUnsupported",reason:`Claude lifecycle hook ${contribution2.identity.id} has no native projection`}}return[{id:`${id}:mirror`,operation:"mirror",source:`.agents/hooks/${contribution2.identity.id}.mjs`,target:`.claude/hooks/${contribution2.identity.id}.mjs`},{id:`${id}:configure`,operation:"merge-json",target:`.claude/settings.json#${configuration.path.join(".")}:${contribution2.identity.id}`,file:".claude/settings.json",responseMode:"claude-post-tool-use-context",...configuration}]}case"subagent-template":return[{id,operation:"render-template",templateId:contribution2.identity.id,source:`.agents/subagents/manifest.mjs#${contribution2.identity.id}`,filename:`${contribution2.identity.id}.md`,target:`.claude/agents/${contribution2.identity.id}.md`,format:"claude-markdown",skills:contribution2.references}];case"tool-configuration":return[]}};var claudeAdapter={matrix:{matrixVersion:"2026.07.17-v1",adapter:{id:"claude",version:"1.0.0"},capabilities:[{family:"skill",support:"degraded",reason:"Skills use the shared Claude compatibility mirror rather than per-scope registrations"},{family:"scoped-prompt",support:"supported"},{family:"lifecycle-hook",support:"degraded",reason:"Only SessionStart and file-edit command hooks have native Claude projections"},{family:"tool-configuration",support:"unsupported",reason:"Harness tool configuration is not projected into Claude settings"},{family:"subagent-template",support:"supported"}]},project:projectContribution};var promptIntent=({id,scopeId})=>scopeId===".agents"||scopeId==="shared"?{id,operation:"mirror",source:".agents/AGENTS.md",target:".codex/AGENTS.md"}:{id,operation:"use-native-prompt",canonicalPath:scopeId==="root"?"AGENTS.md":`${scopeId}/AGENTS.md`};var hookEntries=(id)=>{if(id==="format-edited-file"){return[{event:"SessionStart",matcher:"startup|resume",command:'node "$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs" session-start',statusMessage:"Capturing edited-file baseline",timeout:30},{event:"PostToolUse",matcher:"Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit",command:'node "$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs" post',statusMessage:"Auto-formatting edited files",timeout:30}]}if(id==="scaffold-update-check"){return[{event:"SessionStart",matcher:"startup|resume",command:'node "$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs" codex',statusMessage:"Checking Harness scaffold",timeout:60}]}return[]};var projectContribution2=({scopeId,contribution:contribution2})=>{const id=`codex:${contribution2.kind}:${scopeId}:${contribution2.identity.id}`;switch(contribution2.kind){case"skill":return[{id,operation:"use-native-skill",canonicalPath:`.agents/skills/${contribution2.identity.id}`}];case"scoped-prompt":return[promptIntent({id,scopeId})];case"lifecycle-hook":{const entries=hookEntries(contribution2.identity.id);if(entries.length===0){return{_tag:"HarnessProjectionUnsupported",reason:`Codex lifecycle hook ${contribution2.identity.id} has no native projection`}}return[{id:`${id}:mirror`,operation:"mirror",source:`.agents/hooks/${contribution2.identity.id}.mjs`,target:`.codex/hooks/${contribution2.identity.id}.mjs`},{id:`${id}:configure`,operation:"merge-toml",target:`.codex/config.toml#hook:${contribution2.identity.id}`,file:".codex/config.toml",entries,responseMode:"codex-post-tool-use-block"}]}case"subagent-template":return[{id,operation:"render-template",templateId:contribution2.identity.id,source:`.agents/subagents/manifest.mjs#${contribution2.identity.id}`,filename:`${contribution2.identity.id}.toml`,target:`.codex/agents/${contribution2.identity.id}.toml`,format:"codex-toml",skills:contribution2.references.map((skillId)=>({id:skillId,path:`../../.agents/skills/${skillId}`,enabled:true}))}];case"tool-configuration":return[]}};var codexAdapter={matrix:{matrixVersion:"2026.07.17-v1",adapter:{id:"codex",version:"1.0.0"},capabilities:[{family:"skill",support:"degraded",reason:"Skills are linked only from the Codex subagent templates that reference them"},{family:"scoped-prompt",support:"supported"},{family:"lifecycle-hook",support:"degraded",reason:"Only SessionStart and PostToolUse command hooks have native Codex projections"},{family:"tool-configuration",support:"unsupported",reason:"Harness tool configuration is not projected into Codex config"},{family:"subagent-template",support:"supported"}]},project:projectContribution2};var cursorCapabilityMatrix={matrixVersion:"2026.07.17-v1",adapter:{id:"cursor",version:"1.0.0"},capabilities:[{family:"skill",support:"supported"},{family:"scoped-prompt",support:"supported"},{family:"lifecycle-hook",support:"degraded",reason:"Only session-start and file-edit command hooks have native Cursor projections"},{family:"tool-configuration",support:"unsupported",reason:"Harness tool configuration is not projected into Cursor settings"},{family:"subagent-template",support:"supported"}]};var hookConfig=new Map([["scaffold-update-check",{event:"sessionStart",command:"node .cursor/hooks/scaffold-update-check.mjs cursor",timeout:60000}],["format-edited-file",{event:"afterFileEdit",command:"node .cursor/hooks/format-edited-file.mjs cursor"}]]);var cursorProject=({scopeId,contribution:contribution2})=>{const contributionId=contribution2.identity.id;switch(contribution2.kind){case"skill":return[{id:`cursor:skill:${scopeId}:${contributionId}`,operation:"native",source:`.agents/skills/${contributionId}/SKILL.md`,contributionId}];case"scoped-prompt":{const target=scopeId===".agents"||scopeId==="shared"?".agents/AGENTS.md":scopeId==="root"?"AGENTS.md":`${scopeId}/AGENTS.md`;return[{id:`cursor:scoped-prompt:${scopeId}:${contributionId}`,operation:"native",source:target,target,contributionId}]}case"lifecycle-hook":{const config=hookConfig.get(contributionId);if(config===undefined){return{_tag:"HarnessProjectionUnsupported",reason:`Cursor lifecycle hook ${contributionId} has no native projection`}}return[{id:`cursor:lifecycle-hook:${scopeId}:${contributionId}`,operation:"mirror",source:`.agents/hooks/${contributionId}.mjs`,target:`.cursor/hooks/${contributionId}.mjs`,config:{path:".cursor/hooks.json",...config},responseMode:"cursor-user-message",contributionId}]}case"subagent-template":return[{id:`cursor:subagent-template:${scopeId}:${contributionId}`,operation:"render",target:`.cursor/agents/${contributionId}.md`,format:"cursor-subagent-v1",contributionId}];default:throw new Error(`Cursor received non-projectable ${contribution2.kind} contribution`)}};var cursorAdapter={matrix:cursorCapabilityMatrix,project:cursorProject};var openCodeCapabilityMatrix={matrixVersion:"2026.07.17-v1",adapter:{id:"opencode",version:"1.0.0"},capabilities:[{family:"skill",support:"supported"},{family:"scoped-prompt",support:"supported"},{family:"lifecycle-hook",support:"degraded",reason:"Only the formatter hook has a native OpenCode lifecycle projection"},{family:"tool-configuration",support:"unsupported",reason:"Harness-required CLI tools are operator prerequisites, not OpenCode configuration"},{family:"subagent-template",support:"supported"}]};var openCodeProject=({scopeId,contribution:contribution2})=>{const contributionId=contribution2.identity.id;switch(contribution2.kind){case"skill":return[{id:`opencode:skill:${scopeId}:${contributionId}`,operation:"native",source:`.agents/skills/${contributionId}/SKILL.md`,contributionId}];case"scoped-prompt":{const source=scopeId===".agents"||scopeId==="shared"?".agents/AGENTS.md":scopeId==="root"?"AGENTS.md":`${scopeId}/AGENTS.md`;return[{id:`opencode:scoped-prompt:${scopeId}:${contributionId}`,operation:scopeId===".agents"||scopeId==="shared"?"mirror":"native",source,target:scopeId===".agents"||scopeId==="shared"?".opencode/AGENTS.md":source,contributionId}]}case"lifecycle-hook":if(contributionId!=="format-edited-file"){return{_tag:"HarnessProjectionUnsupported",reason:`OpenCode lifecycle hook ${contributionId} has no native projection`}}return[{id:`opencode:lifecycle-hook:${scopeId}:${contributionId}:mirror`,operation:"mirror",source:`.agents/hooks/${contributionId}.mjs`,target:`.opencode/plugins/${contributionId}.mjs`,responseMode:"opencode-structured-log",contributionId}];case"subagent-template":return[{id:`opencode:subagent-template:${scopeId}:${contributionId}`,operation:"render",target:`.opencode/agents/${contributionId}.md`,format:"opencode-subagent-v1",contributionId}];default:throw new Error(`OpenCode received non-projectable ${contribution2.kind} contribution`)}};var openCodeAdapter={matrix:openCodeCapabilityMatrix,project:openCodeProject};import{spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash9}from"node:crypto";import{cpSync,existsSync as existsSync9,mkdtempSync as mkdtempSync3,readFileSync as readFileSync11,readdirSync as readdirSync3,realpathSync as realpathSync5,rmSync as rmSync3,readlinkSync as readlinkSync3,mkdirSync as mkdirSync5,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir6}from"node:os";import path25 from"node:path";var childEnvironment=(baseEnvironment,overrides)=>{const env={};for(const[key,value5]of Object.entries(baseEnvironment??process.env)){if(value5!==undefined){env[key]=value5}}for(const[key,value5]of Object.entries(overrides??{})){if(value5===undefined){Reflect.deleteProperty(env,key)}else{env[key]=value5}}return env};var processOutputMaxBuffer=256*1024*1024;var nodeProcess={capture:(command,args2,options4)=>{const result4=spawnSync2(command,args2,{cwd:options4?.cwd,encoding:"utf-8",env:childEnvironment(options4?.baseEnvironment,options4?.env),maxBuffer:processOutputMaxBuffer,stdio:["ignore","pipe","pipe"]});return{...result4.error===undefined?{}:{error:result4.error},status:result4.status,stderr:result4.stderr,stdout:result4.stdout}},execute:(command,args2,options4)=>{const result4=nodeProcess.capture(command,args2,options4);if(result4.status!==0){throw Object.assign(new Error(`Process exited with status ${result4.status??"unknown"}.`),{cause:result4.error,...result4})}}};var scriptRuntimePath=(configured="node")=>configured;var runJavaScriptFileSync=({file:file5,cwd,runtimePath="node",environment=process.env,environmentOverrides={}})=>{nodeProcess.execute(scriptRuntimePath(runtimePath),[file5],{baseEnvironment:environment,cwd,env:environmentOverrides})};var previewLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var isWithin=(root,value5)=>{const relative=path25.relative(root,value5);return relative===""||!path25.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path25.sep}`)};var hashFile=(file5)=>createHash9("sha256").update(readFileSync11(file5)).digest("hex");var copyPreviewTree=(source,destination)=>{cpSync(source,destination,{filter:(entry)=>{const relative=path25.relative(source,entry).split(path25.sep).join("/");return relative===""||!relative.split("/").some((segment)=>segment===".git"||segment==="node_modules")},recursive:true,verbatimSymlinks:true})};var restoreLivePackageManifests=(liveRoot,candidate)=>{const visit2=(sourceDirectory)=>{for(const entry of readdirSync3(sourceDirectory,{withFileTypes:true})){if(entry.name===".git"||entry.name==="node_modules"){continue}const source=path25.join(sourceDirectory,entry.name);const relative=path25.relative(liveRoot,source);const target=path25.join(candidate,relative);if(entry.isDirectory()){visit2(source)}else if(entry.isFile()&&entry.name==="package.json"){mkdirSync5(path25.dirname(target),{recursive:true});cpSync(source,target)}}};visit2(liveRoot)};var validatePreviewSymlinks=(candidate)=>{const canonicalRoot=realpathSync5(candidate);const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){const current=path25.join(directory3,entry.name);if(entry.isSymbolicLink()){if(!isWithin(canonicalRoot,realpathSync5(current))){throw new Error(`Candidate symlink escapes preview root: ${path25.relative(candidate,current)}`)}}else if(entry.isDirectory()){visit2(current)}}};visit2(candidate)};var fingerprintLiveState=(root)=>{const values=[];const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true}).toSorted((left,right)=>left.name.localeCompare(right.name))){const absolute=path25.join(directory3,entry.name);const relative=path25.relative(root,absolute).split(path25.sep).join("/");if(relative===".git"||relative.startsWith(".git/")||relative==="node_modules"||relative.startsWith("node_modules/")){continue}if(entry.isDirectory()){if(entry.name===".yarn"||entry.name.startsWith(".pnp")){values.push(`${relative}:directory:${realpathSync5(absolute)}`)}else{visit2(absolute)}}else if(entry.isSymbolicLink()){values.push(`${relative}:symlink:${readlinkSync3(absolute)}`)}else if(entry.isFile()&&(entry.name==="package.json"||previewLockfiles.includes(entry.name)||/\.(?:[cm]?ts|tsx|jsx?|json)$/u.test(entry.name))){values.push(`${relative}:file:${hashFile(absolute)}`)}}};visit2(root);return createHash9("sha256").update(values.toSorted().join(`
2471
2471
  `)).digest("hex")};var hasLintConfiguration=(candidate)=>{const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(entry.name==="node_modules"||entry.name===".git"){continue}const absolute=path25.join(directory3,entry.name);if(entry.isDirectory()?visit2(absolute):/^(?:\.oxlintrc(?:\..+)?|oxlint\.config\..+)$/u.test(entry.name)){return true}}return false};return visit2(candidate)};var findLocalOxlint=(directory3,candidateRoot)=>{let current=directory3;while(isWithin(candidateRoot,current)){const options4=[path25.join(current,"node_modules",".bin","oxlint"),path25.join(current,"node_modules","oxlint","bin","oxlint")];const executable=options4.find((value5)=>existsSync9(value5));if(executable!==undefined){return executable}if(current===candidateRoot){break}current=path25.dirname(current)}return null};var findLocalEffectTsgo=(directory3,candidateRoot)=>{let current=directory3;while(isWithin(candidateRoot,current)){const executable=path25.join(current,"node_modules",".bin","effect-tsgo");if(existsSync9(executable)){return executable}if(current===candidateRoot){break}current=path25.dirname(current)}return null};var commandText=(command,args2)=>[command,...args2].join(" ");var hasOnlyModuleTypeWarnings=(stderr)=>{const lines2=stderr.split(/\r?\n/u).filter((line)=>line.trim().length>0);return lines2.length>0&&lines2.every((line)=>{const normalized=line.trim();return/^\(node:\d+\) \[MODULE_TYPELESS_PACKAGE_JSON\] Warning: Module type of .+ is not specified and it doesn't parse as CommonJS\.$/u.test(normalized)||normalized==="Reparsing as ES module because module syntax was detected. This incurs a performance overhead."||/^To eliminate this warning, add "type": "module" to .+\.$/u.test(normalized)||normalized==="(Use `node --trace-warnings ...` to show where the warning was created)"})};var oxlintJsonOutput=(stdout)=>{const zeroFileNotices=["No files found matching given patterns.","No files found to lint. Please check your paths and ignore patterns."];const notice=zeroFileNotices.find((candidate)=>stdout.startsWith(`${candidate}
2472
2472
  `));return notice===undefined?{json:stdout,zeroFiles:false}:{json:stdout.slice(notice.length+1),zeroFiles:true}};var previewFailure=(failure)=>new LintPreviewFacts({failure,findingCount:0,findings:[],kind:"lint-preview",status:"operational-failure",truncated:false});var isRecord7=(value5)=>typeof value5==="object"&&value5!==null;var parseFinding=(candidate,value5)=>{if(!isRecord7(value5)){return null}const item=value5;const labels=Array.isArray(item.labels)?item.labels:[];const label=isRecord7(labels[0])?labels[0]:{};const span=isRecord7(label.span)?label.span:label;const rawFile=typeof item.file==="string"?item.file:typeof item.filename==="string"?item.filename:typeof label.file==="string"?label.file:"";const line=Number(item.line??span.line??label.line??1);const column=Number(item.column??span.column??label.column??1);if(!Number.isFinite(line)||!Number.isFinite(column)){return null}const finding={column:Math.max(1,column),file:rawFile.length===0?"":path25.relative(candidate,path25.resolve(candidate,rawFile)).split(path25.sep).join("/"),line:Math.max(1,line),message:typeof item.message==="string"?item.message:"Lint finding",rule:typeof item.code==="string"?item.code:typeof item.rule_id==="string"?item.rule_id:"unknown",severity:item.severity==="error"||item.severity===2?"error":"warning"};const helpUrl=typeof item.doc_url==="string"?item.doc_url:typeof item.helpUrl==="string"?item.helpUrl:undefined;return helpUrl===undefined?finding:{...finding,helpUrl}};var isOutputOverflow=(error2)=>typeof error2==="object"&&error2!==null&&("code"in error2)&&error2.code==="ENOBUFS";var parseAgentOutput=(candidate,output2)=>{const findings=[];for(const line of output2.split(/\r?\n/u)){if(line.trim().length===0){continue}const match8=/^(?<file>.*?):(?<line>\d+):(?<column>\d+): (?<severity>error|warning)(?: (?<rule>[^:]+))?: (?<message>.*?)(?: help: (?<help>.*))?$/u.exec(line);if(match8===null){const context3=/^(?<file>.*?):(?<line>\d+):(?<column>\d+): (?<message>.+)$/u.exec(line);const previous=findings.at(-1);const contextGroups=context3?.groups;if(contextGroups!==undefined&&previous!==undefined&&previous.file===path25.relative(candidate,path25.resolve(candidate,contextGroups.file??"")).split(path25.sep).join("/")&&previous.line===Number(contextGroups.line)&&previous.column===Number(contextGroups.column)){continue}return{findings:[],invalidLine:line.slice(0,240)}}const groups=match8.groups??{};const finding=parseFinding(candidate,{code:groups.rule?.trim()||"unknown",column:groups.column,doc_url:groups.help,file:groups.file,line:groups.line,message:groups.message?.trim()??"",severity:groups.severity==="error"?"error":"warning"});if(finding===null){return{findings:[],invalidLine:line.slice(0,240)}}findings.push(finding)}return{findings}};var cleanPreview=()=>new LintPreviewFacts({findingCount:0,findings:[],kind:"lint-preview",status:"clean",truncated:false});var normalizedCandidatePath=(candidate,relativePath)=>{if(path25.isAbsolute(relativePath)){throw new Error(`Candidate removal path must be relative: ${relativePath}`)}const normalized=path25.normalize(relativePath);const absolute=path25.resolve(candidate,normalized);if(normalized==="."||!isWithin(candidate,absolute)){throw new Error(`Candidate removal path escapes preview root: ${relativePath}`)}return absolute};var removePreviewPaths=(candidate,removePaths)=>{const canonicalRoot=realpathSync5(candidate);for(const relativePath of removePaths){const absolute=normalizedCandidatePath(candidate,relativePath);if(!existsSync9(absolute)){continue}if(!isWithin(canonicalRoot,realpathSync5(absolute))){throw new Error(`Candidate removal path escapes preview root: ${relativePath}`)}rmSync3(absolute,{force:true,recursive:false})}};var preparePreviewCandidate=(liveRoot,stagedRoot,candidate,removePaths,manifestSource)=>{const canonicalLiveRoot=realpathSync5(liveRoot);const canonicalCandidateRoot=realpathSync5(candidate);if(isWithin(canonicalLiveRoot,canonicalCandidateRoot)||isWithin(canonicalCandidateRoot,canonicalLiveRoot)){throw new Error("Candidate root overlaps the live repository root.")}const marker=path25.join(candidate,".devpunks","lint-preview-marker");mkdirSync5(path25.dirname(marker),{recursive:true});const markerValue=`${path25.basename(candidate)}:${Date.now()}`;writeFileSync5(marker,markerValue);copyPreviewTree(liveRoot,candidate);copyPreviewTree(stagedRoot,candidate);if(manifestSource==="live"){restoreLivePackageManifests(liveRoot,candidate)}if(readFileSync11(marker,"utf-8")!==markerValue){throw new Error("Candidate ownership marker was not preserved.")}removePreviewPaths(candidate,removePaths);validatePreviewSymlinks(candidate)};var packageDirectories=(root)=>{const directories=[];const visit2=(directory3)=>{if(existsSync9(path25.join(directory3,"package.json"))){directories.push(directory3)}for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(entry.isDirectory()&&entry.name!=="node_modules"&&entry.name!==".git"){visit2(path25.join(directory3,entry.name))}}};visit2(root);return directories};var manifestFingerprint=(root)=>createHash9("sha256").update(packageDirectories(root).map((directory3)=>`${path25.relative(root,directory3)}:${hashFile(path25.join(directory3,"package.json"))}`).toSorted().join(`
2473
- `)).digest("hex");var candidateWorkspaces=(candidate,packageJson)=>{const{workspaces}=packageJson;const patterns=Array.isArray(workspaces)?workspaces:typeof workspaces==="object"&&workspaces!==null&&("packages"in workspaces)?workspaces.packages:[];if(!Array.isArray(patterns)||!patterns.every((pattern)=>typeof pattern==="string")){throw new Error("Candidate workspace patterns must be strings.")}return packageDirectories(candidate).filter((directory3)=>{const relative=path25.relative(candidate,directory3).split(path25.sep).join("/");return relative!==""&&patterns.some((pattern)=>!pattern.startsWith("!")&&path25.matchesGlob(relative,pattern))&&!patterns.some((pattern)=>pattern.startsWith("!")&&path25.matchesGlob(relative,pattern.slice(1)))})};var candidatePackageJson=(candidate)=>{const packagePath=path25.join(candidate,"package.json");if(!existsSync9(packagePath)){throw new Error("Candidate package manifest is missing.")}const packageJson=JSON.parse(readFileSync11(packagePath,"utf-8"));if(!isRecord7(packageJson)){throw new Error("Candidate package manifest must be an object.")}return packageJson};var candidateInstallationRoots=(candidate,selectedRoots)=>{const selected=[...new Set(selectedRoots.map((relative)=>{if(path25.isAbsolute(relative)){throw new Error(`Planned candidate package root must be relative: ${relative}`)}const directory3=path25.resolve(candidate,relative);if(!isWithin(candidate,directory3)||!isWithin(candidate,realpathSync5(directory3))){throw new Error(`Planned candidate package root escapes candidate: ${relative}`)}candidatePackageJson(directory3);return directory3}))].toSorted((left,right)=>left.split(path25.sep).length-right.split(path25.sep).length||left.localeCompare(right));const roots=[candidate];const owned=new Set([candidate,...candidateWorkspaces(candidate,candidatePackageJson(candidate))]);for(const directory3 of selected){if(owned.has(directory3)){continue}roots.push(directory3);owned.add(directory3);for(const workspace of candidateWorkspaces(directory3,candidatePackageJson(directory3))){owned.add(workspace)}}return roots};var candidateLintTargets=(root,fallback)=>{const packageJson=candidatePackageJson(root);const ownsOxlint=(manifest)=>[manifest.dependencies,manifest.devDependencies].some((dependencies)=>typeof dependencies==="object"&&dependencies!==null&&("oxlint"in dependencies));if(ownsOxlint(packageJson)){return[root]}const configured=candidateWorkspaces(root,packageJson).filter((directory3)=>{const manifest=candidatePackageJson(directory3);return ownsOxlint(manifest)||hasLintConfiguration(directory3)});return configured.length>0?configured:fallback?[root]:[]};var runCandidateInstall=(candidate,processCapture,bunExecutable,refreshLockfile,candidateRoot)=>{const scope3=path25.relative(candidateRoot,candidate).split(path25.sep).join("/")||".";const failureMessage=(operation2,result4)=>{const detail=result4.stderr||(result4.error instanceof Error?result4.error.message:`process exited with status ${result4.status??"unknown"}`);return`Candidate ${operation2} failed for ${scope3}: ${detail}`};const bun=bunExecutable??(path25.basename(process.execPath).startsWith("bun")?process.execPath:"bun");if(refreshLockfile){const lockfileArgs=["install","--lockfile-only","--ignore-scripts"];const lockfile=processCapture(bun,lockfileArgs,candidate);if(lockfile.error!==undefined||lockfile.status!==0){return previewFailure({command:commandText(bun,lockfileArgs),kind:"dependency",message:failureMessage("lockfile generation",lockfile)})}}const installArgs=["install","--frozen-lockfile","--ignore-scripts"];const install=processCapture(bun,installArgs,candidate);return install.error!==undefined||install.status!==0?previewFailure({command:commandText(bun,installArgs),kind:"dependency",message:failureMessage("dependency installation",install)}):null};var runCandidateEffectPatch=(candidate,candidateRoot,packageJson,processCapture)=>{const prepare=isRecord7(packageJson.scripts)?packageJson.scripts.prepare:undefined;if(typeof prepare!=="string"||!prepare.includes("effect-tsgo patch --no-typescript --oxlint")){return null}const effectTsgo=findLocalEffectTsgo(candidate,candidateRoot);if(effectTsgo===null){return previewFailure({kind:"dependency",message:`Candidate Effect patch executable is unavailable for ${path25.relative(candidateRoot,candidate)||"."}.`})}const args2=["patch","--no-typescript","--oxlint"];const patchResult=processCapture(effectTsgo,args2,candidate);return patchResult.error!==undefined||patchResult.status!==0?previewFailure({command:commandText(effectTsgo,args2),kind:"process",message:patchResult.stderr||"Candidate Effect lint patch failed."}):null};var runCandidateOxlint=(candidate,processCapture,hasInjectedCapture,sampleSize,candidateRoot)=>{const oxlint=findLocalOxlint(candidate,candidateRoot)??(hasInjectedCapture?path25.join(candidate,"node_modules",".bin","oxlint"):null);if(oxlint===null){return previewFailure({kind:"dependency",message:"Candidate Oxlint executable is unavailable after isolated dependency installation."})}const ignoreNodeModulesArgs=["--ignore-pattern","node_modules/**"];const args2=["--format","json",...ignoreNodeModulesArgs,"."];const lint=processCapture(oxlint,args2,candidate);if(lint.error!==undefined||lint.status===null){if(isOutputOverflow(lint.error)){const agentArgs=["--format","agent",...ignoreNodeModulesArgs,"."];const agent=processCapture(oxlint,agentArgs,candidate);if(agent.error!==undefined||agent.status===null){return previewFailure({command:commandText(oxlint,agentArgs),kind:"process",message:agent.error instanceof Error?agent.error.message:agent.stderr||`Candidate Oxlint exited with status ${agent.status??"unknown"}.`})}const agentFindings=parseAgentOutput(candidate,agent.stdout);if(agentFindings.invalidLine!==undefined){return previewFailure({command:commandText(oxlint,agentArgs),kind:"malformed-output",message:`Candidate Oxlint agent output contained an invalid diagnostic: ${JSON.stringify(agentFindings.invalidLine)}`})}const findings=agentFindings.findings.toSorted((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));return new LintPreviewFacts({findingCount:findings.length,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findings.length===0?"clean":"findings",truncated:findings.length>sampleSize})}return previewFailure({command:commandText(oxlint,args2),kind:"process",message:lint.error instanceof Error?lint.error.message:lint.stderr||`Candidate Oxlint exited with status ${lint.status??"unknown"}.`})}try{const output2=oxlintJsonOutput(lint.stdout);const parsed=JSON.parse(output2.json);let diagnostics;if(Array.isArray(parsed)){diagnostics=parsed}else{if(!isRecord7(parsed)){throw new TypeError("Candidate Oxlint JSON did not contain diagnostics.")}const{diagnostics:parsedDiagnostics}=parsed;if(!Array.isArray(parsedDiagnostics)){throw new TypeError("Candidate Oxlint JSON did not contain diagnostics.")}diagnostics=parsedDiagnostics}const parsedFindings=diagnostics.map((value5)=>parseFinding(candidate,value5));if(parsedFindings.some((finding)=>finding===null)){return previewFailure({command:commandText(oxlint,args2),kind:"malformed-output",message:"Candidate Oxlint JSON contained an invalid diagnostic."})}const findings=parsedFindings.filter((value5)=>value5!==null).toSorted((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));const benignStderr=hasOnlyModuleTypeWarnings(lint.stderr);const unexpectedStderr=lint.stderr.trim().length>0&&!benignStderr;const nonzeroWithoutFindings=lint.status!==0&&findings.length===0&&!benignStderr&&!output2.zeroFiles;return unexpectedStderr||nonzeroWithoutFindings?previewFailure({command:commandText(oxlint,args2),kind:/config|load/iu.test(lint.stderr)?"config-load":"process",message:lint.stderr||`Candidate Oxlint exited with status ${lint.status??"unknown"}.`}):new LintPreviewFacts({findingCount:findings.length,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findings.length===0?"clean":"findings",truncated:findings.length>sampleSize})}catch(error2){const nonBenignStderr=lint.stderr.trim().length>0&&!hasOnlyModuleTypeWarnings(lint.stderr);return previewFailure({command:commandText(oxlint,args2),kind:nonBenignStderr&&/config|load/iu.test(lint.stderr)?"config-load":"malformed-output",message:nonBenignStderr&&lint.stderr||(error2 instanceof Error?error2.message:"Candidate Oxlint returned malformed JSON.")})}};var lintPreviewForCandidate=({candidate,capture,bunExecutable,hasInjectedCapture,liveRoot,plannedPackageRoots,refreshLockfile,sampleSize})=>{if(!hasLintConfiguration(candidate)){return cleanPreview()}const installationRoots=candidateInstallationRoots(candidate,plannedPackageRoots);for(const directory3 of installationRoots){const liveDirectory=path25.join(liveRoot,path25.relative(candidate,directory3));const refresh=directory3===candidate?refreshLockfile:!existsSync9(liveDirectory)||manifestFingerprint(liveDirectory)!==manifestFingerprint(directory3)||!["bun.lock","bun.lockb"].some((lockfile)=>existsSync9(path25.join(directory3,lockfile)));const installFailure=runCandidateInstall(directory3,capture,bunExecutable,refresh,candidate);if(installFailure!==null){return installFailure}validatePreviewSymlinks(candidate)}const preparedDirectories=[...new Set(installationRoots.flatMap((root)=>[root,...candidateWorkspaces(root,candidatePackageJson(root))]))];for(const directory3 of preparedDirectories){const patchFailure=runCandidateEffectPatch(directory3,candidate,candidatePackageJson(directory3),capture);if(patchFailure!==null){return patchFailure}}const configuredWorkspaces=candidateLintTargets(candidate,installationRoots.length===1);const targets=[...new Set([...configuredWorkspaces,...installationRoots.slice(1).flatMap((root)=>candidateLintTargets(root,true))])];const findings=[];let findingCount=0;for(const directory3 of targets){const result4=runCandidateOxlint(directory3,capture,hasInjectedCapture,sampleSize,candidate);if(result4.status==="operational-failure"){return result4}findingCount+=result4.findingCount;findings.push(...result4.findings.map((finding)=>({...finding,file:finding.file===""?"":path25.relative(candidate,path25.resolve(directory3,finding.file)).split(path25.sep).join("/")})))}findings.sort((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));return new LintPreviewFacts({findingCount,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findingCount===0?"clean":"findings",truncated:findingCount>sampleSize})};var runCandidateLintPreview=async({liveRoot,stagedRoot,manifestSource="staged",capture,bunExecutable,removePaths=[],sampleSize=20,prepareCandidate,plannedPackageRoots=[]})=>{const before=fingerprintLiveState(liveRoot);const processCapture=capture??((command,args2,cwd)=>nodeProcess.capture(command,args2,{cwd}));let candidate=null;let result4=null;try{candidate=mkdtempSync3(path25.join(tmpdir6(),"punks-update-candidate-"));preparePreviewCandidate(liveRoot,stagedRoot,candidate,removePaths,manifestSource);const candidateDirectory=candidate;if(candidateDirectory===null){throw new Error("Candidate directory was not created.")}if(prepareCandidate!==undefined){await prepareCandidate(candidateDirectory)}validatePreviewSymlinks(candidateDirectory);const packageManifestChanged=manifestFingerprint(liveRoot)!==manifestFingerprint(candidateDirectory);const hasBunLockfile=["bun.lock","bun.lockb"].some((lockfile)=>existsSync9(path25.join(candidateDirectory,lockfile)));result4=lintPreviewForCandidate({bunExecutable,candidate:candidateDirectory,capture:processCapture,hasInjectedCapture:capture!==undefined,liveRoot,plannedPackageRoots,refreshLockfile:packageManifestChanged||!hasBunLockfile,sampleSize})}catch(error2){result4=previewFailure({kind:"config-load",message:error2 instanceof Error?error2.message:"Candidate lint preview failed."})}finally{if(candidate!==null){try{rmSync3(candidate,{force:true,recursive:true});if(existsSync9(candidate)){result4=previewFailure({kind:"cleanup",message:"Candidate cleanup could not be proven."})}}catch(error2){result4=previewFailure({kind:"cleanup",message:error2 instanceof Error?error2.message:"Candidate cleanup failed."})}}}if(fingerprintLiveState(liveRoot)!==before){return previewFailure({kind:"cleanup",message:"Live repository changed during candidate lint preview."})}return result4??previewFailure({kind:"process",message:"Candidate lint preview returned no result."})};import{lstatSync as lstatSync5}from"node:fs";import path26 from"node:path";var preExistingSkillHomes=[".agents/skills",".claude/skills",".codex/skills",".cursor/skills",".opencode/skills"];var preExistingSkillSnapshotDirectories=preExistingSkillHomes.map((relativeDirectory)=>path26.posix.join(".devpunks/pre-existing-skills",relativeDirectory));var snapshotPreExistingSkillHomes=async(outputDirectory,session)=>{const snapshots=[];for(const relativeDirectory of preExistingSkillHomes){const sourceDirectory=path26.join(outputDirectory,relativeDirectory);assertConfinedDirectory({directoryPath:path26.dirname(sourceDirectory),outputDirectory,...session===undefined?{}:{session}});const stat3=lstatSync5(sourceDirectory,{throwIfNoEntry:false});if(stat3===undefined||stat3.isSymbolicLink()||!stat3.isDirectory()){continue}assertConfinedDirectory({directoryPath:sourceDirectory,outputDirectory,...session===undefined?{}:{session}});const targetPath=path26.join(outputDirectory,".devpunks/pre-existing-skills",relativeDirectory);assertConfinedDirectory({directoryPath:targetPath,outputDirectory,...session===undefined?{}:{session}});snapshots.push({sourceDirectory,targetPath})}const results=await Promise.allSettled(snapshots.map(async({sourceDirectory,targetPath})=>{await snapshotConfinedDirectory({outputDirectory,...session===undefined?{}:{session},sourceDirectory,targetPath})}));const firstFailure=results.find((result4)=>result4.status==="rejected");if(firstFailure!==undefined){throw firstFailure.reason}};var fileMode=(mode)=>mode%512;var isRecord8=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var orderedPlanArtifact=({content,kind,path:artifactPath,source})=>({path:artifactPath,content,kind,source});var encodeContextPlan2=encodeSync2(ContextPlan);var decodeHandoffReceipt=decodeUnknownSync(Struct({managedFileModes:optional(Record(String4,Union2([Number6,Null2]))),managedFileTypes:optional(Record(String4,Literals(["file","symlink"]))),managedFiles:ArraySchema(ScaffoldManagedFileSummary),projectionReceiptFile:optional(String4),projectionStatus:optional(Literals(["partial","success"]))}));var agentHandoffFile=".devpunks/AGENT-HANDOFF.md";var isCurrentHandoffObligation=(obligation)=>obligation?.contentAuthority==="scaffold"&&obligation.producer==="scaffold-handoff"&&obligation.presence==="required"&&obligation.validity==="managed-bytes";var verifiedHandoffContent=(scanDirectory,manifest)=>{const handoffs=manifest.managedFiles.filter(({path:file5})=>file5===agentHandoffFile);const handoff=handoffs.length===1?handoffs[0]:undefined;const obligation=handoff?.obligation;const sourcePath=path27.join(scanDirectory,agentHandoffFile);const stat3=lstatSync6(sourcePath,{throwIfNoEntry:false});const mode=manifest.managedFileModes?.[agentHandoffFile];const source=stat3?.isFile()===true?readFileSync12(sourcePath,"utf-8"):undefined;return handoff?.kind==="handoff"&&handoff.ownership._tag==="ScaffoldManaged"&&isCurrentHandoffObligation(obligation)&&manifest.managedFileTypes?.[agentHandoffFile]!=="symlink"&&(mode===undefined||mode!==null&&stat3!==undefined&&fileMode(stat3.mode)===mode)&&source!==undefined&&hashManagedFileContent(agentHandoffFile,source)===handoff.sha256?source:undefined};var priorHandoffAuthority=(scanDirectory)=>{const empty11={content:undefined,proofs:[]};try{const manifestPath=path27.join(scanDirectory,".devpunks/scaffold-manifest.json");if(!lstatSync6(manifestPath).isFile()){return empty11}const manifest=decodeHandoffReceipt(JSON.parse(readFileSync12(manifestPath,"utf-8")));const content=verifiedHandoffContent(scanDirectory,manifest);const receiptFile=".devpunks/harness-projection-receipt.json";const receipts=manifest.managedFiles.filter(({path:file5})=>file5===receiptFile);if(manifest.projectionReceiptFile!==receiptFile||receipts.length!==1||receipts[0]?.kind!=="projection-receipt"){return{content,proofs:[]}}const receiptPath=path27.join(scanDirectory,receiptFile);if(!lstatSync6(receiptPath).isFile()){return{content,proofs:[]}}const bytes=readFileSync12(receiptPath,"utf-8");const receipt=JSON.parse(bytes);if(!isRecord8(receipt)||receipt.status!==manifest.projectionStatus||!["success","partial"].includes(String(receipt.status))||!Array.isArray(receipt.projections)||hashManagedFileContent(receiptFile,bytes)!==receipts[0]?.sha256){return{content,proofs:[]}}return{content,proofs:readScopedAuthoringProofs(receipt)}}catch{return empty11}};var toPosixPath=(value5)=>value5.split(path27.sep).join("/");var relativePosixPath=(from,to)=>{const relativePath=path27.relative(from,to);return relativePath===""?".":toPosixPath(relativePath)};var successfulProjectionReceiptSchema=Struct({projections:ArraySchema(Struct({actions:ArraySchema(Struct({id:String4,operation:String4,source:optionalKey2(String4),target:optionalKey2(String4),trace:optionalKey2(Struct({scopeId:optionalKey2(String4)}))})),adapter:Struct({id:String4}),failures:ArraySchema(Struct({action:optionalKey2(String4)}))})),status:Literals(["partial","success"])});var decodeSuccessfulProjectionReceipt=decodeUnknownSync(successfulProjectionReceiptSchema,{onExcessProperty:"preserve",propertyOrder:"original"});var readSuccessfulProjectionReceipt=(outputDirectory,receiptFile)=>{const receipt=JSON.parse(readFileSync12(path27.join(outputDirectory,receiptFile),"utf-8"));if(isRecord8(receipt)&&receipt.status==="failure"){throw new Error(`Harness projection failed; inspect ${receiptFile}`)}try{return decodeSuccessfulProjectionReceipt(receipt)}catch(error2){throw new CliValidationError({cause:error2,message:`Invalid Harness projection receipt; inspect ${receiptFile}`})}};var specPathForPromptTarget=(relativePath)=>{const promptTargetPath=toPosixPath(relativePath);if(promptTargetPath===".agents/AGENTS.md"){return".devpunks/specs/prompts/shared-agents.md"}if(promptTargetPath==="AGENTS.md"){return".devpunks/specs/prompts/root.md"}if(promptTargetPath==="docs/AGENTS.md"){return".devpunks/specs/prompts/docs.md"}return path27.posix.join(".devpunks/specs/prompts",path27.posix.dirname(promptTargetPath),"prompt.md")};var uniqueSorted2=(values)=>[...new Set(values)].toSorted();var collectOpensrcReferences=(promptSpecs)=>uniqueSorted2(promptSpecs.flatMap((spec)=>spec.opensrcReferences));var indentation=(line)=>line.length-line.trimStart().length;var nextLefthookBoundary=(lines2,start,boundaryIndent)=>{const index=lines2.findIndex((line,lineIndex)=>lineIndex>start&&line.trim().length>0&&!line.trimStart().startsWith("#")&&indentation(line)<=boundaryIndent);return index===-1?lines2.length:index};var lefthookCommandSection=(lines2)=>{const preCommitIndex=lines2.findIndex((line)=>line.trim()==="pre-commit:");const preCommitIndent=preCommitIndex===-1?0:indentation(lines2[preCommitIndex]);const preCommitEnd=preCommitIndex===-1?lines2.length:nextLefthookBoundary(lines2,preCommitIndex,preCommitIndent);const childIndents=lines2.slice(preCommitIndex+1,preCommitEnd).filter((line)=>line.trim().length>0&&!line.trimStart().startsWith("#")).map(indentation);const childIndent=childIndents.length===0?preCommitIndent+2:Math.min(...childIndents);const commandsIndex=preCommitIndex===-1?-1:lines2.findIndex((line,index)=>index>preCommitIndex&&index<preCommitEnd&&line.trim()==="commands:"&&indentation(line)===childIndent);const commandsIndent=commandsIndex===-1?preCommitIndent+2:indentation(lines2[commandsIndex]);return{commandEnd:commandsIndex===-1?0:nextLefthookBoundary(lines2,commandsIndex,commandsIndent),commandsIndent,commandsIndex,preCommitIndent,preCommitIndex}};var mergeLefthookCommitGate=(outputDirectory,policy="enabled")=>{const configPath=["lefthook.yml","lefthook.yaml"].find((file5)=>existsSync10(path27.join(outputDirectory,file5)));if(configPath===undefined){return{content:null,existingLintCommand:null,path:"lefthook.yml",unsafe:false}}const content=readFileSync12(path27.join(outputDirectory,configPath),"utf-8");const lines2=content.split(`
2473
+ `)).digest("hex");var candidateWorkspaces=(candidate,packageJson)=>{const{workspaces}=packageJson;const patterns=Array.isArray(workspaces)?workspaces:typeof workspaces==="object"&&workspaces!==null&&("packages"in workspaces)?workspaces.packages:[];if(!Array.isArray(patterns)||!patterns.every((pattern)=>typeof pattern==="string")){throw new Error("Candidate workspace patterns must be strings.")}return packageDirectories(candidate).filter((directory3)=>{const relative=path25.relative(candidate,directory3).split(path25.sep).join("/");return relative!==""&&patterns.some((pattern)=>!pattern.startsWith("!")&&path25.matchesGlob(relative,pattern))&&!patterns.some((pattern)=>pattern.startsWith("!")&&path25.matchesGlob(relative,pattern.slice(1)))})};var candidatePackageJson=(candidate)=>{const packagePath=path25.join(candidate,"package.json");if(!existsSync9(packagePath)){throw new Error("Candidate package manifest is missing.")}const packageJson=JSON.parse(readFileSync11(packagePath,"utf-8"));if(!isRecord7(packageJson)){throw new Error("Candidate package manifest must be an object.")}return packageJson};var candidateInstallationRoots=(candidate,selectedRoots)=>{const selected=[...new Set(selectedRoots.map((relative)=>{if(path25.isAbsolute(relative)){throw new Error(`Planned candidate package root must be relative: ${relative}`)}const directory3=path25.resolve(candidate,relative);if(!isWithin(candidate,directory3)||!isWithin(candidate,realpathSync5(directory3))){throw new Error(`Planned candidate package root escapes candidate: ${relative}`)}candidatePackageJson(directory3);return directory3}))].toSorted((left,right)=>left.split(path25.sep).length-right.split(path25.sep).length||left.localeCompare(right));const roots=[candidate];const owned=new Set([candidate,...candidateWorkspaces(candidate,candidatePackageJson(candidate))]);for(const directory3 of selected){if(owned.has(directory3)){continue}roots.push(directory3);owned.add(directory3);for(const workspace of candidateWorkspaces(directory3,candidatePackageJson(directory3))){owned.add(workspace)}}return roots};var candidateLintTargets=(root,fallback)=>{const packageJson=candidatePackageJson(root);const ownsOxlint=(manifest)=>[manifest.dependencies,manifest.devDependencies].some((dependencies)=>typeof dependencies==="object"&&dependencies!==null&&("oxlint"in dependencies));if(ownsOxlint(packageJson)){return[root]}const configured=candidateWorkspaces(root,packageJson).filter((directory3)=>{const manifest=candidatePackageJson(directory3);return ownsOxlint(manifest)||hasLintConfiguration(directory3)});return configured.length>0?configured:fallback?[root]:[]};var runCandidateInstall=(candidate,processCapture,bunExecutable,refreshLockfile,candidateRoot)=>{const scope3=path25.relative(candidateRoot,candidate).split(path25.sep).join("/")||".";const failureMessage=(operation2,result4)=>{const detail=result4.stderr||(result4.error instanceof Error?result4.error.message:`process exited with status ${result4.status??"unknown"}`);return`Candidate ${operation2} failed for ${scope3}: ${detail}`};const bun=bunExecutable??(path25.basename(process.execPath).startsWith("bun")?process.execPath:"bun");if(refreshLockfile){const lockfileArgs=["install","--lockfile-only","--ignore-scripts"];const lockfile=processCapture(bun,lockfileArgs,candidate);if(lockfile.error!==undefined||lockfile.status!==0){return previewFailure({command:commandText(bun,lockfileArgs),kind:"dependency",message:failureMessage("lockfile generation",lockfile)})}}const installArgs=["install","--frozen-lockfile","--ignore-scripts"];const install=processCapture(bun,installArgs,candidate);return install.error!==undefined||install.status!==0?previewFailure({command:commandText(bun,installArgs),kind:"dependency",message:failureMessage("dependency installation",install)}):null};var runCandidateEffectPatch=(candidate,candidateRoot,packageJson,processCapture)=>{const prepare=isRecord7(packageJson.scripts)?packageJson.scripts.prepare:undefined;if(typeof prepare!=="string"||!prepare.includes("effect-tsgo patch --no-typescript --oxlint")){return null}const effectTsgo=findLocalEffectTsgo(candidate,candidateRoot);if(effectTsgo===null){return previewFailure({kind:"dependency",message:`Candidate Effect patch executable is unavailable for ${path25.relative(candidateRoot,candidate)||"."}.`})}const args2=["patch","--no-typescript","--oxlint"];const patchResult=processCapture(effectTsgo,args2,candidate);return patchResult.error!==undefined||patchResult.status!==0?previewFailure({command:commandText(effectTsgo,args2),kind:"process",message:patchResult.stderr||"Candidate Effect lint patch failed."}):null};var runCandidateOxlint=(candidate,processCapture,hasInjectedCapture,sampleSize,candidateRoot)=>{const oxlint=findLocalOxlint(candidate,candidateRoot)??(hasInjectedCapture?path25.join(candidate,"node_modules",".bin","oxlint"):null);if(oxlint===null){return previewFailure({kind:"dependency",message:"Candidate Oxlint executable is unavailable after isolated dependency installation."})}const ignoreNodeModulesArgs=["--ignore-pattern","node_modules/**"];const args2=["--format","json",...ignoreNodeModulesArgs,"."];const lint=processCapture(oxlint,args2,candidate);if(lint.error!==undefined||lint.status===null){if(isOutputOverflow(lint.error)){const agentArgs=["--format","agent",...ignoreNodeModulesArgs,"."];const agent=processCapture(oxlint,agentArgs,candidate);if(agent.error!==undefined||agent.status===null){return previewFailure({command:commandText(oxlint,agentArgs),kind:"process",message:agent.error instanceof Error?agent.error.message:agent.stderr||`Candidate Oxlint exited with status ${agent.status??"unknown"}.`})}const agentFindings=parseAgentOutput(candidate,agent.stdout);if(agentFindings.invalidLine!==undefined){return previewFailure({command:commandText(oxlint,agentArgs),kind:"malformed-output",message:`Candidate Oxlint agent output contained an invalid diagnostic: ${JSON.stringify(agentFindings.invalidLine)}`})}const findings=agentFindings.findings.toSorted((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));return new LintPreviewFacts({findingCount:findings.length,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findings.length===0?"clean":"findings",truncated:findings.length>sampleSize})}return previewFailure({command:commandText(oxlint,args2),kind:"process",message:lint.error instanceof Error?lint.error.message:lint.stderr||`Candidate Oxlint exited with status ${lint.status??"unknown"}.`})}try{const output2=oxlintJsonOutput(lint.stdout);const parsed=JSON.parse(output2.json);let diagnostics;if(Array.isArray(parsed)){diagnostics=parsed}else{if(!isRecord7(parsed)){throw new TypeError("Candidate Oxlint JSON did not contain diagnostics.")}const{diagnostics:parsedDiagnostics}=parsed;if(!Array.isArray(parsedDiagnostics)){throw new TypeError("Candidate Oxlint JSON did not contain diagnostics.")}diagnostics=parsedDiagnostics}const parsedFindings=diagnostics.map((value5)=>parseFinding(candidate,value5));if(parsedFindings.some((finding)=>finding===null)){return previewFailure({command:commandText(oxlint,args2),kind:"malformed-output",message:"Candidate Oxlint JSON contained an invalid diagnostic."})}const findings=parsedFindings.filter((value5)=>value5!==null).toSorted((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));const benignStderr=hasOnlyModuleTypeWarnings(lint.stderr);const unexpectedStderr=lint.stderr.trim().length>0&&!benignStderr;const nonzeroWithoutFindings=lint.status!==0&&findings.length===0&&!benignStderr&&!output2.zeroFiles;return unexpectedStderr||nonzeroWithoutFindings?previewFailure({command:commandText(oxlint,args2),kind:/config|load/iu.test(lint.stderr)?"config-load":"process",message:lint.stderr||`Candidate Oxlint exited with status ${lint.status??"unknown"}.`}):new LintPreviewFacts({findingCount:findings.length,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findings.length===0?"clean":"findings",truncated:findings.length>sampleSize})}catch(error2){const nonBenignStderr=lint.stderr.trim().length>0&&!hasOnlyModuleTypeWarnings(lint.stderr);return previewFailure({command:commandText(oxlint,args2),kind:nonBenignStderr&&/config|load/iu.test(lint.stderr)?"config-load":"malformed-output",message:nonBenignStderr&&lint.stderr||(error2 instanceof Error?error2.message:"Candidate Oxlint returned malformed JSON.")})}};var lintPreviewForCandidate=({candidate,capture,bunExecutable,hasInjectedCapture,liveRoot,plannedPackageRoots,refreshLockfile,sampleSize})=>{if(!hasLintConfiguration(candidate)){return cleanPreview()}const installationRoots=candidateInstallationRoots(candidate,plannedPackageRoots);for(const directory3 of installationRoots){const liveDirectory=path25.join(liveRoot,path25.relative(candidate,directory3));const refresh=directory3===candidate?refreshLockfile:!existsSync9(liveDirectory)||manifestFingerprint(liveDirectory)!==manifestFingerprint(directory3)||!["bun.lock","bun.lockb"].some((lockfile)=>existsSync9(path25.join(directory3,lockfile)));const installFailure=runCandidateInstall(directory3,capture,bunExecutable,refresh,candidate);if(installFailure!==null){return installFailure}validatePreviewSymlinks(candidate)}const preparedDirectories=[...new Set(installationRoots.flatMap((root)=>[root,...candidateWorkspaces(root,candidatePackageJson(root))]))];for(const directory3 of preparedDirectories){const patchFailure=runCandidateEffectPatch(directory3,candidate,candidatePackageJson(directory3),capture);if(patchFailure!==null){return patchFailure}}const configuredWorkspaces=candidateLintTargets(candidate,installationRoots.length===1);const targets=[...new Set([...configuredWorkspaces,...installationRoots.slice(1).flatMap((root)=>candidateLintTargets(root,true))])];const findings=[];let findingCount=0;for(const directory3 of targets){const result4=runCandidateOxlint(directory3,capture,hasInjectedCapture,sampleSize,candidate);if(result4.status==="operational-failure"){return result4}findingCount+=result4.findingCount;findings.push(...result4.findings.map((finding)=>({...finding,file:finding.file===""?"":path25.relative(candidate,path25.resolve(directory3,finding.file)).split(path25.sep).join("/")})))}findings.sort((left,right)=>`${left.file}:${left.line}:${left.column}:${left.rule}:${left.message}`.localeCompare(`${right.file}:${right.line}:${right.column}:${right.rule}:${right.message}`));return new LintPreviewFacts({findingCount,findings:findings.slice(0,sampleSize),kind:"lint-preview",status:findingCount===0?"clean":"findings",truncated:findingCount>sampleSize})};var runCandidateLintPreview=async({liveRoot,stagedRoot,manifestSource="staged",capture,bunExecutable,removePaths=[],sampleSize=20,prepareCandidate,plannedPackageRoots=[]})=>{const before=fingerprintLiveState(liveRoot);const processCapture=capture??((command,args2,cwd)=>nodeProcess.capture(command,args2,{cwd}));let candidate=null;let result4=null;try{candidate=mkdtempSync3(path25.join(tmpdir6(),"punks-update-candidate-"));preparePreviewCandidate(liveRoot,stagedRoot,candidate,removePaths,manifestSource);const candidateDirectory=candidate;if(candidateDirectory===null){throw new Error("Candidate directory was not created.")}if(prepareCandidate!==undefined){await prepareCandidate(candidateDirectory)}validatePreviewSymlinks(candidateDirectory);const packageManifestChanged=manifestFingerprint(liveRoot)!==manifestFingerprint(candidateDirectory);const hasBunLockfile=["bun.lock","bun.lockb"].some((lockfile)=>existsSync9(path25.join(candidateDirectory,lockfile)));result4=lintPreviewForCandidate({bunExecutable,candidate:candidateDirectory,capture:processCapture,hasInjectedCapture:capture!==undefined,liveRoot,plannedPackageRoots,refreshLockfile:packageManifestChanged||!hasBunLockfile,sampleSize})}catch(error2){result4=previewFailure({kind:"config-load",message:error2 instanceof Error?error2.message:"Candidate lint preview failed."})}finally{if(candidate!==null){try{rmSync3(candidate,{force:true,recursive:true});if(existsSync9(candidate)){result4=previewFailure({kind:"cleanup",message:"Candidate cleanup could not be proven."})}}catch(error2){result4=previewFailure({kind:"cleanup",message:error2 instanceof Error?error2.message:"Candidate cleanup failed."})}}}if(fingerprintLiveState(liveRoot)!==before){return previewFailure({kind:"cleanup",message:"Live repository changed during candidate lint preview."})}return result4??previewFailure({kind:"process",message:"Candidate lint preview returned no result."})};import{lstatSync as lstatSync5}from"node:fs";import path26 from"node:path";var preExistingSkillHomes=[".agents/skills",".claude/skills",".codex/skills",".cursor/skills",".opencode/skills"];var preExistingSkillSnapshotDirectories=preExistingSkillHomes.map((relativeDirectory)=>path26.posix.join(".devpunks/pre-existing-skills",relativeDirectory));var snapshotPreExistingSkillHomes=async(outputDirectory,session)=>{const snapshots=[];for(const relativeDirectory of preExistingSkillHomes){const sourceDirectory=path26.join(outputDirectory,relativeDirectory);assertConfinedDirectory({directoryPath:path26.dirname(sourceDirectory),outputDirectory,...session===undefined?{}:{session}});const stat3=lstatSync5(sourceDirectory,{throwIfNoEntry:false});if(stat3===undefined||stat3.isSymbolicLink()||!stat3.isDirectory()){continue}assertConfinedDirectory({directoryPath:sourceDirectory,outputDirectory,...session===undefined?{}:{session}});const targetPath=path26.join(outputDirectory,".devpunks/pre-existing-skills",relativeDirectory);assertConfinedDirectory({directoryPath:targetPath,outputDirectory,...session===undefined?{}:{session}});snapshots.push({sourceDirectory,targetPath})}const results=await Promise.allSettled(snapshots.map(async({sourceDirectory,targetPath})=>{await snapshotConfinedDirectory({outputDirectory,...session===undefined?{}:{session},sourceDirectory,targetPath})}));const firstFailure=results.find((result4)=>result4.status==="rejected");if(firstFailure!==undefined){throw firstFailure.reason}};var fileMode=(mode)=>mode%512;var isRecord8=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var orderedPlanArtifact=({content,kind,path:artifactPath,source})=>({path:artifactPath,content,kind,source});var encodeContextPlan2=encodeSync2(ContextPlan);var decodeAuthoringReceipt=decodeUnknownSync(Struct({managedFiles:ArraySchema(ScaffoldManagedFileSummary),projectionReceiptFile:optional(String4),projectionStatus:optional(Literals(["partial","success"]))}));var agentHandoffFile=".devpunks/AGENT-HANDOFF.md";var readVerifiedAuthoringProofs=(scanDirectory)=>{try{const manifestPath=path27.join(scanDirectory,".devpunks/scaffold-manifest.json");if(!lstatSync6(manifestPath).isFile()){return[]}const manifest=decodeAuthoringReceipt(JSON.parse(readFileSync12(manifestPath,"utf-8")));const receiptFile=".devpunks/harness-projection-receipt.json";const receipts=manifest.managedFiles.filter(({path:file5})=>file5===receiptFile);if(manifest.projectionReceiptFile!==receiptFile||receipts.length!==1||receipts[0]?.kind!=="projection-receipt"){return[]}const receiptPath=path27.join(scanDirectory,receiptFile);if(!lstatSync6(receiptPath).isFile()){return[]}const bytes=readFileSync12(receiptPath,"utf-8");const receipt=JSON.parse(bytes);if(!isRecord8(receipt)||receipt.status!==manifest.projectionStatus||!["success","partial"].includes(String(receipt.status))||!Array.isArray(receipt.projections)||hashManagedFileContent(receiptFile,bytes)!==receipts[0]?.sha256){return[]}return readScopedAuthoringProofs(receipt)}catch{return[]}};var toPosixPath=(value5)=>value5.split(path27.sep).join("/");var relativePosixPath=(from,to)=>{const relativePath=path27.relative(from,to);return relativePath===""?".":toPosixPath(relativePath)};var successfulProjectionReceiptSchema=Struct({projections:ArraySchema(Struct({actions:ArraySchema(Struct({id:String4,operation:String4,source:optionalKey2(String4),target:optionalKey2(String4),trace:optionalKey2(Struct({scopeId:optionalKey2(String4)}))})),adapter:Struct({id:String4}),failures:ArraySchema(Struct({action:optionalKey2(String4)}))})),status:Literals(["partial","success"])});var decodeSuccessfulProjectionReceipt=decodeUnknownSync(successfulProjectionReceiptSchema,{onExcessProperty:"preserve",propertyOrder:"original"});var readSuccessfulProjectionReceipt=(outputDirectory,receiptFile)=>{const receipt=JSON.parse(readFileSync12(path27.join(outputDirectory,receiptFile),"utf-8"));if(isRecord8(receipt)&&receipt.status==="failure"){throw new Error(`Harness projection failed; inspect ${receiptFile}`)}try{return decodeSuccessfulProjectionReceipt(receipt)}catch(error2){throw new CliValidationError({cause:error2,message:`Invalid Harness projection receipt; inspect ${receiptFile}`})}};var specPathForPromptTarget=(relativePath)=>{const promptTargetPath=toPosixPath(relativePath);if(promptTargetPath===".agents/AGENTS.md"){return".devpunks/specs/prompts/shared-agents.md"}if(promptTargetPath==="AGENTS.md"){return".devpunks/specs/prompts/root.md"}if(promptTargetPath==="docs/AGENTS.md"){return".devpunks/specs/prompts/docs.md"}return path27.posix.join(".devpunks/specs/prompts",path27.posix.dirname(promptTargetPath),"prompt.md")};var uniqueSorted2=(values)=>[...new Set(values)].toSorted();var collectOpensrcReferences=(promptSpecs)=>uniqueSorted2(promptSpecs.flatMap((spec)=>spec.opensrcReferences));var indentation=(line)=>line.length-line.trimStart().length;var nextLefthookBoundary=(lines2,start,boundaryIndent)=>{const index=lines2.findIndex((line,lineIndex)=>lineIndex>start&&line.trim().length>0&&!line.trimStart().startsWith("#")&&indentation(line)<=boundaryIndent);return index===-1?lines2.length:index};var lefthookCommandSection=(lines2)=>{const preCommitIndex=lines2.findIndex((line)=>line.trim()==="pre-commit:");const preCommitIndent=preCommitIndex===-1?0:indentation(lines2[preCommitIndex]);const preCommitEnd=preCommitIndex===-1?lines2.length:nextLefthookBoundary(lines2,preCommitIndex,preCommitIndent);const childIndents=lines2.slice(preCommitIndex+1,preCommitEnd).filter((line)=>line.trim().length>0&&!line.trimStart().startsWith("#")).map(indentation);const childIndent=childIndents.length===0?preCommitIndent+2:Math.min(...childIndents);const commandsIndex=preCommitIndex===-1?-1:lines2.findIndex((line,index)=>index>preCommitIndex&&index<preCommitEnd&&line.trim()==="commands:"&&indentation(line)===childIndent);const commandsIndent=commandsIndex===-1?preCommitIndent+2:indentation(lines2[commandsIndex]);return{commandEnd:commandsIndex===-1?0:nextLefthookBoundary(lines2,commandsIndex,commandsIndent),commandsIndent,commandsIndex,preCommitIndent,preCommitIndex}};var mergeLefthookCommitGate=(outputDirectory,policy="enabled")=>{const configPath=["lefthook.yml","lefthook.yaml"].find((file5)=>existsSync10(path27.join(outputDirectory,file5)));if(configPath===undefined){return{content:null,existingLintCommand:null,path:"lefthook.yml",unsafe:false}}const content=readFileSync12(path27.join(outputDirectory,configPath),"utf-8");const lines2=content.split(`
2474
2474
  `);if(lines2.some((line)=>line.includes("\t"))){return{content:null,existingLintCommand:null,path:configPath,unsafe:true}}const{commandEnd,commandsIndent,commandsIndex,preCommitIndent,preCommitIndex}=lefthookCommandSection(lines2);if(preCommitIndex!==-1&&commandsIndex===-1){return{content:null,existingLintCommand:null,path:configPath,unsafe:true}}const commandEntryIndex=lines2.findIndex((line,index)=>index>commandsIndex&&index<commandEnd&&line.trim().length>0&&indentation(line)>commandsIndent);const commandEntryIndent=commandEntryIndex===-1?commandsIndent+2:indentation(lines2[commandEntryIndex]);const lintIndex=lines2.findIndex((line,index)=>index>commandsIndex&&index<commandEnd&&line.trim()==="lint:"&&indentation(line)===commandEntryIndent);if(lintIndex!==-1){const runPrefix=`${" ".repeat(commandEntryIndent+2)}run:`;const lintEnd=nextLefthookBoundary(lines2,lintIndex,commandEntryIndent);const runLine=lines2.find((line,index)=>index>lintIndex&&index<lintEnd&&line.startsWith(runPrefix));const existingLintCommand=runLine?.slice(runPrefix.length).trim()??"existing";const ownedContent=policy==="disabled"?[...lines2.slice(0,lintIndex),...lines2.slice(lintEnd)].join(`
2475
2475
  `):content;return{content:existingLintCommand===managedCommitGateCommand?ownedContent:null,existingLintCommand:existingLintCommand===managedCommitGateCommand?null:existingLintCommand,path:configPath,unsafe:false}}if(policy==="disabled"){return{content,existingLintCommand:null,path:configPath,unsafe:false}}const addition=[`${" ".repeat(commandEntryIndent)}lint:`,`${" ".repeat(commandEntryIndent+2)}run: ${managedCommitGateCommand}`,`${" ".repeat(commandEntryIndent+2)}stage_fixed: false`];const mergedLines=[...lines2];if(commandsIndex===-1){if(mergedLines.at(-1)!==""){mergedLines.push("")}mergedLines.push("pre-commit:",`${" ".repeat(preCommitIndent+2)}commands:`,...addition)}else{mergedLines.splice(commandEnd,0,...addition)}return{content:mergedLines.join(`
2476
2476
  `),existingLintCommand:null,path:configPath,unsafe:false}};var opensrcReferencesForPacks=(packs)=>uniqueSorted2(packs.flatMap((packId)=>exampleRepositoriesForPack(packId).map((repo)=>repo.repo)));var detectionHasPackage=(detection,packageName)=>detection.manifests.some((manifest)=>manifest.dependencies.includes(packageName));var projectOwnedOxlintConfigCandidates=[".oxlintrc.json",".oxlintrc.jsonc"];var existingProjectOwnedOxlintConfigFiles=(scanDirectory)=>projectOwnedOxlintConfigCandidates.filter((candidate)=>existsSync10(path27.join(scanDirectory,candidate)));var oxlintStarterConfig={extends:["ultracite/oxlint/core"],configFile:"oxlint.config.ts"};var oxlintConfigFileName="oxlint.config.ts";var ultraciteCorePreset="core";var compilerCapableOxlintVersion="1.80.0";var minimumCompilerCapableOxlintVersion="1.80.0";var defaultDevDependencyVersion="latest";var lintToolchainVersions={oxfmt:"0.66.0",oxlint:"1.80.0",ultracite:"7.10.7"};var wikiWorkspacePaths=new Set(["wiki","app/wiki","apps/wiki"]);var compatibleOxlintVersion=(candidateVersion)=>{const match8=/^(?:\^|~)?(?<version>(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/u.exec(candidateVersion);const comparison=match8?.groups?.version===undefined?undefined:compareSemanticVersions(match8.groups.version,minimumCompilerCapableOxlintVersion);return comparison!==undefined&&comparison<0?compilerCapableOxlintVersion:candidateVersion};var oxlintCatalogPath=["workspaces","catalog","oxlint"];var isOxlintCatalogStructuredEntry=(entry)=>isRecord8(entry)&&entry.file==="package.json"&&entry.kind==="field"&&Object.hasOwn(entry,"value")&&Array.isArray(entry.path)&&entry.path.length===oxlintCatalogPath.length&&entry.path.every((segment,index)=>segment===oxlintCatalogPath[index]);var hasStructuredValue=(document,entryPath)=>{let value5=document;for(const segment of entryPath){if(!isRecord8(value5)||!Object.hasOwn(value5,segment)){return false}value5=value5[segment]}return true};var patchOxlintCatalog=(packageJson,requiredVersion)=>{const workspaceValue=packageJson.workspaces;const workspaces=isRecord8(workspaceValue)?workspaceValue:undefined;const workspacePackages=Array.isArray(workspaceValue)?workspaceValue:undefined;const catalog=workspaces!==undefined&&isRecord8(workspaces.catalog)?workspaces.catalog:undefined;const current=catalog?.oxlint;if(typeof current!=="string"){return requiredVersion===undefined?packageJson:{...packageJson,workspaces:{...workspacePackages===undefined?workspaces:{packages:workspacePackages},catalog:{...catalog,oxlint:requiredVersion}}}}const compatible=requiredVersion??compatibleOxlintVersion(current);return compatible===current?packageJson:{...packageJson,workspaces:{...workspaces,catalog:{...catalog,oxlint:compatible}}}};var stripJsonComments=(content)=>{let result4="";let inString=false;let escaped=false;let inLineComment=false;let inBlockComment=false;for(let index=0;index<content.length;index+=1){const char=content[index];const next=content[index+1];if(inLineComment){if(char===`
2477
2477
  `){inLineComment=false;result4+=char}continue}if(inBlockComment){if(char==="*"&&next==="/"){inBlockComment=false;index+=1}continue}if(!inString&&char==="/"&&next==="/"){inLineComment=true;index+=1;continue}if(!inString&&char==="/"&&next==="*"){inBlockComment=true;index+=1;continue}result4+=char;if(char==="\\"&&inString){escaped=!escaped;continue}if(char==='"'&&!escaped){inString=!inString}if(char!=="\\"){escaped=false}}return result4.replaceAll(/,\s*(?<closingBracket>[}\]])/gu,"$<closingBracket>")};var readJsonRecord=(filePath)=>{const parsed=JSON.parse(stripJsonComments(readFileSync12(filePath,"utf-8")));return isRecord8(parsed)?parsed:{}};var tsIndent=(width)=>" ".repeat(width);var tsPropertyKey=(key)=>/^[A-Z_$][\w$]*$/iu.test(key)?key:JSON.stringify(key);var compareTsPropertyKeys=(left,right)=>Number(left>right)-Number(left<right);var rawTsExpressionTag=Symbol("RawTsExpression");var rawTsExpression=(source)=>({[rawTsExpressionTag]:true,source});var isRawTsExpression=(value5)=>typeof value5==="object"&&value5!==null&&value5[rawTsExpressionTag]===true;var encodePrettyTsValue=(value5,indent2=0,leadingWidth=indent2)=>{if(isRawTsExpression(value5)){return value5.source}if(Array.isArray(value5)){if(value5.length===0){return"[]"}const compact=`[${value5.map((entry)=>JSON.stringify(entry)).join(", ")}]`;if(value5.every((entry)=>entry===null||typeof entry!=="object")&&leadingWidth+compact.length<=100){return compact}return["[",...value5.map((entry)=>`${tsIndent(indent2+2)}${encodePrettyTsValue(entry,indent2+2)},`),`${tsIndent(indent2)}]`].join(`
2478
2478
  `)}if(isRecord8(value5)){const entries=Object.entries(value5).toSorted(([left],[right])=>compareTsPropertyKeys(left,right));if(entries.length===0){return"{}"}return["{",...entries.map(([key,entry])=>{const prefix=`${tsIndent(indent2+2)}${tsPropertyKey(key)}: `;return`${prefix}${encodePrettyTsValue(entry,indent2+2,prefix.length)},`}),`${tsIndent(indent2)}}`].join(`
2479
- `)}return JSON.stringify(value5)??"undefined"};var encodePrettyTsObject=(value5)=>encodePrettyTsValue(value5);var sourceOrOutputPath=({scanDirectory,outputDirectory,relativePath})=>{const outputPath=path27.join(outputDirectory,relativePath);if(existsSync10(outputPath)){return outputPath}const sourcePath=path27.join(scanDirectory,relativePath);return existsSync10(sourcePath)?sourcePath:null};var ensureStringArray=(value5)=>Array.isArray(value5)?value5.filter((entry)=>typeof entry==="string"):[];var ensureStringOrStringArray=(value5)=>{if(typeof value5==="string"){return[value5]}return ensureStringArray(value5)};var jsPluginMatches=(value5,plugin)=>{if(typeof value5==="string"){return value5===plugin.name||value5===plugin.specifier}return isRecord8(value5)&&(value5.name===plugin.name||value5.specifier===plugin.specifier||value5.name===plugin.name&&value5.specifier===plugin.specifier)};var presetImportName=(preset)=>preset.replaceAll(/[^a-zA-Z0-9]+/gu," ").split(" ").map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join("");var oxlintPresetLocalName=(preset)=>preset===ultraciteCorePreset?"core":`ultracite${presetImportName(preset)}`;var lintPresetsForAssets=(assets)=>uniqueSorted2([ultraciteCorePreset,...assets.flatMap((asset)=>asset.oxlintPresets)]);var lintConfigExtensionsForAssets=(assets,presets)=>{const reservedNames=new Set(["defineConfig","OxlintConfig","localConfig","localRules",...presets.flatMap((preset)=>{const name2=oxlintPresetLocalName(preset);return[name2,`${name2}LocalRules`,`${name2}WithLocalRules`]})]);return[...new Map(assets.flatMap((asset)=>asset.oxlintConfigExtensions??[]).map((extension)=>[`${extension.specifier}:${extension.exportName}`,extension])).values()].map((extension)=>{const specifierParts=extension.specifier.split("/");const packageParts=extension.specifier.startsWith("@")?specifierParts.slice(0,2):specifierParts.slice(0,1);const packageName=presetImportName(packageParts.join(" "));const derivedName=`${packageName.charAt(0).toLowerCase()}${packageName.slice(1)}${presetImportName(extension.exportName)}`;const baseName=/^[A-Za-z_$]/u.test(derivedName)?derivedName:`_${derivedName}`;let localName=baseName;for(let suffix=2;reservedNames.has(localName);suffix+=1){localName=`${baseName}${suffix}`}reservedNames.add(localName);return{...extension,localName}})};var lintPresetRulesForAssets=(assets)=>{const rulesByPreset={};for(const asset of assets){for(const[preset,rules]of Object.entries(asset.oxlintPresetRules??{})){rulesByPreset[preset]={...rulesByPreset[preset],...rules}}}return rulesByPreset};var unknownArray=(value5)=>Array.isArray(value5)?value5:[];var mergedAssetCategories=(assets,existing)=>{const categories={};for(const asset of assets){Object.assign(categories,asset.categories??{})}Object.assign(categories,isRecord8(existing)?existing:{});return categories};var mergedAssetVersions=(assets)=>{const versions={...lintToolchainVersions};for(const asset of assets){Object.assign(versions,asset.requiredDevDependencyVersions??{})}return versions};var mergedAssetRules=(assets)=>{const rules={};for(const asset of assets){Object.assign(rules,asset.rules)}return rules};var localLintPluginName=(plugin,workspacePath)=>{if(workspacePath==="."||!plugin.specifier.startsWith("./tools/oxlint/")){return plugin.name}const suffix=workspacePath.replaceAll(/[^A-Za-z0-9_$]/gu,"-");return`${plugin.name}-${suffix}`};var mergeLintAssetsIntoLocalOxlintConfig=(existingConfig,assets,workspacePath=".")=>{const{$schema:_schema,extends:_extends,...existingLocalConfig}=existingConfig;const nextConfig={...existingLocalConfig};const plugins=ensureStringArray(nextConfig.plugins);const ignorePatterns=uniqueSorted2([".devpunks/**",...ensureStringArray(nextConfig.ignorePatterns),...assets.flatMap((asset)=>asset.ignorePatterns??[])]);const jsPlugins=[...unknownArray(nextConfig.jsPlugins)];const settings=isRecord8(nextConfig.settings)?{...nextConfig.settings}:{};const rules=isRecord8(nextConfig.rules)?{...nextConfig.rules}:{};const projectRuleNames=new Set(Object.keys(rules));const orderedAssets=[...assets].toSorted((left,right)=>Number(left.targetPackageNames!==undefined)-Number(right.targetPackageNames!==undefined));const categories=mergedAssetCategories(orderedAssets,nextConfig.categories);const applyAssetRules=(asset)=>{for(const[key,value5]of Object.entries(asset.rules)){let ruleName=key;for(const plugin of asset.jsPlugins){if(ruleName.startsWith(`${plugin.name}/`)){ruleName=`${localLintPluginName(plugin,workspacePath)}${ruleName.slice(plugin.name.length)}`}}if(!projectRuleNames.has(ruleName)){rules[ruleName]=value5}}};for(const asset of orderedAssets){for(const plugin of asset.plugins){if(!plugins.includes(plugin)){plugins.push(plugin)}}const assetPlugins=asset.jsPlugins.map((plugin)=>({name:localLintPluginName(plugin,workspacePath),specifier:plugin.specifier}));for(const plugin of assetPlugins){if(!jsPlugins.some((entry)=>jsPluginMatches(entry,plugin))){jsPlugins.push(plugin)}}for(const[key,value5]of Object.entries(asset.settings)){if(!(key in settings)){settings[key]=value5}}applyAssetRules(asset)}return{...nextConfig,...Object.keys(categories).length>0?{categories}:{},...ignorePatterns.length>0?{ignorePatterns}:{},...plugins.length>0?{plugins:uniqueSorted2(plugins)}:{},...jsPlugins.length>0?{jsPlugins}:{},...Object.keys(settings).length>0?{settings}:{},...Object.keys(rules).length>0?{rules}:{}}};var encodeOxlintConfigTs=({existingConfig,assets,workspacePath="."})=>{const presets=lintPresetsForAssets(assets);const configExtensions=lintConfigExtensionsForAssets(assets,presets);const presetRules=lintPresetRulesForAssets(assets);const imports=presets.map((preset)=>`import ${oxlintPresetLocalName(preset)} from "ultracite/oxlint/${preset}";`);const extensionImports=configExtensions.map(({exportName,localName,specifier})=>`import { ${exportName} as ${localName} } from ${JSON.stringify(specifier)};`);const existingExtends=ensureStringOrStringArray(existingConfig.extends);const extendsEntries=[...existingExtends.map((entry)=>JSON.stringify(entry)),...presets.map((preset)=>presetRules[preset]===undefined?oxlintPresetLocalName(preset):`${oxlintPresetLocalName(preset)}WithLocalRules`),...configExtensions.map(({localName})=>localName)];const localConfig=mergeLintAssetsIntoLocalOxlintConfig(existingConfig,assets,workspacePath);const{ignorePatterns,rules,...localConfigWithoutRules}=localConfig;const localRulesSource=rules===undefined?"":`const localRules = ${encodePrettyTsObject(rules)} satisfies OxlintConfig["rules"];
2479
+ `)}return JSON.stringify(value5)??"undefined"};var encodePrettyTsObject=(value5)=>encodePrettyTsValue(value5);var sourceOrOutputPath=({scanDirectory,outputDirectory,relativePath})=>{const outputPath=path27.join(outputDirectory,relativePath);if(existsSync10(outputPath)){return outputPath}const sourcePath=path27.join(scanDirectory,relativePath);return existsSync10(sourcePath)?sourcePath:null};var ensureStringArray=(value5)=>Array.isArray(value5)?value5.filter((entry)=>typeof entry==="string"):[];var ensureStringOrStringArray=(value5)=>{if(typeof value5==="string"){return[value5]}return ensureStringArray(value5)};var jsPluginMatches=(value5,plugin)=>{if(typeof value5==="string"){return value5===plugin.name||value5===plugin.specifier}return isRecord8(value5)&&(value5.name===plugin.name||value5.specifier===plugin.specifier||value5.name===plugin.name&&value5.specifier===plugin.specifier)};var presetImportName=(preset)=>preset.replaceAll(/[^a-zA-Z0-9]+/gu," ").split(" ").map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join("");var oxlintPresetLocalName=(preset)=>preset===ultraciteCorePreset?"core":`ultracite${presetImportName(preset)}`;var lintPresetsForAssets=(assets)=>uniqueSorted2([ultraciteCorePreset,...assets.flatMap((asset)=>asset.oxlintPresets)]);var lintConfigExtensionsForAssets=(assets,presets)=>{const reservedNames=new Set(["defineConfig","OxlintConfig","localConfig","localRules",...presets.flatMap((preset)=>{const name2=oxlintPresetLocalName(preset);return[name2,`${name2}LocalRules`,`${name2}WithLocalRules`]})]);return[...new Map(assets.flatMap((asset)=>asset.oxlintConfigExtensions??[]).map((extension)=>[`${extension.specifier}:${extension.exportName}`,extension])).values()].map((extension)=>{const specifierParts=extension.specifier.split("/");const packageParts=extension.specifier.startsWith("@")?specifierParts.slice(0,2):specifierParts.slice(0,1);const packageName=presetImportName(packageParts.join(" "));const derivedName=`${packageName.charAt(0).toLowerCase()}${packageName.slice(1)}${presetImportName(extension.exportName)}`;const baseName=/^[A-Za-z_$]/u.test(derivedName)?derivedName:`_${derivedName}`;let localName=baseName;for(let suffix=2;reservedNames.has(localName);suffix+=1){localName=`${baseName}${suffix}`}reservedNames.add(localName);return{...extension,localName}})};var lintPresetRulesForAssets=(assets)=>{const rulesByPreset={};for(const asset of assets){for(const[preset,rules]of Object.entries(asset.oxlintPresetRules??{})){rulesByPreset[preset]={...rulesByPreset[preset],...rules}}}return rulesByPreset};var unknownArray=(value5)=>Array.isArray(value5)?value5:[];var mergedAssetCategories=(assets,existing)=>{const categories={};for(const asset of assets){Object.assign(categories,asset.categories??{})}Object.assign(categories,isRecord8(existing)?existing:{});return categories};var mergedAssetVersions=(assets)=>{const versions={...lintToolchainVersions};for(const asset of assets){Object.assign(versions,asset.requiredDevDependencyVersions??{})}return versions};var mergedAssetRules=(assets)=>{const rules={};for(const asset of assets){Object.assign(rules,asset.rules)}return rules};var localLintPluginName=(plugin,workspacePath)=>{if(workspacePath==="."||!plugin.specifier.startsWith("./tools/oxlint/")){return plugin.name}const suffix=workspacePath.replaceAll(/[^A-Za-z0-9_$]/gu,"-");return`${plugin.name}-${suffix}`};var mergeLintAssetsIntoLocalOxlintConfig=(existingConfig,assets,workspacePath=".")=>{const{$schema:_schema,extends:_extends,...existingLocalConfig}=existingConfig;const nextConfig={...existingLocalConfig};const plugins=ensureStringArray(nextConfig.plugins);const ignorePatterns=uniqueSorted2([".devpunks/**",...ensureStringArray(nextConfig.ignorePatterns),...assets.flatMap((asset)=>asset.ignorePatterns??[])]);const jsPlugins=[...unknownArray(nextConfig.jsPlugins)];const settings=isRecord8(nextConfig.settings)?{...nextConfig.settings}:{};const rules=isRecord8(nextConfig.rules)?{...nextConfig.rules}:{};const projectRuleNames=new Set(Object.keys(rules));const orderedAssets=[...assets].toSorted((left,right)=>Number(left.targetPackageNames!==undefined)-Number(right.targetPackageNames!==undefined));const categories=mergedAssetCategories(orderedAssets,nextConfig.categories);const rulePlugins=orderedAssets.flatMap((asset)=>asset.jsPlugins);const applyAssetRules=(asset)=>{for(const[key,value5]of Object.entries(asset.rules)){let ruleName=key;for(const plugin of rulePlugins){if(ruleName.startsWith(`${plugin.name}/`)){ruleName=`${localLintPluginName(plugin,workspacePath)}${ruleName.slice(plugin.name.length)}`}}if(!projectRuleNames.has(ruleName)){rules[ruleName]=value5}}};for(const asset of orderedAssets){for(const plugin of asset.plugins){if(!plugins.includes(plugin)){plugins.push(plugin)}}const assetPlugins=asset.jsPlugins.map((plugin)=>({name:localLintPluginName(plugin,workspacePath),specifier:plugin.specifier}));for(const plugin of assetPlugins){if(!jsPlugins.some((entry)=>jsPluginMatches(entry,plugin))){jsPlugins.push(plugin)}}for(const[key,value5]of Object.entries(asset.settings)){if(!(key in settings)){settings[key]=value5}}applyAssetRules(asset)}return{...nextConfig,...Object.keys(categories).length>0?{categories}:{},...ignorePatterns.length>0?{ignorePatterns}:{},...plugins.length>0?{plugins:uniqueSorted2(plugins)}:{},...jsPlugins.length>0?{jsPlugins}:{},...Object.keys(settings).length>0?{settings}:{},...Object.keys(rules).length>0?{rules}:{}}};var encodeOxlintConfigTs=({existingConfig,assets,workspacePath="."})=>{const presets=lintPresetsForAssets(assets);const configExtensions=lintConfigExtensionsForAssets(assets,presets);const presetRules=lintPresetRulesForAssets(assets);const imports=presets.map((preset)=>`import ${oxlintPresetLocalName(preset)} from "ultracite/oxlint/${preset}";`);const extensionImports=configExtensions.map(({exportName,localName,specifier})=>`import { ${exportName} as ${localName} } from ${JSON.stringify(specifier)};`);const existingExtends=ensureStringOrStringArray(existingConfig.extends);const extendsEntries=[...existingExtends.map((entry)=>JSON.stringify(entry)),...presets.map((preset)=>presetRules[preset]===undefined?oxlintPresetLocalName(preset):`${oxlintPresetLocalName(preset)}WithLocalRules`),...configExtensions.map(({localName})=>localName)];const localConfig=mergeLintAssetsIntoLocalOxlintConfig(existingConfig,assets,workspacePath);const{ignorePatterns,rules,...localConfigWithoutRules}=localConfig;const localRulesSource=rules===undefined?"":`const localRules = ${encodePrettyTsObject(rules)} satisfies OxlintConfig["rules"];
2480
2480
 
2481
2481
  `;const localConfigSource=`${encodePrettyTsObject({...localConfigWithoutRules,...rules===undefined?{}:{rules:rawTsExpression("localRules")}})};`;const presetRulesSource=presets.flatMap((preset)=>{const rulesForPreset=presetRules[preset];if(rulesForPreset===undefined){return[]}const presetName=oxlintPresetLocalName(preset);const rulesName=`${presetName}LocalRules`;return[`const ${rulesName} = ${encodePrettyTsObject(rulesForPreset)} satisfies OxlintConfig["rules"];`,"",`const ${presetName}WithLocalRules = {`,` ...${presetName},`,` overrides: (${presetName}.overrides ?? []).map((override) => ({`," ...override,"," rules: {"," ...override.rules,",` ...${rulesName},`," },"," })),","};",""]});const oxlintImports=[...rules===undefined&&presetRulesSource.length===0?[]:['import type { OxlintConfig } from "oxlint";'],'import { defineConfig } from "oxlint";'];let ignorePatternsSource=" ignorePatterns: core.ignorePatterns,";if(ignorePatterns!==undefined){const patterns=ensureStringArray(ignorePatterns);ignorePatternsSource=patterns.length===1?` ignorePatterns: [...(core.ignorePatterns ?? []), ${JSON.stringify(patterns[0])}],`:[" ignorePatterns: ["," ...(core.ignorePatterns ?? []),",...patterns.map((pattern)=>` ${JSON.stringify(pattern)},`)," ],"].join(`
2482
2482
  `)}return[...oxlintImports,...imports,...extensionImports,"",...presetRulesSource,`${localRulesSource}const localConfig = ${localConfigSource}`,"","export default defineConfig({",` extends: [${extendsEntries.join(", ")}],`,ignorePatternsSource," ...localConfig,","});",""].join(`
2483
- `)};var rootPackageJsonRecord=({scanDirectory,outputDirectory})=>{const rootPackageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:"package.json",scanDirectory});return rootPackageJsonPath===null?null:readJsonRecord(rootPackageJsonPath)};var oxlintDependencyVersionFor=({rootPackageJson,isRootWorkspace})=>{const rootDevDependencies=rootPackageJson?.devDependencies;if(isRecord8(rootDevDependencies)&&typeof rootDevDependencies.oxlint==="string"){return compatibleOxlintVersion(rootDevDependencies.oxlint)}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;return!isRootWorkspace&&isRecord8(catalog)&&typeof catalog.oxlint==="string"?"catalog:":compilerCapableOxlintVersion};var catalogVersionFor=(rootPackageJson,packageName)=>{const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;const catalogVersion=isRecord8(catalog)?catalog[packageName]:undefined;return typeof catalogVersion==="string"?catalogVersion:null};var dependencyVersionFor=({rootPackageJson,packageName,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const requiredVersion=requiredVersions[packageName];if(requiredVersion!==undefined){if(!isRootWorkspace&&catalogVersionFor(rootPackageJson,packageName)===requiredVersion){return"catalog:"}return requiredVersion}if(packageName==="oxlint"&&requiresCompilerOxlint){return oxlintDependencyVersionFor({isRootWorkspace,rootPackageJson})}const dependencySections=[rootPackageJson?.devDependencies,rootPackageJson?.dependencies,rootPackageJson?.peerDependencies,rootPackageJson?.optionalDependencies];for(const section2 of dependencySections){if(isRecord8(section2)&&typeof section2[packageName]==="string"){return section2[packageName]}}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;if(!isRootWorkspace&&isRecord8(catalog)&&typeof catalog[packageName]==="string"){return"catalog:"}return defaultDevDependencyVersion};var packageDependencySections=["dependencies","devDependencies","peerDependencies","optionalDependencies"];var packageDependencyEntries=(packageJson,packageName)=>{const entries=[];for(const section2 of packageDependencySections){const dependencies=packageJson[section2];const declaredVersion=isRecord8(dependencies)?dependencies[packageName]:undefined;if(typeof declaredVersion==="string"){entries.push({section:section2,version:declaredVersion})}}return entries};var dependencyMatchesRequiredVersion=({packageName,requiredVersion,rootPackageJson,declaredVersion})=>declaredVersion===requiredVersion||declaredVersion==="catalog:"&&catalogVersionFor(rootPackageJson,packageName)===requiredVersion;var isMissingRequiredOxlintCatalogReference=({declaredVersion,isRootWorkspace,packageName,rootPackageJson})=>!isRootWorkspace&&packageName==="oxlint"&&declaredVersion==="catalog:"&&catalogVersionFor(rootPackageJson,packageName)===null;var dependencyCanUseRequiredVersion=({allowOxlintCatalogRepair=false,declaredVersion,isRootWorkspace,packageName,requiredVersion,rootPackageJson})=>allowOxlintCatalogRepair&&packageName==="oxlint"&&declaredVersion==="catalog:"||dependencyMatchesRequiredVersion({declaredVersion,packageName,requiredVersion,rootPackageJson})||isMissingRequiredOxlintCatalogReference({declaredVersion,isRootWorkspace,packageName,rootPackageJson});var isMigratableRequiredDevDependency=(allowMigration,section2)=>allowMigration&&section2==="devDependencies";var plannedDevDependencyVersionFor=({packageJson,packageName,rootPackageJson,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const{devDependencies}=packageJson;const existingVersion=isRecord8(devDependencies)?devDependencies[packageName]:undefined;const requiredVersion=requiredVersions[packageName];if(typeof existingVersion==="string"&&(requiredVersion===undefined||packageName==="oxlint"&&existingVersion==="catalog:"||dependencyMatchesRequiredVersion({declaredVersion:existingVersion,packageName,requiredVersion,rootPackageJson}))){return existingVersion}return dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson})};var preserveCompilerOxlintCompatibility=({devDependencies,packageJson,packageName,requiresCompilerOxlint})=>{if(packageName==="oxlint"&&requiresCompilerOxlint&&typeof devDependencies.oxlint==="string"){devDependencies.oxlint=compatibleOxlintVersion(devDependencies.oxlint)}else if(packageName==="oxlint"&&requiresCompilerOxlint){const incompatibleSection=["dependencies","peerDependencies","optionalDependencies"].find((sectionName)=>{const section2=packageJson[sectionName];const current=isRecord8(section2)?section2.oxlint:undefined;return typeof current==="string"&&compatibleOxlintVersion(current)!==current});if(incompatibleSection!==undefined){throw new CliValidationError({message:`React Compiler linting found incompatible Oxlint in ${incompatibleSection}; move Oxlint to devDependencies at ${compilerCapableOxlintVersion} or newer.`})}}};var patchPackageJsonDependencies=({allowOxlintCatalogRepair=false,allowRequiredDevDependencyMigration=false,packageJson,packageNames,rootPackageJson,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const nextPackageJson={...packageJson};const devDependencies=isRecord8(nextPackageJson.devDependencies)?{...nextPackageJson.devDependencies}:{};for(const packageName of packageNames){const existingDependencies=packageDependencyEntries(nextPackageJson,packageName);const requiredVersion=requiredVersions[packageName];if(requiredVersion!==undefined&&existingDependencies.length>0){for(const existingDependency2 of existingDependencies){if(isMigratableRequiredDevDependency(allowRequiredDevDependencyMigration,existingDependency2.section)){continue}if(!dependencyCanUseRequiredVersion({allowOxlintCatalogRepair,declaredVersion:existingDependency2.version,isRootWorkspace,packageName,requiredVersion,rootPackageJson})){throw new CliValidationError({message:`Lint asset requires ${packageName}@${requiredVersion}, but ${existingDependency2.section} declares ${existingDependency2.version}.`})}}const existingDevDependency=existingDependencies.find(({section:section2})=>section2==="devDependencies");for(const existingDependency2 of existingDependencies){if(existingDependency2.section!=="dependencies"||allowOxlintCatalogRepair&&existingDependency2.version==="catalog:"){continue}const section2=nextPackageJson[existingDependency2.section];if(isRecord8(section2)){const nextSection={...section2};Reflect.deleteProperty(nextSection,packageName);nextPackageJson[existingDependency2.section]=nextSection}}devDependencies[packageName]=existingDevDependency===undefined?dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson}):plannedDevDependencyVersionFor({isRootWorkspace,packageJson:nextPackageJson,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson});continue}const[existingDependency]=existingDependencies;if(existingDependency!==undefined){preserveCompilerOxlintCompatibility({devDependencies,packageJson,packageName,requiresCompilerOxlint});continue}devDependencies[packageName]=dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson})}nextPackageJson.devDependencies=Object.fromEntries(Object.entries(devDependencies).toSorted(([left],[right])=>left.localeCompare(right)));return nextPackageJson};var validatePlannedPackageJsonDependencies=(input2)=>{for(const[packageName,requiredVersion]of Object.entries(input2.requiredVersions)){const existingDependencies=packageDependencyEntries(input2.packageJson,packageName);for(const existingDependency of existingDependencies){if(existingDependency.section==="devDependencies"){continue}if(!dependencyCanUseRequiredVersion({...input2.allowOxlintCatalogRepair===undefined?{}:{allowOxlintCatalogRepair:input2.allowOxlintCatalogRepair},declaredVersion:existingDependency.version,isRootWorkspace:input2.isRootWorkspace,packageName,requiredVersion,rootPackageJson:input2.rootPackageJson})){throw new CliValidationError({message:`Lint asset requires ${packageName}@${requiredVersion}, but ${existingDependency.section} declares ${existingDependency.version}.`})}}const ordinaryDependency=existingDependencies.find(({section:section2})=>section2==="dependencies");if(ordinaryDependency!==undefined&&!(input2.allowOxlintCatalogRepair===true&&packageName==="oxlint"&&ordinaryDependency.version==="catalog:")){throw new CliValidationError({message:`Move ${packageName}@${requiredVersion} from dependencies to devDependencies before update.`})}}};var hasDirectNonFallthroughCommand=(script,segments)=>segments.some(({end,start})=>{const segment=script.slice(start,end).trimStart();return/^(?:@?exit)(?:\s|$)/iu.test(segment)||/^exec(?:\s|$)/u.test(segment)});var isAmbiguousShellSyntax=(script,index)=>{const character=script[index]??"";return/[|;<>\r\n(){}]/u.test(character)||script.startsWith("$(",index)||character==="#"&&(index===0||/\s/u.test(script[index-1]??""))};var analyzeShellChain=(script)=>{const backgroundSeparators=[];const separators=[];const segments=[];let escaped=false;let quote=null;let safe=true;let segmentStart=0;for(let index=0;index<script.length;index+=1){const character=script[index]??"";if(escaped){escaped=false;continue}if(character==="\\"&&quote!=="'"){escaped=true;continue}if(quote!==null){if(character===quote){quote=null}continue}if(character==="'"||character==='"'||character==="`"){quote=character;safe&&=character!=="`";continue}if(character==="&"){const isAnd=script[index+1]==="&";segments.push({end:index,start:segmentStart});if(isAnd){separators.push({end:index+2,start:index});index+=1}else{backgroundSeparators.push(index);safe=false}segmentStart=index+1;continue}if(isAmbiguousShellSyntax(script,index)){safe=false}}segments.push({end:script.length,start:segmentStart});const complete=[quote===null,!escaped,backgroundSeparators.length===0,segments.every(({end,start})=>script.slice(start,end).trim().length>0),!hasDirectNonFallthroughCommand(script,segments)].every(Boolean);safe&&=complete;return{backgroundSeparators,safe,segments,separators}};var commandSegmentIndex=(script,command,chain)=>chain.safe?chain.segments.findIndex(({end,start})=>script.slice(start,end).trim()===command):-1;var hasShellAndCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);return commandSegmentIndex(script,command,chain)!==-1};var hasBackgroundedShellCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);return chain.backgroundSeparators.length>0&&chain.segments.some(({end,start})=>script.slice(start,end).trim()===command)};var removeShellAndCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);const index=commandSegmentIndex(script,command,chain);if(index===-1){return script}if(chain.segments.length===1){return""}if(index===0){return script.slice(chain.separators[0]?.end).trimStart()}if(index===chain.segments.length-1){return script.slice(0,chain.separators[index-1]?.start).trimEnd()}const prefix=script.slice(0,chain.separators[index-1]?.start).trimEnd();const suffix=script.slice(chain.separators[index]?.end).trimStart();return`${prefix} && ${suffix}`};var appendShellAndCommandSegment=(script,command)=>{if(script.trim().length===0){return command}const chain=analyzeShellChain(script);if(!chain.safe){throw new CliValidationError({message:"Lint setup cannot safely compose package.json scripts.prepare."})}if(commandSegmentIndex(script,command,chain)!==-1){return script}const existing=script.trimEnd();const trailingWhitespace=script.slice(existing.length);return`${existing} && ${command}${trailingWhitespace}`};var patchPackageJsonPrepare=(packageJson,commands)=>{if(commands.length===0){return packageJson}const scripts=isRecord8(packageJson.scripts)?{...packageJson.scripts}:{};const existingPrepare=scripts.prepare;if(existingPrepare!==undefined&&typeof existingPrepare!=="string"){throw new CliValidationError({message:"Lint setup requires package.json scripts.prepare to be a string."})}let prepare=typeof existingPrepare==="string"?existingPrepare:"";for(const command of commands){prepare=appendShellAndCommandSegment(prepare,command)}scripts.prepare=prepare;return{...packageJson,scripts}};var lintTargetManifests=(detection,contextPlan)=>{if(!detection.monorepo||contextPlan.scopes.some((scope3)=>scope3.id==="root"&&scope3.contributions.some(isCommitGateContribution))){return detection.manifests}return detection.manifests.filter((manifest)=>path27.posix.dirname(toPosixPath(manifest.relativePath))!==".")};var existingJsonOxlintConfigPath=({scanDirectory,outputDirectory,workspacePath})=>{const candidates=[".oxlintrc.json",".oxlintrc.jsonc"].map((fileName)=>workspacePath==="."?fileName:path27.posix.join(workspacePath,fileName));for(const candidate of candidates){const configPath=sourceOrOutputPath({outputDirectory,relativePath:candidate,scanDirectory});if(configPath!==null){return configPath}}return null};var hasRootDocsContent=(scanDirectory)=>{const docsDirectory=path27.join(scanDirectory,"docs");if(!existsSync10(docsDirectory)){return false}return readdirSync4(docsDirectory).some((entry)=>entry!=="AGENTS.md")};var ignoredPromptTargetDirectories=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","build","coverage","dist","node_modules","opensrc","skills","tmp","worktrees"]);var discoverAuthoredAgentPromptTargets=(scanDirectory)=>{const targets=[];const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){if(entry.isDirectory()){if(!ignoredPromptTargetDirectories.has(entry.name)){visit2(path27.join(directory3,entry.name))}continue}if(entry.isFile()&&entry.name==="AGENTS.md"){targets.push(relativePosixPath(scanDirectory,path27.join(directory3,entry.name)))}}};if(existsSync10(scanDirectory)){visit2(scanDirectory)}return targets.toSorted()};var hasJavaScriptWorkspaceDependency=(manifest)=>manifest.dependencies.some((dependency)=>dependency==="next"||dependency==="react"||dependency==="react-dom"||dependency==="typescript"||dependency==="vite"||dependency.startsWith("@effect/")||dependency.startsWith("@tanstack/")||dependency.startsWith("@trpc/"));var isPythonUvWorkspace=({scanDirectory,outputDirectory,workspacePath,manifest})=>{const prefix=workspacePath==="."?"":`${workspacePath}/`;const hasPythonProject=sourceOrOutputPath({outputDirectory,relativePath:`${prefix}pyproject.toml`,scanDirectory})!==null||sourceOrOutputPath({outputDirectory,relativePath:`${prefix}uv.lock`,scanDirectory})!==null;return hasPythonProject&&!hasJavaScriptWorkspaceDependency(manifest)};var scopeIdForWorkspacePath=(workspacePath)=>{if(workspacePath===".agents"){return"shared"}return workspacePath==="."?"root":workspacePath};var scopeForWorkspacePath=(contextPlan,relativeWorkspacePath)=>{const scope3=contextPlan.scopes.find(({id})=>id===scopeIdForWorkspacePath(relativeWorkspacePath));if(scope3===undefined){throw new Error(`Missing compiled context scope: ${relativeWorkspacePath}`)}return scope3};var packsForWorkspace=(contextPlan,relativeWorkspacePath)=>scopeForWorkspacePath(contextPlan,relativeWorkspacePath).packs.map(({id})=>id);var hasManagedOxlintCatalogReceipt=({priorManagedDependencies=[],outputDirectory,priorManagedStructuredEntries=[],scanDirectory})=>{if(priorManagedDependencies.some(({name:name2,version:dependencyVersion})=>(name2==="oxlint-tsgolint"||name2==="@effect/tsgo")&&dependencyVersion==="catalog:")){return true}if(priorManagedStructuredEntries.some(isOxlintCatalogStructuredEntry)){return true}const manifestPath=sourceOrOutputPath({outputDirectory,relativePath:".devpunks/scaffold-manifest.json",scanDirectory});if(manifestPath===null){return false}const{managedStructuredEntries}=readJsonRecord(manifestPath);return Array.isArray(managedStructuredEntries)&&managedStructuredEntries.some(isOxlintCatalogStructuredEntry)};var planCompatibleOxlintCatalog=({priorManagedDependencies,priorManagedStructuredEntries,requireReceiptOwnership,selections,rootPackageJson,plannedStructuredEntries,scanDirectory,outputDirectory})=>{const catalogConsumers=selections.filter(({packageJson})=>packageDependencySections.some((section2)=>{const dependencies=packageJson[section2];return isRecord8(dependencies)&&dependencies.oxlint==="catalog:"}));const catalogSelections=catalogConsumers.filter(({requiredOxlintVersion,requiresCompilerOxlint})=>requiresCompilerOxlint||requiredOxlintVersion!==undefined);if(catalogConsumers.length===0||rootPackageJson===null){return}if(sourceOrOutputPath({outputDirectory,relativePath:"pnpm-workspace.yaml",scanDirectory})!==null){throw new CliValidationError({message:"Lint setup cannot manage catalog: dependencies through package.json when pnpm-workspace.yaml owns the workspace catalog."})}const requiredVersion=catalogSelections.find((selection)=>selection.requiredOxlintVersion!==undefined)?.requiredOxlintVersion;const patched=catalogSelections.length===0?rootPackageJson:patchOxlintCatalog(rootPackageJson,requiredVersion);const patchedOxlint=isRecord8(patched.workspaces)&&isRecord8(patched.workspaces.catalog)?patched.workspaces.catalog.oxlint:undefined;const currentOxlint=catalogVersionFor(rootPackageJson,"oxlint");if(currentOxlint!==null&&typeof patchedOxlint==="string"&&patchedOxlint!==currentOxlint&&requireReceiptOwnership&&!hasManagedOxlintCatalogReceipt({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},scanDirectory})){throw new CliValidationError({message:`Lint setup found an ownership conflict: project-owned Oxlint catalog value ${currentOxlint} is incompatible with required ${patchedOxlint}; Harness will not replace it without prior receipt ownership.`})}if(typeof patchedOxlint==="string"){plannedStructuredEntries.push({file:"package.json",kind:"field",path:["workspaces","catalog","oxlint"],source:"lint",value:patchedOxlint})}};var existingLintConfigForWorkspace=({planOnly,outputDirectory,scanDirectory,workspacePath})=>{const existingConfigPath=planOnly?null:existingJsonOxlintConfigPath({outputDirectory,scanDirectory,workspacePath});const existingConfig=planOnly||existingConfigPath===null?{}:readJsonRecord(existingConfigPath);return existingConfig};var skipLintWorkspace=({planOnly,detection,manifest,outputDirectory,scanDirectory,workspacePath})=>planOnly?detection.detectedLanguages.includes("python")&&!hasJavaScriptWorkspaceDependency(manifest):isPythonUvWorkspace({manifest,outputDirectory,scanDirectory,workspacePath});var writeAppliedLintConfigs=({plannedPackageDocuments={},priorManagedDependencies,priorManagedStructuredEntries,allowRequiredDevDependencyMigration,scanDirectory,outputDirectory,detection,contextPlan,baseline,planArtifact,generatedFiles,plannedDependencies,plannedStructuredEntries,planOnly})=>{const rootPackageJson=rootPackageJsonRecord({outputDirectory,scanDirectory});const allowOxlintCatalogRepair=!allowRequiredDevDependencyMigration||hasManagedOxlintCatalogReceipt({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},scanDirectory});const applied=[];const selections=[];const rootPrepareAssets=new Map;let plannedRootPackageJson=null;const planManifest=(manifest)=>{const manifestRelativePath=toPosixPath(manifest.relativePath);const normalizedWorkspacePath=path27.posix.dirname(manifestRelativePath);if(skipLintWorkspace({detection,manifest,outputDirectory,planOnly,scanDirectory,workspacePath:normalizedWorkspacePath})){return}const workspacePacks=packsForWorkspace(contextPlan,normalizedWorkspacePath);const selectedAssets=resolveLintAssetsForPacks(workspacePacks,baseline,{packageName:manifest.packageName});const isWikiWorkspace=wikiWorkspacePaths.has(normalizedWorkspacePath);const assets=isWikiWorkspace?selectedAssets.filter(({id})=>id==="typescript-anti-slop"||id==="punks-anti-slop-transition"):selectedAssets;if(assets.length===0){return}const requiresCompilerOxlint=assets.some(({id})=>id==="react-core");const configFile=normalizedWorkspacePath==="."?oxlintConfigFileName:path27.posix.join(normalizedWorkspacePath,oxlintConfigFileName);const existingConfig=existingLintConfigForWorkspace({outputDirectory,planOnly,scanDirectory,workspacePath:normalizedWorkspacePath});const workspacePlugins=assets.flatMap((asset)=>asset.jsPlugins);generatedFiles.push(planArtifact({content:isWikiWorkspace?makeWikiOxlintConfig({jsPlugins:workspacePlugins.map((plugin)=>({name:localLintPluginName(plugin,normalizedWorkspacePath),specifier:plugin.specifier})),rules:Object.fromEntries(Object.entries(mergedAssetRules(assets)).map(([name2,severity])=>{const plugin=workspacePlugins.find((entry)=>name2.startsWith(`${entry.name}/`));return[plugin===undefined?name2:`${localLintPluginName(plugin,normalizedWorkspacePath)}${name2.slice(plugin.name.length)}`,severity]}))}):encodeOxlintConfigTs({assets,existingConfig,workspacePath:normalizedWorkspacePath}),kind:"harness",path:configFile,source:"lint"}));for(const sourceFile of assets.flatMap((asset)=>asset.sourceFiles??[])){generatedFiles.push(planArtifact({content:readBaselineDataFile(baseline.dataRoot,...sourceFile.sourcePath.split("/")),kind:"harness",path:normalizedWorkspacePath==="."?sourceFile.targetPath:path27.posix.join(normalizedWorkspacePath,sourceFile.targetPath),source:"lint"}))}const packageJsonFile=manifestRelativePath;const requiredDevDependencies=uniqueSorted2([...Object.keys(lintToolchainVersions),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);const requiredDevDependencyVersions=mergedAssetVersions(assets);const prepareCommands=detection.monorepo?[]:uniqueSorted2(assets.flatMap((asset)=>asset.prepareCommands??[]));if(detection.monorepo){for(const asset of assets.filter((candidate)=>(candidate.prepareCommands?.length??0)>0)){rootPrepareAssets.set(asset.id,asset)}}const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:packageJsonFile,scanDirectory});const packageJson=plannedPackageDocuments[packageJsonFile]??(packageJsonPath===null?{}:readJsonRecord(packageJsonPath));const scripts=isRecord8(packageJson.scripts)?packageJson.scripts:{};const quality=resolveQualityCommands(scripts);const resolvedScripts={...scripts,...quality.defaults};for(const name2 of["lint","format:check","format-check","check:format"]){const value5=resolvedScripts[name2];if(typeof value5!=="string"){continue}plannedStructuredEntries.push({file:packageJsonFile,kind:"field",path:["scripts",name2],source:"lint",value:value5})}const packageJsonWithQuality={...packageJson,scripts:resolvedScripts};selections.push({packageJson,requiredOxlintVersion:requiredDevDependencyVersions.oxlint,requiresCompilerOxlint});if(planOnly){validatePlannedPackageJsonDependencies({allowOxlintCatalogRepair,isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson});patchPackageJsonPrepare(packageJson,prepareCommands)}for(const command of prepareCommands){plannedStructuredEntries.push({file:packageJsonFile,kind:"required-shell-segment",path:["scripts","prepare"],source:"lint",value:command})}if(!planOnly){const plannedPackageJson=patchPackageJsonPrepare(patchPackageJsonDependencies({allowOxlintCatalogRepair,allowRequiredDevDependencyMigration,isRootWorkspace:normalizedWorkspacePath===".",packageJson:packageJsonWithQuality,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson}),prepareCommands);if(normalizedWorkspacePath==="."){plannedRootPackageJson=plannedPackageJson}else{planArtifact({content:encodePrettyJson2(plannedPackageJson),kind:"harness",path:packageJsonFile,source:"lint"})}}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:plannedDevDependencyVersionFor({isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageName:name2,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson}),workspace:normalizedWorkspacePath})));applied.push({workspace:normalizedWorkspacePath,configFile,packageJsonFile,assets:assets.map((asset)=>asset.id),requiredDevDependencies})};for(const manifest of lintTargetManifests(detection,contextPlan)){planManifest(manifest)}if(rootPackageJson!==null&&rootPrepareAssets.size>0){const assets=[...rootPrepareAssets.values()];const prepareCommands=uniqueSorted2(assets.flatMap((asset)=>asset.prepareCommands??[]));const requiredDevDependencies=uniqueSorted2([...Object.keys(lintToolchainVersions),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);const requiredDevDependencyVersions=mergedAssetVersions(assets);if(planOnly){validatePlannedPackageJsonDependencies({allowOxlintCatalogRepair,isRootWorkspace:true,packageJson:rootPackageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson});patchPackageJsonPrepare(rootPackageJson,prepareCommands)}for(const command of prepareCommands){plannedStructuredEntries.push({file:"package.json",kind:"required-shell-segment",path:["scripts","prepare"],source:"lint",value:command})}if(!planOnly){plannedRootPackageJson=patchPackageJsonPrepare(patchPackageJsonDependencies({allowOxlintCatalogRepair,allowRequiredDevDependencyMigration,isRootWorkspace:true,packageJson:plannedRootPackageJson??rootPackageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson}),prepareCommands)}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:plannedDevDependencyVersionFor({isRootWorkspace:true,packageJson:rootPackageJson,packageName:name2,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson}),workspace:"."})).filter((proposed)=>!plannedDependencies.some((existing)=>existing.workspace===proposed.workspace&&existing.section===proposed.section&&existing.name===proposed.name&&existing.version===proposed.version&&existing.source===proposed.source&&existing.revision===undefined)))}planCompatibleOxlintCatalog({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},plannedStructuredEntries,requireReceiptOwnership:allowRequiredDevDependencyMigration,rootPackageJson,scanDirectory,selections});const plannedOxlintCatalogEntry=plannedStructuredEntries.find(isOxlintCatalogStructuredEntry);if(plannedRootPackageJson!==null&&typeof plannedOxlintCatalogEntry?.value==="string"){plannedRootPackageJson=patchOxlintCatalog(plannedRootPackageJson,plannedOxlintCatalogEntry.value)}if(plannedRootPackageJson!==null){planArtifact({content:encodePrettyJson2(plannedRootPackageJson),kind:"harness",path:"package.json",source:"lint"})}return applied.toSorted((left,right)=>left.workspace.localeCompare(right.workspace))};var detectedWorkspaces=(scanDirectory,detection)=>detection.manifests.map((manifest)=>path27.posix.dirname(relativePosixPath(scanDirectory,manifest.path))).filter((workspace)=>workspace!==""&&workspace!==".").toSorted();var primarySkillsForWorkspace=(contextPlan,relativeWorkspacePath)=>{const skills=scopeForWorkspacePath(contextPlan,relativeWorkspacePath).contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id);return uniqueSorted2(relativeWorkspacePath===".agents"?skills:scopedPrimarySkills(skills))};var skillIdsForContextPlan=(contextPlan)=>uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id)));var workspacePathForPromptTarget=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return".agents"}if(relativePath==="AGENTS.md"){return"."}if(relativePath==="docs/AGENTS.md"){return"docs"}return path27.posix.dirname(relativePath)};var promptScope=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return"shared"}if(relativePath==="AGENTS.md"){return"root"}return relativePath==="docs/AGENTS.md"?"docs":"workspace"};var ownedPathsForPromptSpec=(spec)=>{if(spec.workspacePath==="docs"){return["docs"]}if(spec.workspacePath===null||spec.workspacePath==="."){return["."]}return[spec.workspacePath]};var buildPromptSpec=({forceGenerated=false,scanDirectory,relativePath,packs,primarySkills})=>{const sourcePath=path27.join(scanDirectory,relativePath);const source=!forceGenerated&&existsSync10(sourcePath)?"copied":"generated";const workspacePath=workspacePathForPromptTarget(relativePath);return{opensrcReferences:opensrcReferencesForPacks(packs),packs,primarySkills,scope:promptScope(relativePath),source,specFile:specPathForPromptTarget(relativePath),targetFile:relativePath,workspacePath}};var specialistIdForPath=(relativePath)=>relativePath.replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"");var buildSubagentManifestSpec=({detection,finalPacks,promptSpecs,workspaces=detectedWorkspaces(detection.cwd,detection)})=>{const specialists=promptSpecs.filter((spec)=>spec.scope==="docs"||spec.scope==="workspace").map((spec)=>({id:specialistIdForPath(spec.workspacePath??spec.targetFile),ownedPaths:ownedPathsForPromptSpec(spec),guidanceFiles:[spec.targetFile],packs:spec.packs,skills:spec.primarySkills.length===0?["simplify"]:spec.primarySkills,notes:subagentSpecialistNote(spec)}));return sortSubagentSpecialists({targetFile:".agents/subagents/manifest.mjs",specFile:".devpunks/specs/subagents/manifest-spec.json",finalPacks,workspaces,specialists})};var decodeSubagentManifestModule=(source)=>{const namedExport=/export\s*\{\s*(?:agents\s*,\s*capabilityPacks|capabilityPacks\s*,\s*agents)\s*\};?\s*$/u;const exportsAgentsDeclaration=/^export\s+const\s+agents\s*=/mu.test(source);const exportsCapabilityPacksDeclaration=/^export\s+const\s+capabilityPacks\s*=/mu.test(source);if(!namedExport.test(source)&&!(exportsAgentsDeclaration&&exportsCapabilityPacksDeclaration)){throw new Error("Subagent manifest does not export agents and capabilityPacks")}const sandbox2={};runInNewContext(`${source.replaceAll(/^export\s+const\s+agents\s*=/gmu,"const agents =").replaceAll(/^export\s+const\s+capabilityPacks\s*=/gmu,"const capabilityPacks =").replace(namedExport,"")}
2483
+ `)};var rootPackageJsonRecord=({scanDirectory,outputDirectory})=>{const rootPackageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:"package.json",scanDirectory});return rootPackageJsonPath===null?null:readJsonRecord(rootPackageJsonPath)};var oxlintDependencyVersionFor=({rootPackageJson,isRootWorkspace})=>{const rootDevDependencies=rootPackageJson?.devDependencies;if(isRecord8(rootDevDependencies)&&typeof rootDevDependencies.oxlint==="string"){return compatibleOxlintVersion(rootDevDependencies.oxlint)}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;return!isRootWorkspace&&isRecord8(catalog)&&typeof catalog.oxlint==="string"?"catalog:":compilerCapableOxlintVersion};var catalogVersionFor=(rootPackageJson,packageName)=>{const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;const catalogVersion=isRecord8(catalog)?catalog[packageName]:undefined;return typeof catalogVersion==="string"?catalogVersion:null};var dependencyVersionFor=({rootPackageJson,packageName,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const requiredVersion=requiredVersions[packageName];if(requiredVersion!==undefined){if(!isRootWorkspace&&catalogVersionFor(rootPackageJson,packageName)===requiredVersion){return"catalog:"}return requiredVersion}if(packageName==="oxlint"&&requiresCompilerOxlint){return oxlintDependencyVersionFor({isRootWorkspace,rootPackageJson})}const dependencySections=[rootPackageJson?.devDependencies,rootPackageJson?.dependencies,rootPackageJson?.peerDependencies,rootPackageJson?.optionalDependencies];for(const section2 of dependencySections){if(isRecord8(section2)&&typeof section2[packageName]==="string"){return section2[packageName]}}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord8(workspaces)?workspaces.catalog:undefined;if(!isRootWorkspace&&isRecord8(catalog)&&typeof catalog[packageName]==="string"){return"catalog:"}return defaultDevDependencyVersion};var packageDependencySections=["dependencies","devDependencies","peerDependencies","optionalDependencies"];var packageDependencyEntries=(packageJson,packageName)=>{const entries=[];for(const section2 of packageDependencySections){const dependencies=packageJson[section2];const declaredVersion=isRecord8(dependencies)?dependencies[packageName]:undefined;if(typeof declaredVersion==="string"){entries.push({section:section2,version:declaredVersion})}}return entries};var dependencyMatchesRequiredVersion=({packageName,requiredVersion,rootPackageJson,declaredVersion})=>declaredVersion===requiredVersion||declaredVersion==="catalog:"&&catalogVersionFor(rootPackageJson,packageName)===requiredVersion;var isMissingRequiredOxlintCatalogReference=({declaredVersion,isRootWorkspace,packageName,rootPackageJson})=>!isRootWorkspace&&packageName==="oxlint"&&declaredVersion==="catalog:"&&catalogVersionFor(rootPackageJson,packageName)===null;var dependencyCanUseRequiredVersion=({allowOxlintCatalogRepair=false,declaredVersion,isRootWorkspace,packageName,requiredVersion,rootPackageJson})=>allowOxlintCatalogRepair&&packageName==="oxlint"&&declaredVersion==="catalog:"||dependencyMatchesRequiredVersion({declaredVersion,packageName,requiredVersion,rootPackageJson})||isMissingRequiredOxlintCatalogReference({declaredVersion,isRootWorkspace,packageName,rootPackageJson});var isMigratableRequiredDevDependency=(allowMigration,section2)=>allowMigration&&section2==="devDependencies";var plannedDevDependencyVersionFor=({packageJson,packageName,rootPackageJson,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const{devDependencies}=packageJson;const existingVersion=isRecord8(devDependencies)?devDependencies[packageName]:undefined;const requiredVersion=requiredVersions[packageName];if(typeof existingVersion==="string"&&(requiredVersion===undefined||packageName==="oxlint"&&existingVersion==="catalog:"||dependencyMatchesRequiredVersion({declaredVersion:existingVersion,packageName,requiredVersion,rootPackageJson}))){return existingVersion}return dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson})};var preserveCompilerOxlintCompatibility=({devDependencies,packageJson,packageName,requiresCompilerOxlint})=>{if(packageName==="oxlint"&&requiresCompilerOxlint&&typeof devDependencies.oxlint==="string"){devDependencies.oxlint=compatibleOxlintVersion(devDependencies.oxlint)}else if(packageName==="oxlint"&&requiresCompilerOxlint){const incompatibleSection=["dependencies","peerDependencies","optionalDependencies"].find((sectionName)=>{const section2=packageJson[sectionName];const current=isRecord8(section2)?section2.oxlint:undefined;return typeof current==="string"&&compatibleOxlintVersion(current)!==current});if(incompatibleSection!==undefined){throw new CliValidationError({message:`React Compiler linting found incompatible Oxlint in ${incompatibleSection}; move Oxlint to devDependencies at ${compilerCapableOxlintVersion} or newer.`})}}};var patchPackageJsonDependencies=({allowOxlintCatalogRepair=false,allowRequiredDevDependencyMigration=false,packageJson,packageNames,rootPackageJson,isRootWorkspace,requiresCompilerOxlint,requiredVersions})=>{const nextPackageJson={...packageJson};const devDependencies=isRecord8(nextPackageJson.devDependencies)?{...nextPackageJson.devDependencies}:{};for(const packageName of packageNames){const existingDependencies=packageDependencyEntries(nextPackageJson,packageName);const requiredVersion=requiredVersions[packageName];if(requiredVersion!==undefined&&existingDependencies.length>0){for(const existingDependency2 of existingDependencies){if(isMigratableRequiredDevDependency(allowRequiredDevDependencyMigration,existingDependency2.section)){continue}if(!dependencyCanUseRequiredVersion({allowOxlintCatalogRepair,declaredVersion:existingDependency2.version,isRootWorkspace,packageName,requiredVersion,rootPackageJson})){throw new CliValidationError({message:`Lint asset requires ${packageName}@${requiredVersion}, but ${existingDependency2.section} declares ${existingDependency2.version}.`})}}const existingDevDependency=existingDependencies.find(({section:section2})=>section2==="devDependencies");for(const existingDependency2 of existingDependencies){if(existingDependency2.section!=="dependencies"||allowOxlintCatalogRepair&&existingDependency2.version==="catalog:"){continue}const section2=nextPackageJson[existingDependency2.section];if(isRecord8(section2)){const nextSection={...section2};Reflect.deleteProperty(nextSection,packageName);nextPackageJson[existingDependency2.section]=nextSection}}devDependencies[packageName]=existingDevDependency===undefined?dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson}):plannedDevDependencyVersionFor({isRootWorkspace,packageJson:nextPackageJson,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson});continue}const[existingDependency]=existingDependencies;if(existingDependency!==undefined){preserveCompilerOxlintCompatibility({devDependencies,packageJson,packageName,requiresCompilerOxlint});continue}devDependencies[packageName]=dependencyVersionFor({isRootWorkspace,packageName,requiredVersions,requiresCompilerOxlint,rootPackageJson})}nextPackageJson.devDependencies=Object.fromEntries(Object.entries(devDependencies).toSorted(([left],[right])=>left.localeCompare(right)));return nextPackageJson};var validatePlannedPackageJsonDependencies=(input2)=>{for(const[packageName,requiredVersion]of Object.entries(input2.requiredVersions)){const existingDependencies=packageDependencyEntries(input2.packageJson,packageName);for(const existingDependency of existingDependencies){if(existingDependency.section==="devDependencies"){continue}if(!dependencyCanUseRequiredVersion({...input2.allowOxlintCatalogRepair===undefined?{}:{allowOxlintCatalogRepair:input2.allowOxlintCatalogRepair},declaredVersion:existingDependency.version,isRootWorkspace:input2.isRootWorkspace,packageName,requiredVersion,rootPackageJson:input2.rootPackageJson})){throw new CliValidationError({message:`Lint asset requires ${packageName}@${requiredVersion}, but ${existingDependency.section} declares ${existingDependency.version}.`})}}const ordinaryDependency=existingDependencies.find(({section:section2})=>section2==="dependencies");if(ordinaryDependency!==undefined&&!(input2.allowOxlintCatalogRepair===true&&packageName==="oxlint"&&ordinaryDependency.version==="catalog:")){throw new CliValidationError({message:`Move ${packageName}@${requiredVersion} from dependencies to devDependencies before update.`})}}};var hasDirectNonFallthroughCommand=(script,segments)=>segments.some(({end,start})=>{const segment=script.slice(start,end).trimStart();return/^(?:@?exit)(?:\s|$)/iu.test(segment)||/^exec(?:\s|$)/u.test(segment)});var isAmbiguousShellSyntax=(script,index)=>{const character=script[index]??"";return/[|;<>\r\n(){}]/u.test(character)||script.startsWith("$(",index)||character==="#"&&(index===0||/\s/u.test(script[index-1]??""))};var analyzeShellChain=(script)=>{const backgroundSeparators=[];const separators=[];const segments=[];let escaped=false;let quote=null;let safe=true;let segmentStart=0;for(let index=0;index<script.length;index+=1){const character=script[index]??"";if(escaped){escaped=false;continue}if(character==="\\"&&quote!=="'"){escaped=true;continue}if(quote!==null){if(character===quote){quote=null}continue}if(character==="'"||character==='"'||character==="`"){quote=character;safe&&=character!=="`";continue}if(character==="&"){const isAnd=script[index+1]==="&";segments.push({end:index,start:segmentStart});if(isAnd){separators.push({end:index+2,start:index});index+=1}else{backgroundSeparators.push(index);safe=false}segmentStart=index+1;continue}if(isAmbiguousShellSyntax(script,index)){safe=false}}segments.push({end:script.length,start:segmentStart});const complete=[quote===null,!escaped,backgroundSeparators.length===0,segments.every(({end,start})=>script.slice(start,end).trim().length>0),!hasDirectNonFallthroughCommand(script,segments)].every(Boolean);safe&&=complete;return{backgroundSeparators,safe,segments,separators}};var commandSegmentIndex=(script,command,chain)=>chain.safe?chain.segments.findIndex(({end,start})=>script.slice(start,end).trim()===command):-1;var hasShellAndCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);return commandSegmentIndex(script,command,chain)!==-1};var hasBackgroundedShellCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);return chain.backgroundSeparators.length>0&&chain.segments.some(({end,start})=>script.slice(start,end).trim()===command)};var removeShellAndCommandSegment=(script,command)=>{const chain=analyzeShellChain(script);const index=commandSegmentIndex(script,command,chain);if(index===-1){return script}if(chain.segments.length===1){return""}if(index===0){return script.slice(chain.separators[0]?.end).trimStart()}if(index===chain.segments.length-1){return script.slice(0,chain.separators[index-1]?.start).trimEnd()}const prefix=script.slice(0,chain.separators[index-1]?.start).trimEnd();const suffix=script.slice(chain.separators[index]?.end).trimStart();return`${prefix} && ${suffix}`};var appendShellAndCommandSegment=(script,command)=>{if(script.trim().length===0){return command}const chain=analyzeShellChain(script);if(!chain.safe){throw new CliValidationError({message:"Lint setup cannot safely compose package.json scripts.prepare."})}if(commandSegmentIndex(script,command,chain)!==-1){return script}const existing=script.trimEnd();const trailingWhitespace=script.slice(existing.length);return`${existing} && ${command}${trailingWhitespace}`};var patchPackageJsonPrepare=(packageJson,commands)=>{if(commands.length===0){return packageJson}const scripts=isRecord8(packageJson.scripts)?{...packageJson.scripts}:{};const existingPrepare=scripts.prepare;if(existingPrepare!==undefined&&typeof existingPrepare!=="string"){throw new CliValidationError({message:"Lint setup requires package.json scripts.prepare to be a string."})}let prepare=typeof existingPrepare==="string"?existingPrepare:"";for(const command of commands){prepare=appendShellAndCommandSegment(prepare,command)}scripts.prepare=prepare;return{...packageJson,scripts}};var lintTargetManifests=(detection,contextPlan)=>{if(!detection.monorepo||contextPlan.scopes.some((scope3)=>scope3.id==="root"&&scope3.contributions.some(isCommitGateContribution))){return detection.manifests}return detection.manifests.filter((manifest)=>path27.posix.dirname(toPosixPath(manifest.relativePath))!==".")};var existingJsonOxlintConfigPath=({scanDirectory,outputDirectory,workspacePath})=>{const candidates=[".oxlintrc.json",".oxlintrc.jsonc"].map((fileName)=>workspacePath==="."?fileName:path27.posix.join(workspacePath,fileName));for(const candidate of candidates){const configPath=sourceOrOutputPath({outputDirectory,relativePath:candidate,scanDirectory});if(configPath!==null){return configPath}}return null};var readExistingJsonOxlintConfig=(options4)=>{const configPath=existingJsonOxlintConfigPath(options4);return configPath===null?{}:readJsonRecord(configPath)};var hasRootDocsContent=(scanDirectory)=>{const docsDirectory=path27.join(scanDirectory,"docs");if(!existsSync10(docsDirectory)){return false}return readdirSync4(docsDirectory).some((entry)=>entry!=="AGENTS.md")};var ignoredPromptTargetDirectories=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","build","coverage","dist","node_modules","opensrc","skills","tmp","worktrees"]);var discoverAuthoredAgentPromptTargets=(scanDirectory)=>{const targets=[];const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){if(entry.isDirectory()){if(!ignoredPromptTargetDirectories.has(entry.name)){visit2(path27.join(directory3,entry.name))}continue}if(entry.isFile()&&entry.name==="AGENTS.md"){targets.push(relativePosixPath(scanDirectory,path27.join(directory3,entry.name)))}}};if(existsSync10(scanDirectory)){visit2(scanDirectory)}return targets.toSorted()};var hasJavaScriptWorkspaceDependency=(manifest)=>manifest.dependencies.some((dependency)=>dependency==="next"||dependency==="react"||dependency==="react-dom"||dependency==="typescript"||dependency==="vite"||dependency.startsWith("@effect/")||dependency.startsWith("@tanstack/")||dependency.startsWith("@trpc/"));var isPythonUvWorkspace=({scanDirectory,outputDirectory,workspacePath,manifest})=>{const prefix=workspacePath==="."?"":`${workspacePath}/`;const hasPythonProject=sourceOrOutputPath({outputDirectory,relativePath:`${prefix}pyproject.toml`,scanDirectory})!==null||sourceOrOutputPath({outputDirectory,relativePath:`${prefix}uv.lock`,scanDirectory})!==null;return hasPythonProject&&!hasJavaScriptWorkspaceDependency(manifest)};var scopeIdForWorkspacePath=(workspacePath)=>{if(workspacePath===".agents"){return"shared"}return workspacePath==="."?"root":workspacePath};var scopeForWorkspacePath=(contextPlan,relativeWorkspacePath)=>{const scope3=contextPlan.scopes.find(({id})=>id===scopeIdForWorkspacePath(relativeWorkspacePath));if(scope3===undefined){throw new Error(`Missing compiled context scope: ${relativeWorkspacePath}`)}return scope3};var packsForWorkspace=(contextPlan,relativeWorkspacePath)=>scopeForWorkspacePath(contextPlan,relativeWorkspacePath).packs.map(({id})=>id);var hasManagedOxlintCatalogReceipt=({priorManagedDependencies=[],outputDirectory,priorManagedStructuredEntries=[],scanDirectory})=>{if(priorManagedDependencies.some(({name:name2,version:dependencyVersion})=>(name2==="oxlint-tsgolint"||name2==="@effect/tsgo")&&dependencyVersion==="catalog:")){return true}if(priorManagedStructuredEntries.some(isOxlintCatalogStructuredEntry)){return true}const manifestPath=sourceOrOutputPath({outputDirectory,relativePath:".devpunks/scaffold-manifest.json",scanDirectory});if(manifestPath===null){return false}const{managedStructuredEntries}=readJsonRecord(manifestPath);return Array.isArray(managedStructuredEntries)&&managedStructuredEntries.some(isOxlintCatalogStructuredEntry)};var planCompatibleOxlintCatalog=({priorManagedDependencies,priorManagedStructuredEntries,requireReceiptOwnership,selections,rootPackageJson,plannedStructuredEntries,scanDirectory,outputDirectory})=>{const catalogConsumers=selections.filter(({packageJson})=>packageDependencySections.some((section2)=>{const dependencies=packageJson[section2];return isRecord8(dependencies)&&dependencies.oxlint==="catalog:"}));const catalogSelections=catalogConsumers.filter(({requiredOxlintVersion,requiresCompilerOxlint})=>requiresCompilerOxlint||requiredOxlintVersion!==undefined);if(catalogConsumers.length===0||rootPackageJson===null){return}if(sourceOrOutputPath({outputDirectory,relativePath:"pnpm-workspace.yaml",scanDirectory})!==null){throw new CliValidationError({message:"Lint setup cannot manage catalog: dependencies through package.json when pnpm-workspace.yaml owns the workspace catalog."})}const requiredVersion=catalogSelections.find((selection)=>selection.requiredOxlintVersion!==undefined)?.requiredOxlintVersion;const patched=catalogSelections.length===0?rootPackageJson:patchOxlintCatalog(rootPackageJson,requiredVersion);const patchedOxlint=isRecord8(patched.workspaces)&&isRecord8(patched.workspaces.catalog)?patched.workspaces.catalog.oxlint:undefined;const currentOxlint=catalogVersionFor(rootPackageJson,"oxlint");if(currentOxlint!==null&&typeof patchedOxlint==="string"&&patchedOxlint!==currentOxlint&&requireReceiptOwnership&&!hasManagedOxlintCatalogReceipt({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},scanDirectory})){throw new CliValidationError({message:`Lint setup found an ownership conflict: project-owned Oxlint catalog value ${currentOxlint} is incompatible with required ${patchedOxlint}; Harness will not replace it without prior receipt ownership.`})}if(typeof patchedOxlint==="string"){plannedStructuredEntries.push({file:"package.json",kind:"field",path:["workspaces","catalog","oxlint"],source:"lint",value:patchedOxlint})}};var skipLintWorkspace=({planOnly,detection,manifest,outputDirectory,scanDirectory,workspacePath})=>planOnly?detection.detectedLanguages.includes("python")&&!hasJavaScriptWorkspaceDependency(manifest):isPythonUvWorkspace({manifest,outputDirectory,scanDirectory,workspacePath});var writeAppliedLintConfigs=({plannedPackageDocuments={},priorManagedDependencies,priorManagedStructuredEntries,allowRequiredDevDependencyMigration,scanDirectory,outputDirectory,detection,contextPlan,baseline,planArtifact,generatedFiles,plannedDependencies,plannedStructuredEntries,planOnly})=>{const rootPackageJson=rootPackageJsonRecord({outputDirectory,scanDirectory});const allowOxlintCatalogRepair=!allowRequiredDevDependencyMigration||hasManagedOxlintCatalogReceipt({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},scanDirectory});const applied=[];const selections=[];const rootPrepareAssets=new Map;let plannedRootPackageJson=null;const planManifest=(manifest)=>{const manifestRelativePath=toPosixPath(manifest.relativePath);const normalizedWorkspacePath=path27.posix.dirname(manifestRelativePath);if(skipLintWorkspace({detection,manifest,outputDirectory,planOnly,scanDirectory,workspacePath:normalizedWorkspacePath})){return}const workspacePacks=packsForWorkspace(contextPlan,normalizedWorkspacePath);const selectedAssets=resolveLintAssetsForPacks(workspacePacks,baseline,{packageName:manifest.packageName});const isWikiWorkspace=wikiWorkspacePaths.has(normalizedWorkspacePath);const assets=isWikiWorkspace?selectedAssets.filter(({id})=>id==="typescript-anti-slop"||id==="punks-anti-slop-transition"):selectedAssets;if(assets.length===0){return}const requiresCompilerOxlint=assets.some(({id})=>id==="react-core");const configFile=normalizedWorkspacePath==="."?oxlintConfigFileName:path27.posix.join(normalizedWorkspacePath,oxlintConfigFileName);const existingConfig=readExistingJsonOxlintConfig({outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath});const workspacePlugins=assets.flatMap((asset)=>asset.jsPlugins);generatedFiles.push(planArtifact({content:isWikiWorkspace?makeWikiOxlintConfig({jsPlugins:workspacePlugins.map((plugin)=>({name:localLintPluginName(plugin,normalizedWorkspacePath),specifier:plugin.specifier})),rules:Object.fromEntries(Object.entries(mergedAssetRules(assets)).map(([name2,severity])=>{const plugin=workspacePlugins.find((entry)=>name2.startsWith(`${entry.name}/`));return[plugin===undefined?name2:`${localLintPluginName(plugin,normalizedWorkspacePath)}${name2.slice(plugin.name.length)}`,severity]}))}):encodeOxlintConfigTs({assets,existingConfig,workspacePath:normalizedWorkspacePath}),kind:"harness",path:configFile,source:"lint"}));for(const sourceFile of assets.flatMap((asset)=>asset.sourceFiles??[])){generatedFiles.push(planArtifact({content:readBaselineDataFile(baseline.dataRoot,...sourceFile.sourcePath.split("/")),kind:"harness",path:normalizedWorkspacePath==="."?sourceFile.targetPath:path27.posix.join(normalizedWorkspacePath,sourceFile.targetPath),source:"lint"}))}const packageJsonFile=manifestRelativePath;const requiredDevDependencies=uniqueSorted2([...Object.keys(lintToolchainVersions),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);const requiredDevDependencyVersions=mergedAssetVersions(assets);const prepareCommands=detection.monorepo?[]:uniqueSorted2(assets.flatMap((asset)=>asset.prepareCommands??[]));if(detection.monorepo){for(const asset of assets.filter((candidate)=>(candidate.prepareCommands?.length??0)>0)){rootPrepareAssets.set(asset.id,asset)}}const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:packageJsonFile,scanDirectory});const packageJson=plannedPackageDocuments[packageJsonFile]??(packageJsonPath===null?{}:readJsonRecord(packageJsonPath));const scripts=isRecord8(packageJson.scripts)?packageJson.scripts:{};const quality=resolveQualityCommands(scripts);const resolvedScripts={...scripts,...quality.defaults};for(const name2 of["lint","format:check","format-check","check:format"]){const value5=resolvedScripts[name2];if(typeof value5!=="string"){continue}plannedStructuredEntries.push({file:packageJsonFile,kind:"field",path:["scripts",name2],source:"lint",value:value5})}const packageJsonWithQuality={...packageJson,scripts:resolvedScripts};selections.push({packageJson,requiredOxlintVersion:requiredDevDependencyVersions.oxlint,requiresCompilerOxlint});if(planOnly){validatePlannedPackageJsonDependencies({allowOxlintCatalogRepair,isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson});patchPackageJsonPrepare(packageJson,prepareCommands)}for(const command of prepareCommands){plannedStructuredEntries.push({file:packageJsonFile,kind:"required-shell-segment",path:["scripts","prepare"],source:"lint",value:command})}if(!planOnly){const plannedPackageJson=patchPackageJsonPrepare(patchPackageJsonDependencies({allowOxlintCatalogRepair,allowRequiredDevDependencyMigration,isRootWorkspace:normalizedWorkspacePath===".",packageJson:packageJsonWithQuality,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson}),prepareCommands);if(normalizedWorkspacePath==="."){plannedRootPackageJson=plannedPackageJson}else{planArtifact({content:encodePrettyJson2(plannedPackageJson),kind:"harness",path:packageJsonFile,source:"lint"})}}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:plannedDevDependencyVersionFor({isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageName:name2,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint,rootPackageJson}),workspace:normalizedWorkspacePath})));applied.push({workspace:normalizedWorkspacePath,configFile,packageJsonFile,assets:assets.map((asset)=>asset.id),requiredDevDependencies})};for(const manifest of lintTargetManifests(detection,contextPlan)){planManifest(manifest)}if(rootPackageJson!==null&&rootPrepareAssets.size>0){const assets=[...rootPrepareAssets.values()];const prepareCommands=uniqueSorted2(assets.flatMap((asset)=>asset.prepareCommands??[]));const requiredDevDependencies=uniqueSorted2([...Object.keys(lintToolchainVersions),...assets.flatMap((asset)=>asset.requiredDevDependencies)]);const requiredDevDependencyVersions=mergedAssetVersions(assets);if(planOnly){validatePlannedPackageJsonDependencies({allowOxlintCatalogRepair,isRootWorkspace:true,packageJson:rootPackageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson});patchPackageJsonPrepare(rootPackageJson,prepareCommands)}for(const command of prepareCommands){plannedStructuredEntries.push({file:"package.json",kind:"required-shell-segment",path:["scripts","prepare"],source:"lint",value:command})}if(!planOnly){plannedRootPackageJson=patchPackageJsonPrepare(patchPackageJsonDependencies({allowOxlintCatalogRepair,allowRequiredDevDependencyMigration,isRootWorkspace:true,packageJson:plannedRootPackageJson??rootPackageJson,packageNames:requiredDevDependencies,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson}),prepareCommands)}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:plannedDevDependencyVersionFor({isRootWorkspace:true,packageJson:rootPackageJson,packageName:name2,requiredVersions:requiredDevDependencyVersions,requiresCompilerOxlint:false,rootPackageJson}),workspace:"."})).filter((proposed)=>!plannedDependencies.some((existing)=>existing.workspace===proposed.workspace&&existing.section===proposed.section&&existing.name===proposed.name&&existing.version===proposed.version&&existing.source===proposed.source&&existing.revision===undefined)))}planCompatibleOxlintCatalog({outputDirectory,...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},plannedStructuredEntries,requireReceiptOwnership:allowRequiredDevDependencyMigration,rootPackageJson,scanDirectory,selections});const plannedOxlintCatalogEntry=plannedStructuredEntries.find(isOxlintCatalogStructuredEntry);if(plannedRootPackageJson!==null&&typeof plannedOxlintCatalogEntry?.value==="string"){plannedRootPackageJson=patchOxlintCatalog(plannedRootPackageJson,plannedOxlintCatalogEntry.value)}if(plannedRootPackageJson!==null){planArtifact({content:encodePrettyJson2(plannedRootPackageJson),kind:"harness",path:"package.json",source:"lint"})}return applied.toSorted((left,right)=>left.workspace.localeCompare(right.workspace))};var detectedWorkspaces=(scanDirectory,detection)=>detection.manifests.map((manifest)=>path27.posix.dirname(relativePosixPath(scanDirectory,manifest.path))).filter((workspace)=>workspace!==""&&workspace!==".").toSorted();var primarySkillsForWorkspace=(contextPlan,relativeWorkspacePath)=>{const skills=scopeForWorkspacePath(contextPlan,relativeWorkspacePath).contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id);return uniqueSorted2(relativeWorkspacePath===".agents"?skills:scopedPrimarySkills(skills))};var skillIdsForContextPlan=(contextPlan)=>uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id)));var workspacePathForPromptTarget=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return".agents"}if(relativePath==="AGENTS.md"){return"."}if(relativePath==="docs/AGENTS.md"){return"docs"}return path27.posix.dirname(relativePath)};var promptScope=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return"shared"}if(relativePath==="AGENTS.md"){return"root"}return relativePath==="docs/AGENTS.md"?"docs":"workspace"};var ownedPathsForPromptSpec=(spec)=>{if(spec.workspacePath==="docs"){return["docs"]}if(spec.workspacePath===null||spec.workspacePath==="."){return["."]}return[spec.workspacePath]};var buildPromptSpec=({forceGenerated=false,scanDirectory,relativePath,packs,primarySkills})=>{const sourcePath=path27.join(scanDirectory,relativePath);const source=!forceGenerated&&existsSync10(sourcePath)?"copied":"generated";const workspacePath=workspacePathForPromptTarget(relativePath);return{opensrcReferences:opensrcReferencesForPacks(packs),packs,primarySkills,scope:promptScope(relativePath),source,specFile:specPathForPromptTarget(relativePath),targetFile:relativePath,workspacePath}};var specialistIdForPath=(relativePath)=>relativePath.replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"");var buildSubagentManifestSpec=({detection,finalPacks,promptSpecs,workspaces=detectedWorkspaces(detection.cwd,detection)})=>{const specialists=promptSpecs.filter((spec)=>spec.scope==="docs"||spec.scope==="workspace").map((spec)=>({id:specialistIdForPath(spec.workspacePath??spec.targetFile),ownedPaths:ownedPathsForPromptSpec(spec),guidanceFiles:[spec.targetFile],packs:spec.packs,skills:spec.primarySkills.length===0?["simplify"]:spec.primarySkills,notes:subagentSpecialistNote(spec)}));return sortSubagentSpecialists({targetFile:".agents/subagents/manifest.mjs",specFile:".devpunks/specs/subagents/manifest-spec.json",finalPacks,workspaces,specialists})};var decodeSubagentManifestModule=(source)=>{const namedExport=/export\s*\{\s*(?:agents\s*,\s*capabilityPacks|capabilityPacks\s*,\s*agents)\s*\};?\s*$/u;const exportsAgentsDeclaration=/^export\s+const\s+agents\s*=/mu.test(source);const exportsCapabilityPacksDeclaration=/^export\s+const\s+capabilityPacks\s*=/mu.test(source);if(!namedExport.test(source)&&!(exportsAgentsDeclaration&&exportsCapabilityPacksDeclaration)){throw new Error("Subagent manifest does not export agents and capabilityPacks")}const sandbox2={};runInNewContext(`${source.replaceAll(/^export\s+const\s+agents\s*=/gmu,"const agents =").replaceAll(/^export\s+const\s+capabilityPacks\s*=/gmu,"const capabilityPacks =").replace(namedExport,"")}
2484
2484
  globalThis.__manifest = { agents, capabilityPacks };`,sandbox2);if(sandbox2.__manifest===undefined){throw new Error("Subagent manifest does not export agents and capabilityPacks")}return sandbox2.__manifest};var normalizeSubagentManifestSkillIds=({baseline,manifest})=>{const aliases=new Map((baseline.skillIdAliases??[]).map(({alias,canonicalId})=>[alias,canonicalId]));const normalize2=(skillIds)=>{const normalized=skillIds.map((skillId)=>aliases.get(skillId)??skillId);if(normalized.every((skillId,index)=>skillId===skillIds[index])){return skillIds}return uniqueSorted2(normalized)};const capabilityPacks=Object.fromEntries(Object.entries(manifest.capabilityPacks).map(([id,pack])=>[id,{...pack,skills:normalize2(pack.skills)}]));const agents=manifest.agents.map((agent)=>agent.skills===undefined?agent:{...agent,skills:normalize2(agent.skills)});return{agents,capabilityPacks}};var renderPreservedSubagentManifestModule=(manifest)=>["const capabilityPacks = ",JSON.stringify(manifest.capabilityPacks,null,2),`;
2485
2485
  `,"const agents = ",JSON.stringify(manifest.agents,null,2),`;
2486
2486
  `,`export { agents, capabilityPacks };
@@ -2488,7 +2488,7 @@ globalThis.__manifest = { agents, capabilityPacks };`,sandbox2);if(sandbox2.__ma
2488
2488
  commands:
2489
2489
  lint:
2490
2490
  run: ${managedCommitGateCommand}
2491
- `,path:gateMerge.path},{content:readBaselineDataFile(baseline.dataRoot,"scripts/commit-gate-runner.mjs"),path:".agents/scripts/commit-gate-runner.mjs"},{content:encodePrettyJson2(gateConsumers.map(({contribution:contribution2,path:consumerPath})=>({...contribution2.contract,owner:contribution2.identity.id,path:consumerPath}))),path:".devpunks/commit-gate-contracts.json"}]){generatedFiles.push(planArtifact({...file5,kind:"harness",source:"baseline"}))}if(!planOnly){const packageFile=plannedFiles.find((file5)=>file5.path===gateOwnerManifest);const packageInput=packageFile===undefined?readJsonRecord(path27.join(scanDirectory,gateOwnerManifest)):JSON.parse(packageFile.content);if(!isRecord8(packageInput)){throw new Error("Commit Gate package manifest must be a JSON object.")}const packageJson=packageInput;const patched=encodePrettyJson2({...packageJson,devDependencies:{...isRecord8(packageJson.devDependencies)?packageJson.devDependencies:{},lefthook:"2.1.10"}});if(packageFile!==undefined){plannedFiles.splice(plannedFiles.indexOf(packageFile),1)}planArtifact({content:patched,kind:"harness",path:gateOwnerManifest,source:"lint"})}}return gatePlan};var selectedLintAssetIdsByPack=(finalPacks,lintAssets)=>{const lintAssetIdsByPack={};for(const packId of finalPacks){const assetIds=lintAssets.filter((asset)=>asset.sourcePacks.includes(packId)).map((asset)=>asset.id);if(assetIds.length>0){lintAssetIdsByPack[packId]=assetIds}}return lintAssetIdsByPack};function runScaffoldOutputPipeline({plannedPackageDocuments,priorManagedDependencies,priorManagedStructuredEntries,scanDirectory,detection,additionalPromptTargets=[],additionalSkillSelection,contextPlan:suppliedContextPlan,finalPacks:suppliedFinalPacks,outputDirectory,repoShapeMode,toolBootstrapStatuses=[],preserveExistingManagedFiles,displayOutputDirectory,baseline=bundledBaseline,baselineOrigin=baseline.summary.authoritySource==="bundled"?"bundled":"resolved",compileDesiredOutput=compileDesiredScaffoldOutput,desiredState:suppliedDesiredState,settings,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2,filesystemSession:suppliedFilesystemSession,planOnly=false,returnPlanOnly=false}){return gen2(function*executeScaffoldOutputPipeline(){const sharedPrompt=yield*readSharedPrompt(baseline);const baselineSummary2=structuredClone(baseline.summary);if(suppliedContextPlan===undefined&&suppliedFinalPacks===undefined){const message="Scaffold output requires a compiled context plan or legacy pack selection";return yield*new ContextPlanCompilationFailure({cause:new Error(message),message,operation:"compile-context-plan"})}const compiledContextPlan=suppliedContextPlan??(yield*compileScaffoldContextPlan({additionalPromptTargets,baseline,detection,finalPacks:suppliedFinalPacks??[],preserveExistingSubagentManifest:preserveExistingManagedFiles??true,scanDirectory}));const materializePipeline=async()=>{const contextPlan=compiledContextPlan;const persistContextPlan=suppliedContextPlan!==undefined;const finalPacks=packsForWorkspace(contextPlan,".");const shouldPreserveExistingManagedFiles=preserveExistingManagedFiles??true;const renderedOutputDirectory=displayOutputDirectory??outputDirectory;const generatedFiles=[];const promptOutputs=[];const promptSpecFiles=[];const lintSpecFiles=[];const sourceGuideFiles=[];const skillFiles=[];const subagentFiles=[];const scriptFiles=[];const hookFiles=[];const harnessFiles=[];const plannedFiles=[];const plannedDependencies=[];const plannedStructuredEntries=[];const plannedDirectoriesToReset=[];const planArtifact=(file5)=>{plannedFiles.push({...file5,obligation:file5.obligation??producerObligation(file5.source,[file5.revision??baseline.summary.resolvedVersion])});return file5.path};const originForBaseline=(sourceBaseline)=>{if(sourceBaseline===baseline){return baselineOrigin}if(sourceBaseline===additionalSkillSelection?.baseline&&additionalSkillSelection.baselineOrigin!==undefined){return additionalSkillSelection.baselineOrigin}return sourceBaseline.summary.authoritySource==="bundled"?"bundled":"resolved"};const planDirectory=({sourceBaseline,sourceDirectory,targetDirectory,source,preserveBytes=false})=>{const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){const absolutePath=path27.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const sourceRelativePath=relativePosixPath(sourceDirectory,absolutePath);if(targetDirectory===".agents/skills/verify-behavior"&&source==="baseline"&&sourceRelativePath.startsWith("references/")&&existsSync10(path27.join(scanDirectory,targetDirectory,sourceRelativePath))){continue}const baselineRelativePath=relativePosixPath(sourceBaseline.skillsRoot,absolutePath);const logicalBaselineRelativePath=originForBaseline(sourceBaseline)==="bundled"?logicalBundledSkillRelativePath(baselineRelativePath):baselineRelativePath;const logicalSourceRelativePath=logicalBaselineRelativePath===baselineRelativePath?sourceRelativePath:path27.posix.relative(relativePosixPath(sourceBaseline.skillsRoot,sourceDirectory),logicalBaselineRelativePath);const relativePath=path27.posix.join(targetDirectory,logicalSourceRelativePath);if(entry.isSymbolicLink()){planArtifact({content:readlinkSync4(absolutePath),encoding:"symlink",kind:"skill",path:relativePath,source});continue}if(!entry.isFile()){continue}const bytes=readFileSync12(absolutePath);let content;try{content=preserveBytes||bytes.includes(0)?undefined:new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{content=undefined}planArtifact({content:content??bytes.toString("base64"),encoding:content===undefined?"base64":"utf-8",kind:"skill",mode:fileMode(lstatSync6(absolutePath).mode),path:relativePath,source})}};visit2(sourceDirectory)};const selectedSkillIds=skillIdsForContextPlan(contextPlan);const additionalSkillIds=new Set(additionalSkillSelection?.skillIds);const baselineSkillIds=new Set(baseline.skills.map(({id})=>id));const referencedProjectLocalSkillIds=uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.flatMap((contribution2)=>contribution2.kind==="subagent-template"?contribution2.references.filter((skillId)=>!baselineSkillIds.has(skillId)):[])));const projectLocalSkillIds=new Set(planOnly?[]:projectLocalSkillMetadata({baseline,scanDirectory,skillIds:referencedProjectLocalSkillIds}).map(({id})=>id));const finalSkills=uniqueSorted2(planOnly?[...selectedSkillIds.filter((skillId)=>baselineSkillIds.has(skillId)),...additionalSkillIds]:[...selectedSkillIds,...projectLocalSkillIds,...additionalSkillIds]);const hasOxfmt=detectionHasPackage(detection,"oxfmt");const hasPython=detection.detectedLanguages.includes("python");const finalHookIds=new Set(scopeForWorkspacePath(contextPlan,".").contributions.filter(({kind})=>kind==="lifecycle-hook").map(({identity:identity3})=>identity3.id).filter((hookId)=>hookId!=="format-edited-file"||hasOxfmt||hasPython));const lintAssets=resolveLintAssetsForPacks(finalPacks,baseline);const appliedLintConfigs=writeAppliedLintConfigs({...plannedPackageDocuments===undefined?{}:{plannedPackageDocuments},...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},allowRequiredDevDependencyMigration:suppliedDesiredState!==undefined,baseline,contextPlan,detection,generatedFiles,outputDirectory,planArtifact,planOnly,plannedDependencies,plannedStructuredEntries,scanDirectory});const rootOxlintConfigFiles=uniqueSorted2([...existingProjectOwnedOxlintConfigFiles(scanDirectory),...appliedLintConfigs.filter(({workspace})=>workspace===".").map(({configFile})=>configFile)]);const lintAssetIdsByPack=selectedLintAssetIdsByPack(finalPacks,lintAssets);const hasExistingRootOxlintConfig=rootOxlintConfigFiles.length>0;const lintStarterConfigFile=hasExistingRootOxlintConfig?null:".devpunks/specs/lint/oxlint-starter.json";const promptTargets=suppliedContextPlan===undefined?promptTargetsForDetection(scanDirectory,detection,additionalPromptTargets,!planOnly):promptTargetsForContextPlan(contextPlan);const promptSpecs=promptTargets.map((target)=>buildPromptSpec({forceGenerated:planOnly,packs:packsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),primarySkills:primarySkillsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),relativePath:target.relativePath,scanDirectory}));const opensrcReferences=collectOpensrcReferences(promptSpecs);const sourceGuides=sourceGuidesForSelection({detectedTechnologies:detection.detectedTechnologies,finalPacks});const sourceGuideSummaries=sourceGuides.map(summarizeSourceGuide);const contextPlanFile=".devpunks/context-plan.json";const planPromptAndLintArtifacts=()=>{if(persistContextPlan){generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(encodeContextPlan2(contextPlan)),kind:"context-plan",path:contextPlanFile,source:"context-plan"})))}generatedFiles.push(planArtifact({path:".agents/AGENTS.md",obligation:{contentAuthority:"scaffold",dependencies:[baseline.summary.digest,sharedPrompt.capability.sha256],presence:"required",producer:"baseline/sharedPrompt/v1",validity:"managed-bytes"},sharedPromptIdentity:{baselineDigest:baseline.summary.digest,baselineVersion:baseline.summary.resolvedVersion,capabilityVersion:1,templateDigest:sharedPrompt.capability.sha256},content:sharedPrompt.content,kind:"agent-prompt",source:"prompt"}));promptOutputs.push(".agents/AGENTS.md");const additionalPromptTargetByPath=new Map(additionalPromptTargets.map((target)=>[target.relativePath,target]));additionalPromptTargetByPath.delete(".agents/AGENTS.md");for(const[promptTarget,{seedContent}]of[...additionalPromptTargetByPath].toSorted(([left],[right])=>left.localeCompare(right))){const promptSpec=promptSpecs.find(({targetFile})=>targetFile===promptTarget);if(promptSpec===undefined){continue}generatedFiles.push(planArtifact(orderedPlanArtifact({content:resolvePromptContent({preserveExistingManagedFiles:shouldPreserveExistingManagedFiles,promptSpec,relativePath:promptTarget,scanDirectory,...seedContent===undefined?{}:{seedContent}}),kind:"agent-prompt",path:promptTarget,source:"prompt"})));promptOutputs.push(promptTarget)}for(const promptSpec of promptSpecs){generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderPromptSpecMarkdown(promptSpec),kind:"prompt-spec",path:promptSpec.specFile,source:"prompt"})));promptSpecFiles.push(promptSpec.specFile)}const readmeFile="opensrc/README.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSourceGuideReadme(sourceGuides),kind:"source-guide",path:readmeFile,source:"source-guide"})));sourceGuideFiles.push(readmeFile);for(const guide of sourceGuides){const guideFile=sourceGuideFile(guide);generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSourceGuide(guide),kind:"source-guide",path:guideFile,source:"source-guide"})));sourceGuideFiles.push(guideFile)}if(lintAssets.length>0){const lintAssetsFile=".devpunks/specs/lint/assets.json";generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(lintAssets),kind:"lint-spec",path:lintAssetsFile,source:"lint"})));lintSpecFiles.push(lintAssetsFile);const lintSelectionFile=".devpunks/specs/lint/selection.json";generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(Object.fromEntries([["finalPacks",finalPacks],["selectedAssetIds",lintAssets.map((asset)=>asset.id)],["selectedAssetsByPack",lintAssetIdsByPack],["requiredDevDependencies",uniqueSorted2([...Object.keys(lintToolchainVersions),...lintAssets.flatMap((asset)=>asset.requiredDevDependencies)])],["existingRootOxlintConfigFiles",rootOxlintConfigFiles],["starterConfigFile",lintStarterConfigFile],["ultraciteCorePreset","ultracite/oxlint/core"],["appliedLintConfigs",appliedLintConfigs]])),kind:"lint-spec",path:lintSelectionFile,source:"lint"})));lintSpecFiles.push(lintSelectionFile);const lintReadmeFile=".devpunks/specs/lint/README.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderLintSpecMarkdown({hasExistingOxlintConfig:hasExistingRootOxlintConfig,lintAssets,starterConfigFile:lintStarterConfigFile}),kind:"lint-spec",path:lintReadmeFile,source:"lint"})));lintSpecFiles.push(lintReadmeFile);if(lintStarterConfigFile!==null){generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(oxlintStarterConfig),kind:"lint-spec",path:lintStarterConfigFile,source:"lint"})));lintSpecFiles.push(lintStarterConfigFile)}}};planPromptAndLintArtifacts();const resolveSkillSource=(skillId)=>{if(!additionalSkillIds.has(skillId)){return{baseline,sourceDirectory:baseline.skills.find(({id})=>id===skillId)?.sourceDirectory}}const selectedBaseline=additionalSkillSelection?.baseline;const selectedSkill=selectedBaseline===undefined?undefined:skillRegistryByIdForBaseline(selectedBaseline)[skillId];if(selectedBaseline!==undefined&&selectedSkill!==undefined){return{baseline:selectedBaseline,sourceDirectory:selectedSkill.sourceDirectory}}return{baseline:bundledBaseline,sourceDirectory:skillRegistryByIdForBaseline(bundledBaseline)[skillId]?.sourceDirectory}};const planSkillArtifacts=()=>{for(const skillId of finalSkills){const skillSource=resolveSkillSource(skillId);const baselineSourceDirectory=skillSource.sourceDirectory;if(baselineSourceDirectory===undefined&&!projectLocalSkillIds.has(skillId)){throw new Error(`Unknown scaffold skill: ${skillId}`)}const targetDirectory=path27.posix.join(".agents/skills",skillId);const absoluteTargetDirectory=path27.join(outputDirectory,targetDirectory);const absoluteSourceDirectory=baselineSourceDirectory===undefined?path27.join(scanDirectory,targetDirectory):resolveBaselinePath({baselineRoot:skillSource.baseline.root,baselineSkillsRoot:skillSource.baseline.skillsRoot,relativePath:baselineSourceDirectory});const materializesSkill=path27.resolve(absoluteSourceDirectory)!==path27.resolve(absoluteTargetDirectory);if(materializesSkill){plannedDirectoriesToReset.push(targetDirectory)}planDirectory({source:baselineSourceDirectory===undefined?"project-local-skill":"baseline",sourceBaseline:skillSource.baseline,sourceDirectory:absoluteSourceDirectory,targetDirectory});if(skillId==="verify-behavior"){const referencesTarget=path27.posix.join(targetDirectory,"references");const referencesSource=path27.join(scanDirectory,referencesTarget);if(existsSync10(referencesSource)){const relativeReferences=path27.relative(realpathSync6(scanDirectory),realpathSync6(referencesSource));if(!lstatSync6(referencesSource).isDirectory()||relativeReferences===".."||relativeReferences.startsWith(`..${path27.sep}`)||path27.isAbsolute(relativeReferences)){throw new Error("Project Verifier references must be a repository-contained directory.")}planDirectory({preserveBytes:true,source:"project-local-skill",sourceBaseline:baseline,sourceDirectory:referencesSource,targetDirectory:referencesTarget})}}if(baselineSourceDirectory!==undefined){generatedFiles.push(targetDirectory)}skillFiles.push(targetDirectory)}};planSkillArtifacts();const projectionScriptFiles=["sync-subagents.mjs","harness-projection/core.mjs","harness-projection/apply.mjs",...existsSync10(path27.join(baseline.dataRoot,"scripts/harness-projection/authoring.mjs"))?["harness-projection/authoring.mjs"]:[],"harness-projection/adapters/claude.mjs","harness-projection/adapters/codex.mjs","harness-projection/adapters/cursor.mjs","harness-projection/adapters/opencode.mjs"].map((relativePath)=>`.agents/scripts/${relativePath}`);for(const scriptFile of projectionScriptFiles){const sourcePath=scriptFile.slice(".agents/scripts/".length);const content=readBaselineDataFile(baseline.dataRoot,"scripts",...sourcePath.split("/"));generatedFiles.push(planArtifact({content,kind:"script",path:scriptFile,source:"baseline"}));scriptFiles.push(scriptFile)}const syncScriptFile=".agents/scripts/sync-subagents.mjs";const planSubagentArtifacts=()=>{const useCompiledSubagentAuthority=planOnly||suppliedDesiredState!==undefined;const compiledSubagentTemplates=useCompiledSubagentAuthority?contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="subagent-template")):[];const compiledSubagentScopes=useCompiledSubagentAuthority?contextPlan.scopes.flatMap((scope3)=>{if(scope3.id==="root"||scope3.id==="shared"||scope3.id===".agents"){return[]}const specialistId=specialistIdForPath(scope3.id);const template=compiledSubagentTemplates.find(({identity:identity3})=>identity3.id===specialistId);return template===undefined?[]:[{scope:scope3,template}]}):[];const subagentWorkspaces=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3})=>scope3.id):detectedWorkspaces(scanDirectory,detection);const manifestPromptPath=".agents/subagents/manifest.prompt.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSubagentManifestPrompt({finalPacks,workspaces:subagentWorkspaces}),kind:"subagent",path:manifestPromptPath,source:"subagent"})));subagentFiles.push(manifestPromptPath);const subagentPromptSpecs=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3,template})=>buildPromptSpec({forceGenerated:true,packs:scope3.packs.map(({id})=>id),primarySkills:template.references,relativePath:path27.posix.join(scope3.id,"AGENTS.md"),scanDirectory})):promptSpecs;const manifestSpec=buildSubagentManifestSpec({detection,finalPacks,promptSpecs:subagentPromptSpecs,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(manifestSpec),kind:"subagent",path:manifestSpec.specFile,source:"subagent"})));subagentFiles.push(manifestSpec.specFile);const renderedSubagentManifest=subagentManifestSource({baseline,detection,finalPacks,preserveExisting:true,promptSpecs:subagentPromptSpecs,scanDirectory,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});assertSubagentManifestMatchesContext(contextPlan,decodeSubagentManifestModule(renderedSubagentManifest));generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderedSubagentManifest,kind:"subagent",path:".agents/subagents/manifest.mjs",source:"subagent"})));subagentFiles.push(".agents/subagents/manifest.mjs");return manifestSpec};const subagentManifestSpec=planSubagentArtifacts();for(const hook of hookRegistryForBaseline(baseline).filter((entry)=>finalHookIds.has(entry.id))){generatedFiles.push(planArtifact({content:readBaselineDataFile(baseline.dataRoot,...hook.sourcePath.split("/")),kind:"hook",path:hook.outputPath,source:"baseline"}));hookFiles.push(hook.outputPath)}const gatePlan=planCommitGateOutput({baseline,contextPlan,detection,generatedFiles,planArtifact,planOnly,plannedDependencies,plannedFiles,scanDirectory,...settings===undefined?{}:{settings}});const previousHandoff=priorHandoffAuthority(scanDirectory);const handoffContent=(proofs)=>{const scopedAuthoringActions=assessScopedAuthoring({contextPlan,proofs});return scopedAuthoringActions.length===0&&previousHandoff.content!==undefined&&!previousHandoff.content.includes("## Commit Gate Post-Command Handoff")&&!gatePlan.action.startsWith("defer")?previousHandoff.content:renderAgentHandoffMarkdown({...gatePlan.action.startsWith("defer")&&gatePlan.handoff!==null?{commitGateHandoff:gatePlan.handoff}:{},detectedTechnologies:detection.detectedTechnologies,finalPacks,harnessFiles:harnessFiles.toSorted(),hookFiles:hookFiles.toSorted(),lintSpecFiles:lintSpecFiles.toSorted(),monorepo:detection.monorepo,opensrcReferences,outputDirectory:renderedOutputDirectory,promptOutputs:promptOutputs.toSorted(),promptSpecFiles:promptSpecFiles.toSorted(),repoShapeMode,scaffoldManifestFile:".devpunks/scaffold-manifest.json",scopedAuthoringActions,scriptFiles:scriptFiles.toSorted(),skillFiles:skillFiles.toSorted(),sourceGuideFiles:sourceGuideFiles.toSorted(),subagentFiles:subagentFiles.toSorted(),toolBootstrapStatuses})};const handoffIndex=plannedFiles.length;generatedFiles.push(planArtifact({content:handoffContent(previousHandoff.proofs),kind:"handoff",path:agentHandoffFile,source:"scaffold-handoff"}));const buildDesiredOutputInput=()=>({baseline:{catalogRevision:baselineSummary2.version,provenance:baselineSummary2},contextPlan,dependencies:plannedDependencies,files:plannedFiles,projections:[claudeAdapter,codexAdapter,cursorAdapter,openCodeAdapter].map((adapter)=>({matrix:adapter.matrix,result:project({adapter,contextPlan})})),...settings===undefined?{}:{settings},structuredEntries:[...plannedStructuredEntries,...settings===undefined?[]:[{file:".devpunks/settings.json",kind:"field",path:["requiredTools"],source:"project-settings",value:[...settings.requiredTools]}]]});const desiredOutputInput=buildDesiredOutputInput();if(planOnly){return desiredOutputInput}const desiredReceiptState=(()=>{if(suppliedDesiredState!==undefined){return suppliedDesiredState}const desiredOutput=compileDesiredOutput(desiredOutputInput);if(desiredOutput._tag==="DesiredScaffoldStateCompilationFailure"){throw new Error(desiredOutput.errors.map(({message})=>message).join(`
2491
+ `,path:gateMerge.path},{content:readBaselineDataFile(baseline.dataRoot,"scripts/commit-gate-runner.mjs"),path:".agents/scripts/commit-gate-runner.mjs"},{content:encodePrettyJson2(gateConsumers.map(({contribution:contribution2,path:consumerPath})=>({...contribution2.contract,owner:contribution2.identity.id,path:consumerPath}))),path:".devpunks/commit-gate-contracts.json"}]){generatedFiles.push(planArtifact({...file5,kind:"harness",source:"baseline"}))}if(!planOnly){const packageFile=plannedFiles.find((file5)=>file5.path===gateOwnerManifest);const packageInput=packageFile===undefined?readJsonRecord(path27.join(scanDirectory,gateOwnerManifest)):JSON.parse(packageFile.content);if(!isRecord8(packageInput)){throw new Error("Commit Gate package manifest must be a JSON object.")}const packageJson=packageInput;const patched=encodePrettyJson2({...packageJson,devDependencies:{...isRecord8(packageJson.devDependencies)?packageJson.devDependencies:{},lefthook:"2.1.10"}});if(packageFile!==undefined){plannedFiles.splice(plannedFiles.indexOf(packageFile),1)}planArtifact({content:patched,kind:"harness",path:gateOwnerManifest,source:"lint"})}}return gatePlan};var selectedLintAssetIdsByPack=(finalPacks,lintAssets)=>{const lintAssetIdsByPack={};for(const packId of finalPacks){const assetIds=lintAssets.filter((asset)=>asset.sourcePacks.includes(packId)).map((asset)=>asset.id);if(assetIds.length>0){lintAssetIdsByPack[packId]=assetIds}}return lintAssetIdsByPack};function runScaffoldOutputPipeline({plannedPackageDocuments,priorManagedDependencies,priorManagedStructuredEntries,scanDirectory,detection,additionalPromptTargets=[],additionalSkillSelection,contextPlan:suppliedContextPlan,finalPacks:suppliedFinalPacks,outputDirectory,repoShapeMode,toolBootstrapStatuses=[],preserveExistingManagedFiles,displayOutputDirectory,baseline=bundledBaseline,baselineOrigin=baseline.summary.authoritySource==="bundled"?"bundled":"resolved",compileDesiredOutput=compileDesiredScaffoldOutput,desiredState:suppliedDesiredState,settings,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2,filesystemSession:suppliedFilesystemSession,planOnly=false,returnPlanOnly=false}){return gen2(function*executeScaffoldOutputPipeline(){const sharedPrompt=yield*readSharedPrompt(baseline);const baselineSummary2=structuredClone(baseline.summary);if(suppliedContextPlan===undefined&&suppliedFinalPacks===undefined){const message="Scaffold output requires a compiled context plan or legacy pack selection";return yield*new ContextPlanCompilationFailure({cause:new Error(message),message,operation:"compile-context-plan"})}const compiledContextPlan=suppliedContextPlan??(yield*compileScaffoldContextPlan({additionalPromptTargets,baseline,detection,finalPacks:suppliedFinalPacks??[],preserveExistingSubagentManifest:preserveExistingManagedFiles??true,scanDirectory}));const materializePipeline=async()=>{const contextPlan=compiledContextPlan;const persistContextPlan=suppliedContextPlan!==undefined;const finalPacks=packsForWorkspace(contextPlan,".");const shouldPreserveExistingManagedFiles=preserveExistingManagedFiles??true;const renderedOutputDirectory=displayOutputDirectory??outputDirectory;const generatedFiles=[];const promptOutputs=[];const promptSpecFiles=[];const lintSpecFiles=[];const sourceGuideFiles=[];const skillFiles=[];const subagentFiles=[];const scriptFiles=[];const hookFiles=[];const harnessFiles=[];const plannedFiles=[];const plannedDependencies=[];const plannedStructuredEntries=[];const plannedDirectoriesToReset=[];const planArtifact=(file5)=>{plannedFiles.push({...file5,obligation:file5.obligation??producerObligation(file5.source,[file5.revision??baseline.summary.resolvedVersion])});return file5.path};const originForBaseline=(sourceBaseline)=>{if(sourceBaseline===baseline){return baselineOrigin}if(sourceBaseline===additionalSkillSelection?.baseline&&additionalSkillSelection.baselineOrigin!==undefined){return additionalSkillSelection.baselineOrigin}return sourceBaseline.summary.authoritySource==="bundled"?"bundled":"resolved"};const planDirectory=({sourceBaseline,sourceDirectory,targetDirectory,source,preserveBytes=false})=>{const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){const absolutePath=path27.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const sourceRelativePath=relativePosixPath(sourceDirectory,absolutePath);if(targetDirectory===".agents/skills/verify-behavior"&&source==="baseline"&&sourceRelativePath.startsWith("references/")&&existsSync10(path27.join(scanDirectory,targetDirectory,sourceRelativePath))){continue}const baselineRelativePath=relativePosixPath(sourceBaseline.skillsRoot,absolutePath);const logicalBaselineRelativePath=originForBaseline(sourceBaseline)==="bundled"?logicalBundledSkillRelativePath(baselineRelativePath):baselineRelativePath;const logicalSourceRelativePath=logicalBaselineRelativePath===baselineRelativePath?sourceRelativePath:path27.posix.relative(relativePosixPath(sourceBaseline.skillsRoot,sourceDirectory),logicalBaselineRelativePath);const relativePath=path27.posix.join(targetDirectory,logicalSourceRelativePath);if(entry.isSymbolicLink()){planArtifact({content:readlinkSync4(absolutePath),encoding:"symlink",kind:"skill",path:relativePath,source});continue}if(!entry.isFile()){continue}const bytes=readFileSync12(absolutePath);let content;try{content=preserveBytes||bytes.includes(0)?undefined:new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{content=undefined}planArtifact({content:content??bytes.toString("base64"),encoding:content===undefined?"base64":"utf-8",kind:"skill",mode:fileMode(lstatSync6(absolutePath).mode),path:relativePath,source})}};visit2(sourceDirectory)};const selectedSkillIds=skillIdsForContextPlan(contextPlan);const additionalSkillIds=new Set(additionalSkillSelection?.skillIds);const baselineSkillIds=new Set(baseline.skills.map(({id})=>id));const referencedProjectLocalSkillIds=uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.flatMap((contribution2)=>contribution2.kind==="subagent-template"?contribution2.references.filter((skillId)=>!baselineSkillIds.has(skillId)):[])));const projectLocalSkillIds=new Set(planOnly?[]:projectLocalSkillMetadata({baseline,scanDirectory,skillIds:referencedProjectLocalSkillIds}).map(({id})=>id));const finalSkills=uniqueSorted2(planOnly?[...selectedSkillIds.filter((skillId)=>baselineSkillIds.has(skillId)),...additionalSkillIds]:[...selectedSkillIds,...projectLocalSkillIds,...additionalSkillIds]);const hasOxfmt=detectionHasPackage(detection,"oxfmt");const hasPython=detection.detectedLanguages.includes("python");const finalHookIds=new Set(scopeForWorkspacePath(contextPlan,".").contributions.filter(({kind})=>kind==="lifecycle-hook").map(({identity:identity3})=>identity3.id).filter((hookId)=>hookId!=="format-edited-file"||hasOxfmt||hasPython));const lintAssets=resolveLintAssetsForPacks(finalPacks,baseline);const appliedLintConfigs=writeAppliedLintConfigs({...plannedPackageDocuments===undefined?{}:{plannedPackageDocuments},...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},allowRequiredDevDependencyMigration:suppliedDesiredState!==undefined,baseline,contextPlan,detection,generatedFiles,outputDirectory,planArtifact,planOnly,plannedDependencies,plannedStructuredEntries,scanDirectory});const rootOxlintConfigFiles=uniqueSorted2([...existingProjectOwnedOxlintConfigFiles(scanDirectory),...appliedLintConfigs.filter(({workspace})=>workspace===".").map(({configFile})=>configFile)]);const lintAssetIdsByPack=selectedLintAssetIdsByPack(finalPacks,lintAssets);const hasExistingRootOxlintConfig=rootOxlintConfigFiles.length>0;const lintStarterConfigFile=hasExistingRootOxlintConfig?null:".devpunks/specs/lint/oxlint-starter.json";const promptTargets=suppliedContextPlan===undefined?promptTargetsForDetection(scanDirectory,detection,additionalPromptTargets,!planOnly):promptTargetsForContextPlan(contextPlan);const promptSpecs=promptTargets.map((target)=>buildPromptSpec({forceGenerated:planOnly,packs:packsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),primarySkills:primarySkillsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),relativePath:target.relativePath,scanDirectory}));const opensrcReferences=collectOpensrcReferences(promptSpecs);const sourceGuides=sourceGuidesForSelection({detectedTechnologies:detection.detectedTechnologies,finalPacks});const sourceGuideSummaries=sourceGuides.map(summarizeSourceGuide);const contextPlanFile=".devpunks/context-plan.json";const planPromptAndLintArtifacts=()=>{if(persistContextPlan){generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(encodeContextPlan2(contextPlan)),kind:"context-plan",path:contextPlanFile,source:"context-plan"})))}generatedFiles.push(planArtifact({path:".agents/AGENTS.md",obligation:{contentAuthority:"scaffold",dependencies:[baseline.summary.digest,sharedPrompt.capability.sha256],presence:"required",producer:"baseline/sharedPrompt/v1",validity:"managed-bytes"},sharedPromptIdentity:{baselineDigest:baseline.summary.digest,baselineVersion:baseline.summary.resolvedVersion,capabilityVersion:1,templateDigest:sharedPrompt.capability.sha256},content:sharedPrompt.content,kind:"agent-prompt",source:"prompt"}));promptOutputs.push(".agents/AGENTS.md");const additionalPromptTargetByPath=new Map(additionalPromptTargets.map((target)=>[target.relativePath,target]));additionalPromptTargetByPath.delete(".agents/AGENTS.md");for(const[promptTarget,{seedContent}]of[...additionalPromptTargetByPath].toSorted(([left],[right])=>left.localeCompare(right))){const promptSpec=promptSpecs.find(({targetFile})=>targetFile===promptTarget);if(promptSpec===undefined){continue}generatedFiles.push(planArtifact(orderedPlanArtifact({content:resolvePromptContent({preserveExistingManagedFiles:shouldPreserveExistingManagedFiles,promptSpec,relativePath:promptTarget,scanDirectory,...seedContent===undefined?{}:{seedContent}}),kind:"agent-prompt",path:promptTarget,source:"prompt"})));promptOutputs.push(promptTarget)}for(const promptSpec of promptSpecs){generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderPromptSpecMarkdown(promptSpec),kind:"prompt-spec",path:promptSpec.specFile,source:"prompt"})));promptSpecFiles.push(promptSpec.specFile)}const readmeFile="opensrc/README.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSourceGuideReadme(sourceGuides),kind:"source-guide",path:readmeFile,source:"source-guide"})));sourceGuideFiles.push(readmeFile);for(const guide of sourceGuides){const guideFile=sourceGuideFile(guide);generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSourceGuide(guide),kind:"source-guide",path:guideFile,source:"source-guide"})));sourceGuideFiles.push(guideFile)}if(lintAssets.length>0){const lintAssetsFile=".devpunks/specs/lint/assets.json";generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(lintAssets),kind:"lint-spec",path:lintAssetsFile,source:"lint"})));lintSpecFiles.push(lintAssetsFile);const lintSelectionFile=".devpunks/specs/lint/selection.json";generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(Object.fromEntries([["finalPacks",finalPacks],["selectedAssetIds",lintAssets.map((asset)=>asset.id)],["selectedAssetsByPack",lintAssetIdsByPack],["requiredDevDependencies",uniqueSorted2([...Object.keys(lintToolchainVersions),...lintAssets.flatMap((asset)=>asset.requiredDevDependencies)])],["existingRootOxlintConfigFiles",rootOxlintConfigFiles],["starterConfigFile",lintStarterConfigFile],["ultraciteCorePreset","ultracite/oxlint/core"],["appliedLintConfigs",appliedLintConfigs]])),kind:"lint-spec",path:lintSelectionFile,source:"lint"})));lintSpecFiles.push(lintSelectionFile);const lintReadmeFile=".devpunks/specs/lint/README.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderLintSpecMarkdown({hasExistingOxlintConfig:hasExistingRootOxlintConfig,lintAssets,starterConfigFile:lintStarterConfigFile}),kind:"lint-spec",path:lintReadmeFile,source:"lint"})));lintSpecFiles.push(lintReadmeFile);if(lintStarterConfigFile!==null){generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(oxlintStarterConfig),kind:"lint-spec",path:lintStarterConfigFile,source:"lint"})));lintSpecFiles.push(lintStarterConfigFile)}}};planPromptAndLintArtifacts();const resolveSkillSource=(skillId)=>{if(!additionalSkillIds.has(skillId)){return{baseline,sourceDirectory:baseline.skills.find(({id})=>id===skillId)?.sourceDirectory}}const selectedBaseline=additionalSkillSelection?.baseline;const selectedSkill=selectedBaseline===undefined?undefined:skillRegistryByIdForBaseline(selectedBaseline)[skillId];if(selectedBaseline!==undefined&&selectedSkill!==undefined){return{baseline:selectedBaseline,sourceDirectory:selectedSkill.sourceDirectory}}return{baseline:bundledBaseline,sourceDirectory:skillRegistryByIdForBaseline(bundledBaseline)[skillId]?.sourceDirectory}};const planSkillArtifacts=()=>{for(const skillId of finalSkills){const skillSource=resolveSkillSource(skillId);const baselineSourceDirectory=skillSource.sourceDirectory;if(baselineSourceDirectory===undefined&&!projectLocalSkillIds.has(skillId)){throw new Error(`Unknown scaffold skill: ${skillId}`)}const targetDirectory=path27.posix.join(".agents/skills",skillId);const absoluteTargetDirectory=path27.join(outputDirectory,targetDirectory);const absoluteSourceDirectory=baselineSourceDirectory===undefined?path27.join(scanDirectory,targetDirectory):resolveBaselinePath({baselineRoot:skillSource.baseline.root,baselineSkillsRoot:skillSource.baseline.skillsRoot,relativePath:baselineSourceDirectory});const materializesSkill=path27.resolve(absoluteSourceDirectory)!==path27.resolve(absoluteTargetDirectory);if(materializesSkill){plannedDirectoriesToReset.push(targetDirectory)}planDirectory({source:baselineSourceDirectory===undefined?"project-local-skill":"baseline",sourceBaseline:skillSource.baseline,sourceDirectory:absoluteSourceDirectory,targetDirectory});if(skillId==="verify-behavior"){const referencesTarget=path27.posix.join(targetDirectory,"references");const referencesSource=path27.join(scanDirectory,referencesTarget);if(existsSync10(referencesSource)){const relativeReferences=path27.relative(realpathSync6(scanDirectory),realpathSync6(referencesSource));if(!lstatSync6(referencesSource).isDirectory()||relativeReferences===".."||relativeReferences.startsWith(`..${path27.sep}`)||path27.isAbsolute(relativeReferences)){throw new Error("Project Verifier references must be a repository-contained directory.")}planDirectory({preserveBytes:true,source:"project-local-skill",sourceBaseline:baseline,sourceDirectory:referencesSource,targetDirectory:referencesTarget})}}if(baselineSourceDirectory!==undefined){generatedFiles.push(targetDirectory)}skillFiles.push(targetDirectory)}};planSkillArtifacts();const projectionScriptFiles=["sync-subagents.mjs","harness-projection/core.mjs","harness-projection/apply.mjs",...existsSync10(path27.join(baseline.dataRoot,"scripts/harness-projection/authoring.mjs"))?["harness-projection/authoring.mjs"]:[],"harness-projection/adapters/claude.mjs","harness-projection/adapters/codex.mjs","harness-projection/adapters/cursor.mjs","harness-projection/adapters/opencode.mjs"].map((relativePath)=>`.agents/scripts/${relativePath}`);for(const scriptFile of projectionScriptFiles){const sourcePath=scriptFile.slice(".agents/scripts/".length);const content=readBaselineDataFile(baseline.dataRoot,"scripts",...sourcePath.split("/"));generatedFiles.push(planArtifact({content,kind:"script",path:scriptFile,source:"baseline"}));scriptFiles.push(scriptFile)}const syncScriptFile=".agents/scripts/sync-subagents.mjs";const planSubagentArtifacts=()=>{const useCompiledSubagentAuthority=planOnly||suppliedDesiredState!==undefined;const compiledSubagentTemplates=useCompiledSubagentAuthority?contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="subagent-template")):[];const compiledSubagentScopes=useCompiledSubagentAuthority?contextPlan.scopes.flatMap((scope3)=>{if(scope3.id==="root"||scope3.id==="shared"||scope3.id===".agents"){return[]}const specialistId=specialistIdForPath(scope3.id);const template=compiledSubagentTemplates.find(({identity:identity3})=>identity3.id===specialistId);return template===undefined?[]:[{scope:scope3,template}]}):[];const subagentWorkspaces=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3})=>scope3.id):detectedWorkspaces(scanDirectory,detection);const manifestPromptPath=".agents/subagents/manifest.prompt.md";generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderSubagentManifestPrompt({finalPacks,workspaces:subagentWorkspaces}),kind:"subagent",path:manifestPromptPath,source:"subagent"})));subagentFiles.push(manifestPromptPath);const subagentPromptSpecs=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3,template})=>buildPromptSpec({forceGenerated:true,packs:scope3.packs.map(({id})=>id),primarySkills:template.references,relativePath:path27.posix.join(scope3.id,"AGENTS.md"),scanDirectory})):promptSpecs;const manifestSpec=buildSubagentManifestSpec({detection,finalPacks,promptSpecs:subagentPromptSpecs,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});generatedFiles.push(planArtifact(orderedPlanArtifact({content:encodePrettyJson2(manifestSpec),kind:"subagent",path:manifestSpec.specFile,source:"subagent"})));subagentFiles.push(manifestSpec.specFile);const renderedSubagentManifest=subagentManifestSource({baseline,detection,finalPacks,preserveExisting:true,promptSpecs:subagentPromptSpecs,scanDirectory,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});assertSubagentManifestMatchesContext(contextPlan,decodeSubagentManifestModule(renderedSubagentManifest));generatedFiles.push(planArtifact(orderedPlanArtifact({content:renderedSubagentManifest,kind:"subagent",path:".agents/subagents/manifest.mjs",source:"subagent"})));subagentFiles.push(".agents/subagents/manifest.mjs");return manifestSpec};const subagentManifestSpec=planSubagentArtifacts();for(const hook of hookRegistryForBaseline(baseline).filter((entry)=>finalHookIds.has(entry.id))){generatedFiles.push(planArtifact({content:readBaselineDataFile(baseline.dataRoot,...hook.sourcePath.split("/")),kind:"hook",path:hook.outputPath,source:"baseline"}));hookFiles.push(hook.outputPath)}const gatePlan=planCommitGateOutput({baseline,contextPlan,detection,generatedFiles,planArtifact,planOnly,plannedDependencies,plannedFiles,scanDirectory,...settings===undefined?{}:{settings}});const handoffContent=(proofs)=>{const scopedAuthoringActions=assessScopedAuthoring({contextPlan,proofs});return renderAgentHandoffMarkdown({...gatePlan.action.startsWith("defer")&&gatePlan.handoff!==null?{commitGateHandoff:gatePlan.handoff}:{},detectedTechnologies:detection.detectedTechnologies,finalPacks,harnessFiles:harnessFiles.toSorted(),hookFiles:hookFiles.toSorted(),lintSpecFiles:lintSpecFiles.toSorted(),monorepo:detection.monorepo,opensrcReferences,outputDirectory:renderedOutputDirectory,promptOutputs:promptOutputs.toSorted(),promptSpecFiles:promptSpecFiles.toSorted(),repoShapeMode,scaffoldManifestFile:".devpunks/scaffold-manifest.json",scopedAuthoringActions,scriptFiles:scriptFiles.toSorted(),skillFiles:skillFiles.toSorted(),sourceGuideFiles:sourceGuideFiles.toSorted(),subagentFiles:subagentFiles.toSorted(),toolBootstrapStatuses})};const handoffIndex=plannedFiles.length;generatedFiles.push(planArtifact({content:handoffContent(readVerifiedAuthoringProofs(scanDirectory)),kind:"handoff",path:agentHandoffFile,source:"scaffold-handoff"}));const buildDesiredOutputInput=()=>({baseline:{catalogRevision:baselineSummary2.version,provenance:baselineSummary2},contextPlan,dependencies:plannedDependencies,files:plannedFiles,projections:[claudeAdapter,codexAdapter,cursorAdapter,openCodeAdapter].map((adapter)=>({matrix:adapter.matrix,result:project({adapter,contextPlan})})),...settings===undefined?{}:{settings},structuredEntries:[...plannedStructuredEntries,...settings===undefined?[]:[{file:".devpunks/settings.json",kind:"field",path:["requiredTools"],source:"project-settings",value:[...settings.requiredTools]}]]});const desiredOutputInput=buildDesiredOutputInput();if(planOnly){return desiredOutputInput}const desiredReceiptState=(()=>{if(suppliedDesiredState!==undefined){return suppliedDesiredState}const desiredOutput=compileDesiredOutput(desiredOutputInput);if(desiredOutput._tag==="DesiredScaffoldStateCompilationFailure"){throw new Error(desiredOutput.errors.map(({message})=>message).join(`
2492
2492
  `))}return Object.freeze(desiredOutput._tag==="DesiredScaffoldOutputCompiled"?desiredOutput.catalog:desiredOutput.state)})();const manageOxlintCatalogReceipt=(()=>{const desiredEntry=desiredReceiptState.structuredEntries.find(isOxlintCatalogStructuredEntry);if(desiredEntry===undefined){return false}const packageJsonPath=path27.join(outputDirectory,desiredEntry.file);if(!existsSync10(packageJsonPath)){return true}const packageJson=readJsonRecord(packageJsonPath);if(!hasStructuredValue(packageJson,desiredEntry.path)){return true}const manifestPath=path27.join(outputDirectory,".devpunks/scaffold-manifest.json");if(!existsSync10(manifestPath)){return false}const priorEntries=readJsonRecord(manifestPath).managedStructuredEntries;return Array.isArray(priorEntries)&&priorEntries.some(isOxlintCatalogStructuredEntry)})();const staticResult=Object.freeze({appliedLintConfigs,baseline:baselineSummary2,contextPlan,contextPlanFile,detection,finalPacks:[...finalPacks],generatedFiles:[...generatedFiles],hookFiles:[...hookFiles],lintAssets,lintSpecFiles:[...lintSpecFiles],opensrcReferences,outputDirectory,persistContextPlan,promptOutputs:[...promptOutputs],promptSpecFiles:[...promptSpecFiles],promptSpecs,renderedOutputDirectory,repoShapeMode,scanDirectory,scriptFiles:[...scriptFiles],skillFiles:[...skillFiles],sourceGuideFiles:[...sourceGuideFiles],sourceGuides:sourceGuideSummaries,subagentFiles:[...subagentFiles],subagentManifestSpec,syncScriptFile,toolBootstrapStatuses});const applyPlannedOutput=async({filesystemSession:suppliedPlanFilesystemSession,scriptEnvironment:suppliedPlanScriptEnvironment,scriptRuntimePath:suppliedPlanScriptRuntimePath})=>{let filesystemSession;const materializeDesiredOutput=async()=>{let operationSession;if(suppliedPlanFilesystemSession===undefined){operationSession=await bindConfinedFilesystemSession(outputDirectory)}else{assertConfinedFilesystemSession({outputDirectory,session:suppliedPlanFilesystemSession});operationSession=suppliedPlanFilesystemSession}filesystemSession=operationSession;await snapshotPreExistingSkillHomes(outputDirectory,operationSession);await settleStartedMutations(plannedDirectoriesToReset.map(async(relativeDirectory)=>{const resetDirectory=path27.join(outputDirectory,relativeDirectory);assertConfinedDirectory({directoryPath:resetDirectory,outputDirectory,session:operationSession});await ensureConfinedDirectory({directoryPath:path27.dirname(resetDirectory),outputDirectory,session:operationSession});assertConfinedDirectory({directoryPath:resetDirectory,outputDirectory,session:operationSession});await removeConfinedPath({outputDirectory,recursive:true,session:operationSession,targetPath:resetDirectory})}));await settleStartedMutations(desiredReceiptState.files.map(async(file5)=>await applyDesiredArtifact({content:file5.content,...file5.encoding===undefined?{}:{encoding:file5.encoding},...file5.mode===undefined?{}:{mode:file5.mode},outputDirectory,relativePath:file5.path,session:operationSession})));const oxlintCatalogEntry=desiredReceiptState.structuredEntries.find(isOxlintCatalogStructuredEntry);if(manageOxlintCatalogReceipt&&oxlintCatalogEntry!==undefined&&typeof oxlintCatalogEntry.value==="string"){const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:oxlintCatalogEntry.file,scanDirectory});if(packageJsonPath!==null){await applyDesiredArtifact({content:encodePrettyJson2(patchOxlintCatalog(readJsonRecord(packageJsonPath),oxlintCatalogEntry.value)),outputDirectory,relativePath:oxlintCatalogEntry.file,session:operationSession})}}const projectionPlanDirectory=suppliedDesiredState===undefined?null:mkdtempSync4(path27.join(tmpdir7(),"hi-projection-plan-"));try{const projectionPlanPath=projectionPlanDirectory===null?null:path27.join(projectionPlanDirectory,"plan.json");if(suppliedDesiredState!==undefined&&projectionPlanPath!==null){const appliedContextPlan=decodeUnknownSync(ContextPlan)(JSON.parse(readFileSync12(path27.join(outputDirectory,contextPlanFile),"utf-8")));const refreshedProjections=[claudeAdapter,codexAdapter,cursorAdapter,openCodeAdapter].map((adapter)=>normalizeHarnessProjection({matrix:adapter.matrix,result:project({adapter,contextPlan:appliedContextPlan})})).toSorted((left,right)=>{if(left.matrix.adapter.id===right.matrix.adapter.id){return 0}return left.matrix.adapter.id<right.matrix.adapter.id?-1:1});writeFileSync6(projectionPlanPath,encodePrettyJson2({contextPlanVersion:appliedContextPlan.version,projections:refreshedProjections,version:"1"}))}runJavaScriptFileSync({cwd:outputDirectory,...suppliedPlanScriptEnvironment===undefined?{}:{environment:suppliedPlanScriptEnvironment},environmentOverrides:{DP_HARNESS_PROJECTION_PLAN:projectionPlanPath??undefined},file:path27.join(outputDirectory,syncScriptFile),...suppliedPlanScriptRuntimePath===undefined?{}:{runtimePath:suppliedPlanScriptRuntimePath}})}finally{if(projectionPlanDirectory!==null){rmSync4(projectionPlanDirectory,{force:true,recursive:true})}}};await materializeDesiredOutput();for(const file5 of desiredReceiptState.files.filter(({obligation})=>obligation?.contentAuthority==="scaffold"&&obligation.validity==="managed-bytes")){const absolutePath=path27.join(outputDirectory,file5.path);const stat3=lstatSync6(absolutePath);const symlink3=file5.encoding==="symlink";let expectedContent=file5.content;if(symlink3){expectedContent=`symlink:${file5.content}`}else if(file5.encoding==="base64"){expectedContent=Buffer.from(file5.content,"base64")}const actualContent=stat3.isSymbolicLink()?`symlink:${readlinkSync4(absolutePath)}`:readFileSync12(absolutePath);if(stat3.isSymbolicLink()!==symlink3||!symlink3&&!stat3.isFile()||hashManagedFileContent(file5.path,actualContent)!==hashManagedFileContent(file5.path,expectedContent)||!symlink3&&file5.mode!==undefined&&fileMode(stat3.mode)!==fileMode(file5.mode)){throw new Error(`Scaffold output failed current-state verification: ${file5.path}`)}}const activeFilesystemSession=filesystemSession;if(activeFilesystemSession===undefined){throw new Error("Scaffold filesystem session was not initialized.")}const collectHarnessProjectionFiles=()=>{const projectionReceiptFile2=persistContextPlan?".devpunks/harness-projection-receipt.json":null;const projectionReceipt2=projectionReceiptFile2===null?null:readSuccessfulProjectionReceipt(outputDirectory,projectionReceiptFile2);if(projectionReceiptFile2!==null){generatedFiles.push(projectionReceiptFile2)}harnessFiles.push(...scanDirectory===outputDirectory||projectionReceipt2!==null?[]:collectRelativeFiles(outputDirectory,".").filter((relativePath)=>path27.posix.basename(relativePath)==="CLAUDE.md"),...collectRelativeFiles(outputDirectory,".claude").filter((relativePath)=>projectionReceipt2===null&&scanDirectory!==outputDirectory||path27.posix.basename(relativePath)!=="CLAUDE.md"),...collectRelativeFiles(outputDirectory,".codex"),...collectRelativeFiles(outputDirectory,".cursor"),...collectRelativeFiles(outputDirectory,".opencode"));const claudeProjection=projectionReceipt2?.projections.find(({adapter})=>adapter.id==="claude");const failedClaudeActions=new Set(claudeProjection?.failures.flatMap(({action:action2})=>action2===undefined?[]:[action2]));harnessFiles.push(...claudeProjection?.actions.flatMap((action2)=>{if(action2.operation!=="mirror"||!action2.id.includes(":scoped-prompt:")||action2.target===undefined||failedClaudeActions.has(action2.id)){return[]}const targetPath=path27.resolve(outputDirectory,action2.target);const relativeTarget=path27.relative(outputDirectory,targetPath);if(relativeTarget.startsWith(`..${path27.sep}`)||path27.isAbsolute(relativeTarget)||!existsSync10(targetPath)){return[]}const targetStat=lstatSync6(targetPath);if(!targetStat.isSymbolicLink()){if(action2.source===undefined||!targetStat.isFile()){return[]}const sourcePath=path27.resolve(outputDirectory,action2.source);const relativeSource=path27.relative(outputDirectory,sourcePath);if(relativeSource.startsWith(`..${path27.sep}`)||path27.isAbsolute(relativeSource)||!existsSync10(sourcePath)||!lstatSync6(sourcePath).isFile()||hashContent(readFileSync12(targetPath))!==hashContent(readFileSync12(sourcePath))){return[]}}return[toPosixPath(relativeTarget)]})??[]);const uniqueHarnessFiles=uniqueSorted2([...harnessFiles,...existsSync10(path27.join(outputDirectory,"opencode.json"))?["opencode.json"]:[]]);harnessFiles.splice(0,harnessFiles.length,...uniqueHarnessFiles);generatedFiles.push(...harnessFiles);return[projectionReceiptFile2,projectionReceipt2]};const[projectionReceiptFile,projectionReceipt]=collectHarnessProjectionFiles();const content=handoffContent(readScopedAuthoringProofs(projectionReceipt));const handoff=plannedFiles[handoffIndex];if(handoff===undefined){throw new Error("The current handoff producer is missing.")}plannedFiles[handoffIndex]={...handoff,content};await writeEvidenceArtifact({content,outputDirectory,relativePath:agentHandoffFile,session:activeFilesystemSession});const scaffoldManifestFile=".devpunks/scaffold-manifest.json";const manifestGeneratedFiles=[...generatedFiles,scaffoldManifestFile].toSorted();const producerForFile=(filePath)=>{if(filePath===scaffoldManifestFile){return"scaffold-manifest"}if(filePath===agentHandoffFile||filePath===".devpunks/AGENT-SYSTEM-PROMPT.md"){return"scaffold-handoff"}if(filePath===projectionReceiptFile||harnessFiles.includes(filePath)){return"harness-projection"}return"undeclared-artifact"};const withObligation=(file5)=>{const desired=plannedFiles.find((entry)=>entry.path===file5.path);return{...file5,obligation:desired?.obligation??producerObligation(producerForFile(file5.path)),...desired?.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:desired.sharedPromptIdentity}}};const managedFiles=expandManagedFiles(outputDirectory,generatedFiles).map(withObligation);const managedFileTypes=Object.fromEntries(managedFiles.map(({path:relativePath})=>[relativePath,lstatSync6(path27.join(outputDirectory,relativePath)).isSymbolicLink()?"symlink":"file"]));const managedFileModes=Object.fromEntries(managedFiles.map(({path:relativePath})=>{const stat3=lstatSync6(path27.join(outputDirectory,relativePath));return[relativePath,stat3.isSymbolicLink()?null:fileMode(stat3.mode)]}));const managedDependencies=desiredReceiptState.dependencies.filter((dependency)=>{const packageFile=dependency.workspace==="."?"package.json":path27.posix.join(dependency.workspace,"package.json");const absolutePath=path27.join(outputDirectory,packageFile);if(!existsSync10(absolutePath)){return false}const document=readJsonRecord(absolutePath);const section2=document[dependency.section];return isRecord8(section2)&&section2[dependency.name]===dependency.version});const managedStructuredEntries=desiredReceiptState.structuredEntries.filter((entry)=>{if(isOxlintCatalogStructuredEntry(entry)&&!manageOxlintCatalogReceipt){return false}const absolutePath=path27.join(outputDirectory,entry.file);if(!existsSync10(absolutePath)){return false}let value5=readJsonRecord(absolutePath);for(const segment of entry.path){if(!isRecord8(value5)){return false}value5=value5[segment]}if(entry.kind==="required-shell-segment"){return typeof value5==="string"&&typeof entry.value==="string"&&hasShellAndCommandSegment(value5,entry.value)}return JSON.stringify(value5)===JSON.stringify(entry.value)});generatedFiles.push(await writeEvidenceArtifact({content:encodePrettyJson2(Object.fromEntries([["cwd",scanDirectory],["outputDirectory",renderedOutputDirectory],["repoShapeMode",repoShapeMode],["monorepo",detection.monorepo],["manifests",detection.manifests.map((manifest)=>relativePosixPath(scanDirectory,manifest.path)||"package.json")],["detectedLanguages",detection.detectedLanguages],["detectedTechnologies",detection.detectedTechnologies],["monorepoSignals",detection.monorepoSignals.map((signal)=>Object.fromEntries([["type",signal.type],["path",relativePosixPath(scanDirectory,signal.path)||"."]]))],["finalPacks",finalPacks],...persistContextPlan?[["contextPlanFile",contextPlanFile]]:[],...projectionReceiptFile===null?[]:[["projectionReceiptFile",projectionReceiptFile],["projectionStatus",projectionReceipt?.status]],["promptOutputs",promptOutputs],["promptSpecFiles",promptSpecFiles],["lintSpecFiles",lintSpecFiles],["sourceGuideFiles",sourceGuideFiles],["skillFiles",skillFiles],["subagentFiles",subagentFiles],["scriptFiles",scriptFiles],["hookFiles",hookFiles],["harnessFiles",harnessFiles],["agentHandoffFile",agentHandoffFile],["promptSpecs",promptSpecs],["opensrcReferences",opensrcReferences],["sourceGuides",sourceGuideSummaries],["lintAssets",lintAssets],["appliedLintConfigs",appliedLintConfigs],["subagentManifestSpec",subagentManifestSpec],["baseline",baselineSummary2],["version",version2],["managedFiles",managedFiles],["managedFileTypes",managedFileTypes],["managedFileModes",managedFileModes],["managedDependencies",managedDependencies],["managedStructuredEntries",managedStructuredEntries],["generatedFiles",manifestGeneratedFiles]])),outputDirectory,relativePath:scaffoldManifestFile,session:activeFilesystemSession}));const managedFilesWithManifest=expandManagedFiles(outputDirectory,[...generatedFiles]).map(withObligation);const collectHiddenOutputDirectories=()=>[promptOutputs.some((value5)=>value5.startsWith(".agents/"))||subagentFiles.some((value5)=>value5.startsWith(".agents/"))||scriptFiles.some((value5)=>value5.startsWith(".agents/"))||hookFiles.some((value5)=>value5.startsWith(".agents/"))?".agents":null,harnessFiles.some((value5)=>value5.startsWith(".claude/"))?".claude":null,harnessFiles.some((value5)=>value5.startsWith(".codex/"))?".codex":null,harnessFiles.some((value5)=>value5.startsWith(".cursor/"))?".cursor":null,harnessFiles.some((value5)=>value5.startsWith(".opencode/"))?".opencode":null,promptSpecFiles.some((value5)=>value5.startsWith(".devpunks/"))||subagentFiles.some((value5)=>value5.startsWith(".devpunks/"))?".devpunks":null].filter((value5)=>value5!==null);const hiddenOutputDirectories=collectHiddenOutputDirectories();return{agentHandoffFile,baseline:baselineSummary2,contextPlan,contextPlanFile,generatedFiles:generatedFiles.toSorted(),harnessFiles:harnessFiles.toSorted(),hiddenOutputDirectories,hookFiles:hookFiles.toSorted(),lintAssets,lintSpecFiles:lintSpecFiles.toSorted(),managedFiles:managedFilesWithManifest,opensrcReferences,outputDirectory,projectionReceiptFile,projectionStatus:projectionReceipt?.status??null,promptOutputs:promptOutputs.toSorted(),promptSpecFiles:promptSpecFiles.toSorted(),promptSpecs,scaffoldManifestFile,scriptFiles:scriptFiles.toSorted(),skillFiles:skillFiles.toSorted(),sourceGuideFiles:sourceGuideFiles.toSorted(),sourceGuides:sourceGuideSummaries,subagentFiles:subagentFiles.toSorted(),subagentManifestSpec}};const materializationPlan=Object.freeze({desiredInput:desiredOutputInput,desiredState:desiredReceiptState,resetDirectories:Object.freeze([...plannedDirectoriesToReset]),staticResult});materializationPlanAppliers.set(materializationPlan,applyPlannedOutput);if(returnPlanOnly){return materializationPlan}materializationPlanAppliers.delete(materializationPlan);return await applyPlannedOutput({...suppliedFilesystemSession===undefined?{}:{filesystemSession:suppliedFilesystemSession},...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2}})};return yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Scaffold output materialization failed."}),try:materializePipeline})})}var planScaffoldOutput=(options4)=>runScaffoldOutputPipeline({...options4,planOnly:true});var planScaffoldMaterialization=(options4)=>runScaffoldOutputPipeline({...options4,returnPlanOnly:true});var applyScaffoldMaterializationPlan=(plan,runtime)=>gen2(function*applyPreparedScaffoldMaterialization(){const apply2=materializationPlanAppliers.get(plan);if(apply2===undefined){return yield*new CliValidationError({message:"The scaffold materialization plan is unknown or already consumed."})}materializationPlanAppliers.delete(plan);return yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Scaffold output materialization failed."}),try:async()=>await apply2(runtime)})});var writeScaffoldOutput=(options4)=>(options4.materializationPlan===undefined?planScaffoldMaterialization(options4):succeed6(options4.materializationPlan)).pipe(flatMap3((materializationPlan)=>applyScaffoldMaterializationPlan(materializationPlan,{...options4.filesystemSession===undefined?{}:{filesystemSession:options4.filesystemSession},...options4.scriptEnvironment===undefined?{}:{scriptEnvironment:options4.scriptEnvironment},...options4.scriptRuntimePath===undefined?{}:{scriptRuntimePath:options4.scriptRuntimePath}})));import{existsSync as existsSync11,lstatSync as lstatSync7,readlinkSync as readlinkSync5,readdirSync as readdirSync5}from"node:fs";import path28 from"node:path";var harnessProjectionSurfaces=[{agentDirectory:".claude/agents",agentExtension:".md",configFile:".claude/settings.json",hookDirectory:".claude/hooks"},{agentDirectory:".codex/agents",agentExtension:".toml",configFile:".codex/config.toml",hookDirectory:".codex/hooks"},{agentDirectory:".cursor/agents",agentExtension:".md",configFile:".cursor/hooks.json",hookDirectory:".cursor/hooks"},{agentDirectory:".opencode/agents",agentExtension:".md",configFile:"opencode.json",hookDirectory:".opencode/plugins"}];var managedProjectionHookIds=["format-edited-file","scaffold-update-check"];var withoutProjectionFragment=(targetPath)=>targetPath.split("#",1)[0]??"";var isOutsideRoot2=(relativePath)=>relativePath===".."||relativePath.startsWith(`..${path28.sep}`)||path28.isAbsolute(relativePath);var resolveProjectionPath=(outputDirectory,candidate)=>{const outputRoot=path28.resolve(outputDirectory);const resolved=path28.resolve(outputRoot,withoutProjectionFragment(candidate));const relative=path28.relative(outputRoot,resolved);if(relative.length===0||isOutsideRoot2(relative)){throw new CliValidationError({message:`Refusing to project scaffold content outside ${outputDirectory}.`})}return resolved};var preservesConsumerPromptTarget=({action:action2,outputDirectory})=>{if(action2.operation!=="mirror"||!action2.id.includes(":scoped-prompt:")||typeof action2.source!=="string"||typeof action2.target!=="string"||action2.source===action2.target){return false}const sourcePath=resolveProjectionPath(outputDirectory,action2.source);const targetPath=resolveProjectionPath(outputDirectory,action2.target);let target;try{target=lstatSync7(targetPath)}catch(error2){if(error2 instanceof Error&&"code"in error2&&typeof error2.code==="string"&&error2.code==="ENOENT"){return false}throw error2}if(!target.isSymbolicLink()){return!target.isFile()}return readlinkSync5(targetPath)!==path28.relative(path28.dirname(targetPath),sourcePath)};var omitsPreservedConsumerPromptTarget=({action:action2,outputDirectory,preserveConsumerPromptTargets})=>preserveConsumerPromptTargets&&preservesConsumerPromptTarget({action:action2,outputDirectory});var projectionMutationDestinations=(outputDirectory,plan,preserveConsumerPromptTargets)=>plan.projections.flatMap(({result:result4})=>result4.actions.flatMap((action2)=>{const operation2=typeof action2.operation==="string"?action2.operation:"";const target=typeof action2.target==="string"?action2.target:undefined;const configPath=typeof action2.config==="object"&&action2.config!==null&&"path"in action2.config&&typeof action2.config.path==="string"?action2.config.path:undefined;if(operation2==="mirror"){const source=typeof action2.source==="string"?action2.source:undefined;const omitPreservedTarget=omitsPreservedConsumerPromptTarget({action:action2,outputDirectory,preserveConsumerPromptTargets});const mirror=source===undefined||target===undefined||omitPreservedTarget?[]:[{allowedTargetSymlink:path28.relative(path28.dirname(resolveProjectionPath(outputDirectory,target)),resolveProjectionPath(outputDirectory,source)),targetPath:target}];return[...mirror,...configPath===undefined?[]:[{targetPath:configPath}]]}if(operation2==="render"||operation2==="render-template"){return target===undefined?[]:[{targetPath:target}]}if(operation2==="merge-json"||operation2==="merge-toml"){const file5=typeof action2.file==="string"?action2.file:target;return file5===undefined?[]:[{targetPath:file5}]}return[]}));var syntheticProjectionMutationDestinations=(outputDirectory,session)=>[...harnessProjectionSurfaces.flatMap((surface)=>{const absoluteAgentDirectory=resolveProjectionPath(outputDirectory,surface.agentDirectory);assertConfinedDirectory({directoryPath:absoluteAgentDirectory,outputDirectory,session});const existingAgents=existsSync11(absoluteAgentDirectory)?readdirSync5(absoluteAgentDirectory).filter((name2)=>name2.endsWith(surface.agentExtension)).map((name2)=>({targetPath:path28.join(surface.agentDirectory,name2)})):[];const hooks=managedProjectionHookIds.map((hookId)=>{const source=`.agents/hooks/${hookId}.mjs`;const target=`${surface.hookDirectory}/${hookId}.mjs`;return{allowedTargetSymlink:path28.relative(path28.dirname(resolveProjectionPath(outputDirectory,target)),resolveProjectionPath(outputDirectory,source)),targetPath:target}});return[...existingAgents,{targetPath:surface.configFile},...hooks]}),{targetPath:".codex/hooks.json"}];var preflightScaffoldOutputTargets=({directoryPaths,fileTargets,outputDirectory,plan,preserveConsumerPromptTargets,session})=>{const ordinaryFileTargets=[...plan.structuredEntries.map(({file:file5})=>({path:file5})),...fileTargets];for(const target of ordinaryFileTargets){assertConfinedWrite({...target.allowedTargetSymlink===undefined?{}:{allowedTargetSymlink:target.allowedTargetSymlink},outputDirectory,session,targetPath:path28.resolve(outputDirectory,target.path)})}for(const file5 of plan.files){assertConfinedWrite({...file5.encoding==="symlink"?{allowedTargetSymlink:file5.content}:{},outputDirectory,session,targetPath:path28.resolve(outputDirectory,file5.path)})}for(const destination of[...projectionMutationDestinations(outputDirectory,plan,preserveConsumerPromptTargets),...syntheticProjectionMutationDestinations(outputDirectory,session)]){assertConfinedWrite({...destination.allowedTargetSymlink===undefined?{}:{allowedTargetSymlink:destination.allowedTargetSymlink},outputDirectory,session,targetPath:resolveProjectionPath(outputDirectory,destination.targetPath)})}for(const relativePath of new Set(directoryPaths)){assertConfinedDirectory({directoryPath:path28.resolve(outputDirectory,relativePath),outputDirectory,session})}};var isRecord9=(value5)=>typeof value5==="object"&&value5!==null;var recordOrEmpty=(value5)=>isRecord9(value5)?value5:Object.fromEntries([]);var settleStageMutations=settleStartedMutations;var agentSystemPromptFile=".devpunks/AGENT-SYSTEM-PROMPT.md";var preflightStageDestinations=({outputDirectory,plan,resetDirectories,session,wikiFramework,wikiTarget})=>{const template=makeWikiScaffoldTemplate(wikiTarget.wikiRoot,wikiFramework);const inWiki=(relativePath)=>path29.posix.join(wikiTarget.targetRoot,relativePath);const wikiClaudePath=inWiki("CLAUDE.md");const filePaths=new Set([".devpunks/settings.json",".devpunks/AGENT-HANDOFF.md",".devpunks/scaffold-manifest.json",".devpunks/harness-projection-receipt.json",agentSystemPromptFile,".gitignore",...template.files.map(({path:filePath})=>inWiki(filePath)),...template.rawSubdirectories.map((directory3)=>inWiki(`raw/${directory3}/.gitkeep`)),inWiki("content/docs/project/.gitkeep"),inWiki("specs/.gitkeep"),inWiki("AGENTS.md"),wikiClaudePath,inWiki("index.md"),inWiki("log.md"),inWiki("backlog-provider.md"),inWiki("wiki-framework.md")]);preflightScaffoldOutputTargets({directoryPaths:[...template.topLevelDirectories.map(inWiki),...template.rawSubdirectories.map((directory3)=>inWiki(`raw/${directory3}`)),...resetDirectories,".devpunks/pre-existing-skills",...preExistingSkillSnapshotDirectories],fileTargets:[...filePaths].map((relativePath)=>({...relativePath===wikiClaudePath?{allowedTargetSymlink:"AGENTS.md"}:{},path:relativePath})),outputDirectory,plan,preserveConsumerPromptTargets:false,session})};var backlogProviderLabels2={"azure-devops":"Azure DevOps",github:"GitHub Projects and Issues",linear:"Linear",monday:"monday.com"};var wikiFrameworkLabels2={next:"Next.js","tanstack-start":"TanStack Start"};var writeAgentSystemPrompt=async({outputDirectory,content,session})=>{const absolutePath=path29.join(outputDirectory,agentSystemPromptFile);await writeConfinedFile({content:`${content}
2493
2493
  `,outputDirectory,replace:true,session,targetPath:absolutePath});return agentSystemPromptFile};var selectedSkills2=({packIds,baseline})=>[...new Set(packIds.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var baselineWithDefaultSkills=(baseline)=>{const defaultSkills=selectedSkills2({baseline,packIds:defaultPackIdsForBaseline(baseline)});const availableSkillIds=new Set(baseline.skills.map((skill)=>skill.id));return defaultSkills.every((skillId)=>availableSkillIds.has(skillId))?baseline:bundledBaseline};var wikiPromptTargetFor=({wikiRoot,wikiFramework,targetRoot=wikiRoot})=>({relativePath:path29.posix.join(targetRoot,"AGENTS.md"),seedContent:makeWikiScaffoldTemplate(wikiRoot,wikiFramework).agentsMarkdown});var renderBacklogProviderMarkdown=(provider)=>`# Backlog Provider
2494
2494
 
@@ -2505,30 +2505,31 @@ Keep this framework pinned unless the user explicitly changes it. \`punks update
2505
2505
  `)||content===""?content:`${content}
2506
2506
  `;await writeConfinedFile({content:`${contentWithTrailingNewline}${missingLines.join(`
2507
2507
  `)}
2508
- `,outputDirectory,replace:true,session,targetPath:gitignorePath});return relativePosixPath2(outputDirectory,gitignorePath)};var hasFlatRoutePage=(directoryPath)=>existsSync12(`${directoryPath}.md`)||existsSync12(`${directoryPath}.mdx`);var isNestedRouteSeedBlockedByFlatPage=({wikiDirectory,filePath})=>{const normalized=filePath.split(path29.sep).join(path29.posix.sep);const match8=/^content\/docs\/project\/(?<project>[^/]+)\/(?:index\.mdx|meta\.json)$/u.exec(normalized);const project2=match8?.groups?.project;if(project2===undefined){return false}return hasFlatRoutePage(path29.join(wikiDirectory,"content","docs","project",project2))};var appendCreatedFile=(createdFiles,createdFile)=>{if(createdFile!==null&&!createdFiles.includes(createdFile)){createdFiles.push(createdFile)}};var scaffoldWiki=async({outputDirectory,wikiRoot,targetRoot,backlogProvider,session,wikiFramework})=>{const template=makeWikiScaffoldTemplate(wikiRoot,wikiFramework);const createdFiles=[];const wikiDirectory=path29.join(outputDirectory,targetRoot);await settleStageMutations(template.topLevelDirectories.map(async(directory3)=>{await ensureConfinedDirectory({directoryPath:path29.join(wikiDirectory,directory3),outputDirectory,session})}));const rawKeepFiles=await settleStageMutations(template.rawSubdirectories.map(async(rawSubdirectory)=>{await ensureConfinedDirectory({directoryPath:path29.join(wikiDirectory,"raw",rawSubdirectory),outputDirectory,session});const keepFile=path29.join(wikiDirectory,"raw",rawSubdirectory,".gitkeep");return await writeMissingFile({content:"",outputDirectory,session,targetPath:keepFile})}));for(const createdFile of rawKeepFiles){appendCreatedFile(createdFiles,createdFile)}const directoryKeepFiles=[path29.join(wikiDirectory,"content","docs","project",".gitkeep"),path29.join(wikiDirectory,"specs",".gitkeep")];const createdKeepFiles=await settleStageMutations(directoryKeepFiles.map(async(keepFile)=>{if(directoryHasEntries({directoryPath:path29.dirname(keepFile),outputDirectory,session})){return null}return await writeMissingFile({content:"",outputDirectory,session,targetPath:keepFile})}));for(const createdFile of createdKeepFiles){appendCreatedFile(createdFiles,createdFile)}const createdTemplateFiles=await settleStageMutations(template.files.map(async(file5)=>{if(isNestedRouteSeedBlockedByFlatPage({filePath:file5.path,wikiDirectory})){return null}const writeFile3=file5.path==="scripts/sync-content.mjs"?writeManagedFile:writeMissingFile;return await writeFile3({content:file5.content,outputDirectory,session,targetPath:path29.join(wikiDirectory,file5.path)})}));for(const createdFile of createdTemplateFiles){appendCreatedFile(createdFiles,createdFile)}const updatedPackageFile=await updateExistingWikiPackage({outputDirectory,packagePath:path29.join(wikiDirectory,"package.json"),session,wikiFramework});appendCreatedFile(createdFiles,updatedPackageFile);const updatedGitignoreFile=await updateExistingWikiGitignore({expectedContent:template.files.find((file5)=>file5.path===".gitignore")?.content,gitignorePath:path29.join(wikiDirectory,".gitignore"),outputDirectory,session});appendCreatedFile(createdFiles,updatedGitignoreFile);if(wikiFramework==="tanstack-start"){const updatedViteConfig=await updateExistingTanstackViteConfig({outputDirectory,session,viteConfigPath:path29.join(wikiDirectory,"vite.config.ts")});appendCreatedFile(createdFiles,updatedViteConfig)}const agentsPath=path29.join(wikiDirectory,"AGENTS.md");const agentsFile=await writeMissingFile({content:template.agentsMarkdown,outputDirectory,session,targetPath:agentsPath});appendCreatedFile(createdFiles,agentsFile);const claudePath=path29.join(wikiDirectory,"CLAUDE.md");assertConfinedWrite({allowedTargetSymlink:"AGENTS.md",outputDirectory,session,targetPath:claudePath});if(!existsSync12(claudePath)){await replaceConfinedSymlink({linkTarget:"AGENTS.md",outputDirectory,session,targetPath:claudePath});createdFiles.push(relativePosixPath2(outputDirectory,claudePath))}const indexPath=path29.join(wikiDirectory,"index.md");const indexFile=await writeMissingFile({content:template.indexMarkdown,outputDirectory,session,targetPath:indexPath});appendCreatedFile(createdFiles,indexFile);const logPath=path29.join(wikiDirectory,"log.md");const logFile=await writeMissingFile({content:template.logMarkdown,outputDirectory,session,targetPath:logPath});appendCreatedFile(createdFiles,logFile);const backlogProviderFile=await writeMissingFile({content:renderBacklogProviderMarkdown(backlogProvider),outputDirectory,session,targetPath:path29.join(wikiDirectory,"backlog-provider.md")});appendCreatedFile(createdFiles,backlogProviderFile);const wikiFrameworkFile=await writeMissingFile({content:renderWikiFrameworkMarkdown(wikiFramework),outputDirectory,session,targetPath:path29.join(wikiDirectory,"wiki-framework.md")});appendCreatedFile(createdFiles,wikiFrameworkFile);return createdFiles.toSorted()};var isWikiOutputDirectory=(outputDirectory)=>{const normalized=path29.resolve(outputDirectory);return path29.basename(normalized)==="wiki"};var appSurfacedWikiRoot="app/wiki";var wikiRootMarkerFiles=["package.json","backlog-provider.md","wiki-framework.md"];var isDirectory=(directoryPath)=>{try{return statSync2(directoryPath).isDirectory()}catch{return false}};var hasWikiRootMarkers=(directoryPath)=>wikiRootMarkerFiles.some((marker)=>existsSync12(path29.join(directoryPath,marker)));var hasRootWorkspaces=(outputDirectory)=>{const packagePath=path29.join(outputDirectory,"package.json");if(!existsSync12(packagePath)){return false}try{const packageJson=JSON.parse(readFileSync13(packagePath,"utf-8"));return isRecord9(packageJson)&&packageJson.workspaces!==undefined}catch{return false}};var hasRootMonorepoSignals=(outputDirectory)=>existsSync12(path29.join(outputDirectory,"pnpm-workspace.yaml"))||existsSync12(path29.join(outputDirectory,"turbo.json"))||hasRootWorkspaces(outputDirectory);var hasAppPackageSurfaces=(outputDirectory)=>{if(hasRootMonorepoSignals(outputDirectory)){return false}const appDirectory=path29.join(outputDirectory,"app");if(!isDirectory(appDirectory)){return false}return readdirSync6(appDirectory,{withFileTypes:true}).some((entry)=>entry.isDirectory()&&existsSync12(path29.join(appDirectory,entry.name,"package.json")))};var stageWikiTarget=({outputDirectory,monorepo})=>{if(isWikiOutputDirectory(outputDirectory)){const parent=path29.basename(path29.dirname(path29.resolve(outputDirectory)));let wikiRoot="wiki";if(parent==="apps"){wikiRoot="apps/wiki"}else if(parent==="app"){wikiRoot=appSurfacedWikiRoot}return{targetRoot:".",wikiRoot}}if(!hasRootMonorepoSignals(outputDirectory)&&(hasWikiRootMarkers(path29.join(outputDirectory,appSurfacedWikiRoot))||hasAppPackageSurfaces(outputDirectory))){return{targetRoot:appSurfacedWikiRoot,wikiRoot:appSurfacedWikiRoot}}return{targetRoot:monorepo?"apps/wiki":"wiki",wikiRoot:monorepo?"apps/wiki":"wiki"}};var scaffoldWikiForDirectory=async({outputDirectory,monorepo,wikiFramework="next"})=>{const session=createConfinedFilesystemSession(outputDirectory);const wikiTarget=stageWikiTarget({monorepo,outputDirectory});return await scaffoldWiki({backlogProvider:"github",outputDirectory,session,targetRoot:wikiTarget.targetRoot,wikiFramework,wikiRoot:wikiTarget.wikiRoot})};var makeStageScopedScaffoldAdapter=({projectSettings})=>({plan:fn2("StageScopedScaffoldAdapter.plan")(function*planStage(callerInput,{filesystemSession,inspectionInput,selectedBaselineOrigin}){const input2=structuredClone(callerInput);const ownedInspectionInput=structuredClone(inspectionInput);const{baseline:scaffoldBaseline,outputDirectory}=ownedInspectionInput;const{inspection:{detection},wikiTarget}=input2;const{backlogProvider,assetProviderSlug,backlogProjectUrl,commitGate,repositoryManager}=input2.settings;const normalizedCommitGate=commitGate??"enabled";const finalPacks=defaultPackIdsForBaseline(scaffoldBaseline);const wikiPromptTarget=wikiPromptTargetFor({targetRoot:wikiTarget.targetRoot,wikiFramework:input2.wikiFramework,wikiRoot:wikiTarget.wikiRoot});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:[wikiPromptTarget],additionalScopes:wikiTarget.targetRoot==="."?[]:[{id:wikiTarget.targetRoot,kind:"docs",manifest:null,relativeWorkspacePath:wikiTarget.targetRoot}],baseline:scaffoldBaseline,detection,finalPacks,preserveExistingSubagentManifest:false,scanDirectory:outputDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:String(cause)})));const requiredTools=[...new Set([...requiredToolsForSkills2(skillIdsForContextPlan(contextPlan),scaffoldBaseline),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted();const desiredSettings={assetProviderSlug,backlogProjectUrl,backlogProvider,commitGate:normalizedCommitGate,baselineVersion:scaffoldBaseline.summary.version,cliVersion:version2,repositoryManager,requiredTools};const planningOptions={additionalPromptTargets:[wikiPromptTarget],additionalSkillSelection:{baseline:input2.selectedBaseline,baselineOrigin:selectedBaselineOrigin??(input2.selectedBaseline.summary.authoritySource==="bundled"?"bundled":"resolved"),skillIds:input2.stageSkillIds},baseline:scaffoldBaseline,contextPlan,detection,filesystemSession,outputDirectory,repoShapeMode:"auto",scanDirectory:outputDirectory,scriptEnvironment:input2.scriptEnvironment,scriptRuntimePath:input2.scriptRuntimePath,settings:desiredSettings};const materializationPlan=yield*planScaffoldMaterialization(planningOptions).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:String(cause)})));const plannedOutput=materializationPlan.desiredInput;const plannedDesiredStateInput=desiredScaffoldStateInput({...plannedOutput,settings:desiredSettings});const plannedCompilation=compileDesiredScaffoldState(plannedDesiredStateInput);if(plannedCompilation._tag==="DesiredScaffoldStateCompilationFailure"){return yield*new CliValidationError({cause:plannedCompilation,message:plannedCompilation.errors.map(({message})=>message).join(`
2508
+ `,outputDirectory,replace:true,session,targetPath:gitignorePath});return relativePosixPath2(outputDirectory,gitignorePath)};var hasFlatRoutePage=(directoryPath)=>existsSync12(`${directoryPath}.md`)||existsSync12(`${directoryPath}.mdx`);var isNestedRouteSeedBlockedByFlatPage=({wikiDirectory,filePath})=>{const normalized=filePath.split(path29.sep).join(path29.posix.sep);const match8=/^content\/docs\/project\/(?<project>[^/]+)\/(?:index\.mdx|meta\.json)$/u.exec(normalized);const project2=match8?.groups?.project;if(project2===undefined){return false}return hasFlatRoutePage(path29.join(wikiDirectory,"content","docs","project",project2))};var appendCreatedFile=(createdFiles,createdFile)=>{if(createdFile!==null&&!createdFiles.includes(createdFile)){createdFiles.push(createdFile)}};var scaffoldWiki=async({outputDirectory,wikiRoot,targetRoot,backlogProvider,session,wikiFramework})=>{const template=makeWikiScaffoldTemplate(wikiRoot,wikiFramework);const createdFiles=[];const wikiDirectory=path29.join(outputDirectory,targetRoot);await settleStageMutations(template.topLevelDirectories.map(async(directory3)=>{await ensureConfinedDirectory({directoryPath:path29.join(wikiDirectory,directory3),outputDirectory,session})}));const rawKeepFiles=await settleStageMutations(template.rawSubdirectories.map(async(rawSubdirectory)=>{await ensureConfinedDirectory({directoryPath:path29.join(wikiDirectory,"raw",rawSubdirectory),outputDirectory,session});const keepFile=path29.join(wikiDirectory,"raw",rawSubdirectory,".gitkeep");if(directoryHasEntries({directoryPath:path29.dirname(keepFile),outputDirectory,session})){return null}return await writeMissingFile({content:"",outputDirectory,session,targetPath:keepFile})}));for(const createdFile of rawKeepFiles){appendCreatedFile(createdFiles,createdFile)}const directoryKeepFiles=[path29.join(wikiDirectory,"content","docs","project",".gitkeep"),path29.join(wikiDirectory,"specs",".gitkeep")];const createdKeepFiles=await settleStageMutations(directoryKeepFiles.map(async(keepFile)=>{if(directoryHasEntries({directoryPath:path29.dirname(keepFile),outputDirectory,session})){return null}return await writeMissingFile({content:"",outputDirectory,session,targetPath:keepFile})}));for(const createdFile of createdKeepFiles){appendCreatedFile(createdFiles,createdFile)}const createdTemplateFiles=await settleStageMutations(template.files.map(async(file5)=>{if(isNestedRouteSeedBlockedByFlatPage({filePath:file5.path,wikiDirectory})){return null}const writeFile3=file5.path==="scripts/sync-content.mjs"?writeManagedFile:writeMissingFile;return await writeFile3({content:file5.content,outputDirectory,session,targetPath:path29.join(wikiDirectory,file5.path)})}));for(const createdFile of createdTemplateFiles){appendCreatedFile(createdFiles,createdFile)}const updatedPackageFile=await updateExistingWikiPackage({outputDirectory,packagePath:path29.join(wikiDirectory,"package.json"),session,wikiFramework});appendCreatedFile(createdFiles,updatedPackageFile);const updatedGitignoreFile=await updateExistingWikiGitignore({expectedContent:template.files.find((file5)=>file5.path===".gitignore")?.content,gitignorePath:path29.join(wikiDirectory,".gitignore"),outputDirectory,session});appendCreatedFile(createdFiles,updatedGitignoreFile);if(wikiFramework==="tanstack-start"){const updatedViteConfig=await updateExistingTanstackViteConfig({outputDirectory,session,viteConfigPath:path29.join(wikiDirectory,"vite.config.ts")});appendCreatedFile(createdFiles,updatedViteConfig)}const agentsPath=path29.join(wikiDirectory,"AGENTS.md");const agentsFile=await writeMissingFile({content:template.agentsMarkdown,outputDirectory,session,targetPath:agentsPath});appendCreatedFile(createdFiles,agentsFile);const claudePath=path29.join(wikiDirectory,"CLAUDE.md");assertConfinedWrite({allowedTargetSymlink:"AGENTS.md",outputDirectory,session,targetPath:claudePath});if(!existsSync12(claudePath)){await replaceConfinedSymlink({linkTarget:"AGENTS.md",outputDirectory,session,targetPath:claudePath});createdFiles.push(relativePosixPath2(outputDirectory,claudePath))}const indexPath=path29.join(wikiDirectory,"index.md");const indexFile=await writeMissingFile({content:template.indexMarkdown,outputDirectory,session,targetPath:indexPath});appendCreatedFile(createdFiles,indexFile);const logPath=path29.join(wikiDirectory,"log.md");const logFile=await writeMissingFile({content:template.logMarkdown,outputDirectory,session,targetPath:logPath});appendCreatedFile(createdFiles,logFile);const backlogProviderFile=await writeMissingFile({content:renderBacklogProviderMarkdown(backlogProvider),outputDirectory,session,targetPath:path29.join(wikiDirectory,"backlog-provider.md")});appendCreatedFile(createdFiles,backlogProviderFile);const wikiFrameworkFile=await writeMissingFile({content:renderWikiFrameworkMarkdown(wikiFramework),outputDirectory,session,targetPath:path29.join(wikiDirectory,"wiki-framework.md")});appendCreatedFile(createdFiles,wikiFrameworkFile);return createdFiles.toSorted()};var isWikiOutputDirectory=(outputDirectory)=>{const normalized=path29.resolve(outputDirectory);return path29.basename(normalized)==="wiki"};var appSurfacedWikiRoot="app/wiki";var wikiRootMarkerFiles=["package.json","backlog-provider.md","wiki-framework.md"];var isDirectory=(directoryPath)=>{try{return statSync2(directoryPath).isDirectory()}catch{return false}};var hasWikiRootMarkers=(directoryPath)=>wikiRootMarkerFiles.some((marker)=>existsSync12(path29.join(directoryPath,marker)));var hasRootWorkspaces=(outputDirectory)=>{const packagePath=path29.join(outputDirectory,"package.json");if(!existsSync12(packagePath)){return false}try{const packageJson=JSON.parse(readFileSync13(packagePath,"utf-8"));return isRecord9(packageJson)&&packageJson.workspaces!==undefined}catch{return false}};var hasRootMonorepoSignals=(outputDirectory)=>existsSync12(path29.join(outputDirectory,"pnpm-workspace.yaml"))||existsSync12(path29.join(outputDirectory,"turbo.json"))||hasRootWorkspaces(outputDirectory);var hasAppPackageSurfaces=(outputDirectory)=>{if(hasRootMonorepoSignals(outputDirectory)){return false}const appDirectory=path29.join(outputDirectory,"app");if(!isDirectory(appDirectory)){return false}return readdirSync6(appDirectory,{withFileTypes:true}).some((entry)=>entry.isDirectory()&&existsSync12(path29.join(appDirectory,entry.name,"package.json")))};var stageWikiTarget=({outputDirectory,monorepo})=>{if(isWikiOutputDirectory(outputDirectory)){const parent=path29.basename(path29.dirname(path29.resolve(outputDirectory)));let wikiRoot="wiki";if(parent==="apps"){wikiRoot="apps/wiki"}else if(parent==="app"){wikiRoot=appSurfacedWikiRoot}return{targetRoot:".",wikiRoot}}if(!hasRootMonorepoSignals(outputDirectory)&&(hasWikiRootMarkers(path29.join(outputDirectory,appSurfacedWikiRoot))||hasAppPackageSurfaces(outputDirectory))){return{targetRoot:appSurfacedWikiRoot,wikiRoot:appSurfacedWikiRoot}}return{targetRoot:monorepo?"apps/wiki":"wiki",wikiRoot:monorepo?"apps/wiki":"wiki"}};var scaffoldWikiForDirectory=async({outputDirectory,monorepo,wikiFramework="next"})=>{const session=createConfinedFilesystemSession(outputDirectory);const wikiTarget=stageWikiTarget({monorepo,outputDirectory});return await scaffoldWiki({backlogProvider:"github",outputDirectory,session,targetRoot:wikiTarget.targetRoot,wikiFramework,wikiRoot:wikiTarget.wikiRoot})};var makeStageScopedScaffoldAdapter=({projectSettings})=>({plan:fn2("StageScopedScaffoldAdapter.plan")(function*planStage(callerInput,{filesystemSession,inspectionInput,selectedBaselineOrigin}){const input2=structuredClone(callerInput);const ownedInspectionInput=structuredClone(inspectionInput);const{baseline:scaffoldBaseline,outputDirectory}=ownedInspectionInput;const{inspection:{detection},wikiTarget}=input2;const{backlogProvider,assetProviderSlug,backlogProjectUrl,commitGate,repositoryManager}=input2.settings;const normalizedCommitGate=commitGate??"enabled";const finalPacks=defaultPackIdsForBaseline(scaffoldBaseline);const wikiPromptTarget=wikiPromptTargetFor({targetRoot:wikiTarget.targetRoot,wikiFramework:input2.wikiFramework,wikiRoot:wikiTarget.wikiRoot});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:[wikiPromptTarget],additionalScopes:wikiTarget.targetRoot==="."?[]:[{id:wikiTarget.targetRoot,kind:"docs",manifest:null,relativeWorkspacePath:wikiTarget.targetRoot}],baseline:scaffoldBaseline,detection,finalPacks,preserveExistingSubagentManifest:false,scanDirectory:outputDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:String(cause)})));const requiredTools=[...new Set([...requiredToolsForSkills2(skillIdsForContextPlan(contextPlan),scaffoldBaseline),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted();const desiredSettings={assetProviderSlug,backlogProjectUrl,backlogProvider,commitGate:normalizedCommitGate,baselineVersion:scaffoldBaseline.summary.version,cliVersion:version2,repositoryManager,requiredTools};const planningOptions={additionalPromptTargets:[wikiPromptTarget],additionalSkillSelection:{baseline:input2.selectedBaseline,baselineOrigin:selectedBaselineOrigin??(input2.selectedBaseline.summary.authoritySource==="bundled"?"bundled":"resolved"),skillIds:input2.stageSkillIds},baseline:scaffoldBaseline,contextPlan,detection,filesystemSession,outputDirectory,repoShapeMode:"auto",scanDirectory:outputDirectory,scriptEnvironment:input2.scriptEnvironment,scriptRuntimePath:input2.scriptRuntimePath,settings:desiredSettings};const materializationPlan=yield*planScaffoldMaterialization(planningOptions).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:String(cause)})));const plannedOutput=materializationPlan.desiredInput;const plannedDesiredStateInput=desiredScaffoldStateInput({...plannedOutput,settings:desiredSettings});const plannedCompilation=compileDesiredScaffoldState(plannedDesiredStateInput);if(plannedCompilation._tag==="DesiredScaffoldStateCompilationFailure"){return yield*new CliValidationError({cause:plannedCompilation,message:plannedCompilation.errors.map(({message})=>message).join(`
2509
2509
  `)})}yield*try_3({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Scaffold preflight failed."}),try:()=>{preflightStageDestinations({outputDirectory,plan:plannedOutput,resetDirectories:materializationPlan.resetDirectories,session:filesystemSession,wikiFramework:input2.wikiFramework,wikiTarget})}});const settingsInitialization={calculatedTools:{requiredTools},managedVersions:{baselineVersion:materializationPlan.staticResult.baseline.version,cliVersion:version2},userChoices:{assetProviderSlug,backlogProjectUrl,backlogProvider,commitGate:normalizedCommitGate,repositoryManager}};const outputOptions={additionalPromptTargets:[wikiPromptTarget],contextPlan,desiredState:materializationPlan.desiredState,detection,filesystemSession,materializationPlan,outputDirectory,repoShapeMode:"auto",scanDirectory:outputDirectory,scriptEnvironment:input2.scriptEnvironment,scriptRuntimePath:input2.scriptRuntimePath,settings:desiredSettings};return Object.freeze({_tag:"StagePlanState",backlogProvider,detection,filesystemSession,finalPacks,outputDirectory,outputOptions,plannedCompilation,plannedDesiredStateInput,settingsInitialization,wikiFramework:input2.wikiFramework,wikiPromptTarget,wikiTarget})}),materialize:(state)=>{const{backlogProvider,detection,filesystemSession,finalPacks,outputDirectory,outputOptions,plannedCompilation,plannedDesiredStateInput,settingsInitialization,wikiFramework,wikiPromptTarget,wikiTarget}=state;const{materializationPlan}=outputOptions;return gen2(function*materializeStage(){const settingsDirectory=path29.join(outputDirectory,".devpunks");assertConfinedDirectory({directoryPath:settingsDirectory,outputDirectory,session:filesystemSession});const settingsDirectoryExisted=existsSync12(settingsDirectory);assertConfinedFilesystemSession({outputDirectory,session:filesystemSession});let committed=false;yield*projectSettings.initialize(outputDirectory,settingsInitialization,filesystemSession).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));return yield*gen2(function*applyInitializedStage(){const lifecycle=yield*runInitScaffoldLifecycle({apply:({desiredState})=>gen2(function*applyStageScaffold(){const projectedWikiFiles=[wikiPromptTarget.relativePath,path29.posix.join(wikiTarget.targetRoot,"CLAUDE.md")].filter((file5)=>!existsSync12(path29.join(outputDirectory,file5)));const scaffoldOutput2=yield*writeScaffoldOutput({...outputOptions,contextPlan:desiredState.contextPlan,desiredState,materializationPlan,settings:desiredState.settings}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:String(cause)})));committed=true;const wikiFiles2=yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Wiki scaffold failed."}),try:async()=>[...new Set([...await scaffoldWiki({outputDirectory,...wikiTarget,backlogProvider,session:filesystemSession,wikiFramework}),...projectedWikiFiles.filter((file5)=>existsSync12(path29.join(outputDirectory,file5)))])].toSorted()});yield*completeLocalQualitySetup({desiredState,rootDirectory:outputDirectory,session:filesystemSession}).pipe(catchTag2("LocalQualitySetupFailure",(cause)=>fail6(new CliValidationError({cause,message:cause.message}))));return{scaffoldOutput:scaffoldOutput2,wikiFiles:wikiFiles2}}),compile:()=>plannedCompilation,gather:()=>succeed6(plannedDesiredStateInput)});if(lifecycle._tag==="ScaffoldLifecycleCompilationFailed"){return yield*new CliValidationError({cause:lifecycle.compilation,message:lifecycle.compilation.errors.map(({message})=>message).join(`
2510
2510
  `)})}const{scaffoldOutput,wikiFiles}=lifecycle.application;if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Init scaffold did not produce harness projection evidence."})}const{projectionReceiptFile,projectionStatus,skillFiles}=scaffoldOutput;yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Scaffold gitignore cleanup failed."}),try:async()=>await removeHarnessDirectoriesFromGitignore(outputDirectory,undefined,filesystemSession)});yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Agent system prompt write failed."}),try:async()=>await writeAgentSystemPrompt({content:formatAgentHandoffSummary({addedPacks:[],agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile,baseline:scaffoldOutput.baseline,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:outputDirectory,defaultPacks:finalPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:[],detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile].toSorted(),harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:[],lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:detection.manifests.map((manifest)=>path29.relative(detection.cwd,manifest.path)||"package.json"),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile,projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:[],repoShapeMode:"auto",scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:[],toolBootstrapStatuses:[]}),outputDirectory,session:filesystemSession})});return{_tag:"MaterializedStageScaffold",commitState:"committed",contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,outputDirectory,projectionReceiptFile,projectionStatus,skillFiles,wikiFiles,wikiRoot:wikiTarget.wikiRoot}}).pipe(onError2(()=>gen2(function*rollbackInitializedStage(){if(committed){return}yield*projectSettings.rollbackInitialization(outputDirectory,{initialization:settingsInitialization,removeSettingsDirectory:!settingsDirectoryExisted},filesystemSession).pipe(result2)})))})}});var operationFailure2=(cause,outputDirectory)=>{if(cause instanceof CliValidationError){return cause}if(cause instanceof RepositoryScanError){return new CliValidationError({cause:new CliDetectionError({cause:cause.cause,message:"Failed to detect repository shape."}),message:`Could not inspect repository at ${outputDirectory}.`})}return new CliValidationError({cause:cause.cause,message:cause.message})};var runStageScaffold=({commandId,outputDirectory,interaction,baseline=bundledBaseline,configuration={disableBundledUrl:true},scriptRuntimePath:scriptRuntimePath2="node",scriptEnvironment={}})=>gen2(function*executeStageScaffold(){const operation2=yield*ScopedScaffoldOperation;const stage=stageScaffoldById[commandId];const selectedBaseline=structuredClone(baseline);const scaffoldBaseline=baselineWithDefaultSkills(selectedBaseline);const inspection=yield*operation2.inspect({baseline:scaffoldBaseline,outputDirectory,repoShapeMode:"auto",scanDirectory:outputDirectory}).pipe(mapError3((cause)=>operationFailure2(cause,outputDirectory)));const wikiTarget=Object.freeze(stageWikiTarget({monorepo:inspection.detection.monorepo,outputDirectory}));const settings=Object.freeze(structuredClone(yield*interaction.selectRepoSettings()));const wikiFramework=yield*interaction.selectWikiFramework();const plan=yield*operation2.plan({_tag:"PlanStageScaffold",inspection,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2,selectedBaseline,settings,stageSkillIds:stage.skills,wikiFramework,wikiTarget}).pipe(mapError3((cause)=>operationFailure2(cause,outputDirectory)));const materialized=yield*operation2.materialize(plan).pipe(mapError3((cause)=>operationFailure2(cause,outputDirectory)));if(materialized._tag!=="MaterializedStageScaffold"){return yield*new CliValidationError({message:"Stage scaffold operation returned repository materialization."})}const operatorPrompt=stage.renderPrompt({backlogProvider:settings.backlogProvider,wikiFramework,wikiRoot:materialized.wikiRoot});yield*interaction.emit({_tag:"InitComplete",commandId,hiddenOutputDirectories:materialized.hiddenOutputDirectories,operatorPrompt,outputDirectory,settings,skillFiles:materialized.skillFiles,summary:stage.summary,wikiFiles:materialized.wikiFiles,wikiFramework});yield*submitCliEventEffect("cli.scaffold.init.completed",{baseline:{version:selectedBaseline.summary.version},configuration,cwd:outputDirectory});return{...settings,contextPlan:materialized.contextPlan,contextPlanFile:materialized.contextPlanFile,outputDirectory,projectionReceiptFile:materialized.projectionReceiptFile,projectionStatus:materialized.projectionStatus,skillFiles:materialized.skillFiles,wikiFiles:materialized.wikiFiles,wikiFramework}});import{existsSync as existsSync13}from"node:fs";import path30 from"node:path";var findOperatorProjectRoot=(cwd)=>{let directory3=path30.resolve(cwd);const filesystemRoot=path30.parse(directory3).root;while(true){if(existsSync13(path30.join(directory3,".git"))){return directory3}if(directory3===filesystemRoot){return path30.resolve(cwd)}directory3=path30.dirname(directory3)}};import path31 from"node:path";var record2=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5)?Object.fromEntries(Object.entries(value5)):{};var overlayWikiDetection=({detection,stagedDetection,documents})=>{const rootManifest=detection.manifests.find(({relativePath})=>relativePath==="package.json");return{...detection,manifests:[...detection.manifests.filter(({relativePath})=>!Object.hasOwn(documents,relativePath)),...stagedDetection.manifests.filter(({relativePath})=>Object.hasOwn(documents,relativePath)).map((manifest)=>{const existing=detection.manifests.find(({relativePath})=>relativePath===manifest.relativePath);const hasDeclaration=Object.hasOwn(documents[manifest.relativePath]??{},"packageManager");const manager=hasDeclaration?manifest.packageManager:manifest.packageManager??existing?.packageManager??rootManifest?.packageManager;const lockfile=hasDeclaration?manifest.lockfile:manifest.lockfile??(existing?.packageManager===manager?existing?.lockfile:undefined)??(rootManifest?.packageManager===manager?rootManifest?.lockfile:undefined);return{...manifest,...manager===undefined?{}:{packageManager:manager},...lockfile===undefined?{}:{lockfile},path:path31.join(detection.cwd,manifest.relativePath)}})]}};var generatedWikiDependencies=({documents,previousDocuments,managedDependencies})=>Object.entries(documents).flatMap(([file5,document])=>["dependencies","devDependencies"].flatMap((section2)=>{const previous=record2(previousDocuments[file5]?.[section2]);return Object.entries(record2(document[section2])).flatMap(([name2,version3])=>typeof version3==="string"&&(!Object.hasOwn(previous,name2)||managedDependencies.some((entry)=>entry.name===name2&&entry.section===section2&&entry.workspace===path31.posix.dirname(file5)))?[{name:name2,section:section2,source:"baseline",version:version3,workspace:path31.posix.dirname(file5)}]:[])}));var withPlannedWikiPackages=({plan,documents,dependencies})=>{const managedIdentities=new Set(plan.dependencies.map((entry)=>JSON.stringify([entry.workspace,entry.section,entry.name])));const mergedDependencies=[...new Map([...dependencies.filter((entry)=>!managedIdentities.has(JSON.stringify([entry.workspace,entry.section,entry.name]))),...plan.dependencies].map((entry)=>[JSON.stringify([entry.workspace,entry.section,entry.name,entry.version,entry.source,entry.revision]),entry])).values()];const packages=Object.entries(documents).map(([file5,source])=>{const document={...source};for(const dependency of mergedDependencies.filter(({workspace})=>path31.posix.dirname(file5)===workspace)){document[dependency.section]={...record2(document[dependency.section]),[dependency.name]:dependency.version}}for(const entry of plan.structuredEntries){if(entry.file===file5&&entry.kind==="field"&&entry.path.length===2){const[section2,field]=entry.path;if(section2!==undefined&&field!==undefined){document[section2]={...record2(document[section2]),[field]:entry.value}}}}return{content:`${JSON.stringify(document,null,2)}
2511
2511
  `,kind:"harness",path:file5,source:"baseline"}});return{...plan,dependencies:mergedDependencies,files:[...plan.files.filter(({path:file5})=>!Object.hasOwn(documents,file5)),...packages]}};import{createHash as createHash12}from"node:crypto";import{spawnSync as spawnSync3}from"node:child_process";import{cpSync as cpSync2,existsSync as existsSync15,lstatSync as lstatSync8,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync5,realpathSync as realpathSync7,readdirSync as readdirSync8,readFileSync as readFileSync15,readlinkSync as readlinkSync6,rmSync as rmSync5,symlinkSync,writeFileSync as writeFileSync7}from"node:fs";import{tmpdir as tmpdir8}from"node:os";import path33 from"node:path";import{existsSync as existsSync14,readFileSync as readFileSync14,readdirSync as readdirSync7,statSync as statSync3}from"node:fs";import path32 from"node:path";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 sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths2=new Set(["app/wiki","apps/wiki","wiki"]);var pythonDependencyFiles=["Pipfile","poetry.lock","pyproject.toml","requirements.txt","uv.lock"];var detectedPythonPackages=["alembic","sqlalchemy"];var isRecord10=(value5)=>typeof value5==="object"&&value5!==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),scripts:optional(Record(String4,String4)),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)&&existsSync14(path32.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 qualityCommandContractFor=(packageJson)=>resolveQualityCommands(packageJson.scripts).contract;var parsePackageJsonRecord=decodeUnknownSync(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync(ArraySchema(String4));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record3)=>{if(!record3){return}for(const name2 of Object.keys(record3)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path32.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths2].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests2=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync7(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path32.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync14(cwd)){visit2(cwd)}return results.toSorted()};var detectPythonPackages=(cwd)=>{const detected=new Set;for(const filename of pythonDependencyFiles){for(const dependencyFile of recursiveFindFiles(cwd,filename)){if(isWikiRelativePath(path32.relative(cwd,dependencyFile))){continue}const content=readFileSync14(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=path32.join(cwd,rootDirectoryName);if(!existsSync14(rootDirectory)){return[]}return readdirSync7(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path32.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync14(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync7(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path32.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync14(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord10(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path32.join(cwd,"pnpm-workspace.yaml");if(!existsSync14(workspacePath)){return[]}const patterns=[];let inPackagesSection=false;for(const rawLine of readFileSync14(workspacePath,"utf-8").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 expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path32.join(cwd,pattern.slice(0,-2));if(!existsSync14(baseDirectory)){return[]}return readdirSync7(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path32.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync14(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path32.join(cwd,pattern,"package.json");return existsSync14(manifestPath)?[manifestPath]:[]};var discoverPackageJsonInputs=(cwd)=>{const rootPackageJsonPath=path32.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json");if(!existsSync14(rootPackageJsonPath)){return{declaredWorkspacePaths:new Set,manifestPaths:recursivePackageJsonPaths,rootPackageJson:null}}const rootPackageJson=parsePackageJsonRecord(readFileSync14(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=path32.relative(cwd,path32.dirname(manifestPath)).split(path32.sep).join("/");return relative!==""&&[...workspacePatterns].some((pattern)=>!pattern.startsWith("!")&&path32.matchesGlob(relative,pattern))&&![...workspacePatterns].some((pattern)=>pattern.startsWith("!")&&path32.matchesGlob(relative,pattern.slice(1)))})),manifestPaths:[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value5,index,values)=>values.indexOf(value5)===index).toSorted(),rootPackageJson}};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests2(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix));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)=>path32.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync7(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path32.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path32.relative(cwd,absolutePath);if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")){detected.add(language)}}}}};if(existsSync14(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests)=>{const packageNames=new Set(packDetectionManifests2(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml")){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json")){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync14(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord10(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync14(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord10(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)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const root=statSync3(cwd,{throwIfNoEntry:false});if(root===undefined||!root.isDirectory()){throw new TypeError("Repository input must be an existing directory.")}const{declaredWorkspacePaths,manifestPaths,rootPackageJson}=discoverPackageJsonInputs(cwd);const rootDeclaration=rootPackageJson?.packageManager===undefined?undefined:packageManagerFor(cwd,rootPackageJson)?.packageManager;const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync14(manifestPath,"utf-8"));const packageManager=packageManagerFor(cwd,pkg,declaredWorkspacePaths.has(manifestPath)?rootDeclaration:undefined);const qualityCommandContract=qualityCommandContractFor(pkg);return{dependencies:collectPackageNames(pkg),...packageManager,packageName:pkg.name??null,path:manifestPath,...qualityCommandContract===undefined?{}:{qualityCommandContract},relativePath:path32.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests);const detectedPackages=detectPythonPackages(cwd);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests);return{cwd,detectedLanguages,detectedPackages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}});var manifestPaths=(result4)=>result4.manifests.map((manifest)=>path32.relative(result4.cwd,manifest.path)||"package.json");var applyRepoShapeMode=(result4,repoShapeMode)=>repoShapeMode==="auto"?result4:{...result4,monorepo:repoShapeMode==="monorepo"};import{createHash as createHash11}from"node:crypto";var nodeScaffoldContentHasher={sha256:(file5)=>{const{content:fileContent,encoding}=file5;let content=fileContent;if(encoding==="base64"){content=Buffer.from(fileContent,"base64")}else if(encoding==="symlink"){content=`symlink:${fileContent}`}return createHash11("sha256").update(content).digest("hex")}};class ProjectProducerFailure extends TaggedErrorClass()("@punks/cli/scaffold-state/ProjectProducerFailure",{cause:Defect(),message:String4,operation:Literal2("derive-project-generated-ownership"),sourcePath:String4}){}var ProjectProducer=Service("@punks/cli/features/scaffold-state/ProjectProducer");var deriveProjectGeneratedOwnership=fn2("ScaffoldState.deriveProjectGeneratedOwnership")(function*deriveProjectGeneratedOwnership2({declaration,repositoryRoot}){if(declaration.authority._tag!=="RepositoryMirror"){return yield*new ProjectProducerFailure({cause:declaration.authority,message:`Unsupported project producer authority: ${JSON.stringify(declaration.authority._tag)}`,operation:"derive-project-generated-ownership",sourcePath:declaration.authority.sourcePath})}const producer=yield*ProjectProducer;const outputFingerprint=yield*producer.fingerprintRepositoryMirror({repositoryRoot,sourcePath:declaration.authority.sourcePath});return{_tag:"ProjectGenerated",evidence:{...declaration,outputFingerprint}}});var scaffoldManifestFile=".devpunks/scaffold-manifest.json";var scaffoldPublicationInputIdentity=(baseline)=>hashManagedFileContent("publication-inputs.json",encodePrettyJson2({baseline:{commit:baseline.summary.commit,digest:baseline.summary.digest,sha256:baseline.summary.sha256,tag:baseline.summary.tag,version:baseline.summary.version},capabilities:baseline.capabilities}));var agentHandoffFile2=".devpunks/AGENT-HANDOFF.md";var agentSystemPromptFile2=".devpunks/AGENT-SYSTEM-PROMPT.md";var legacyRequiredToolsFile=".devpunks/required-tools.json";var repoSettingsDisplayFile=".devpunks/settings.json";var updateCompleteMessage=({applied,applyRequested,hasManagedUpdates})=>{if(applied){return"Managed scaffold files updated."}if(applyRequested&&hasManagedUpdates){return"Managed scaffold updates remain; no files were written."}if(applyRequested){return"No managed scaffold changes were needed."}return"No files were written."};var scaffoldApplicationValidationFailure=(failures)=>{for(const{cause}of failures){if(is2(CliValidationError)(cause)){return cause}}return};var managedFileSchema=ScaffoldManagedFileSummary;var managedDependencyReceiptSchema=Struct({name:String4,section:Literals(["dependencies","devDependencies","peerDependencies"]),version:String4,workspace:String4});var managedStructuredEntryKindSchema=Literals(["field","key","required-shell-segment"]);var managedStructuredEntryReceiptSchema=Struct({file:String4,kind:managedStructuredEntryKindSchema,path:ArraySchema(String4),value:Unknown2});var scaffoldManifestSchema=fromJsonString2(Struct({baseline:optional(Unknown2),contextPlanFile:optional(String4),finalPacks:ArraySchema(String4),generatedFiles:optional(ArraySchema(String4)),managedDependencies:optional(ArraySchema(managedDependencyReceiptSchema)),managedFileModes:optional(Record(String4,Union2([Number6,Null2]))),managedFileTypes:optional(Record(String4,Literals(["file","symlink"]))),managedFiles:optional(ArraySchema(managedFileSchema)),managedStructuredEntries:optional(ArraySchema(managedStructuredEntryReceiptSchema)),pendingPublication:optional(Struct({dependencies:ArraySchema(managedDependencyReceiptSchema),inputIdentity:NonEmptyString,structuredEntries:ArraySchema(managedStructuredEntryReceiptSchema),version:Literal2("1")})),projectionReceiptFile:optional(String4),projectionStatus:optional(Literals(["partial","success"])),repoShapeMode:optional(String4),scaffoldDegradations:optional(ArraySchema(Unknown2)),version:optional(String4)}));var isOxlintCatalogStructuredEntry2=(entry)=>entry.file==="package.json"&&entry.kind==="field"&&entry.path.length===3&&entry.path[0]==="workspaces"&&entry.path[1]==="catalog"&&entry.path[2]==="oxlint";var ownershipMetadataOperationChanges=({allChanges,applied,required})=>{if(!required||allChanges.some(({path:relativePath})=>relativePath===scaffoldManifestFile)){return[]}return[{action:"update",state:applied?"completed":"planned",subject:scaffoldManifestFile}]};var noopHumanOutput=(_line)=>void_3;var parseManifest=decodeUnknownSync(scaffoldManifestSchema);var isRecord11=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var isUnknownArray=(value5)=>Array.isArray(value5);var manifestBaselineRecord=(value5)=>isRecord11(value5)?value5:undefined;var hashContent2=(content)=>createHash12("sha256").update(content).digest("hex");var fileMode2=(mode)=>mode%512;var normalizeRepoShapeMode=(value5)=>value5==="monorepo"||value5==="single"?value5:"auto";var normalizePacks=(values,baseline)=>{const known=new Set(baseline.packs.map((pack)=>pack.id));const unknown2=values.filter((value5)=>!known.has(value5));if(unknown2.length>0){throw new Error(`Unknown packs in ${scaffoldManifestFile}: ${unknown2.join(", ")}`)}return[...new Set(values)].toSorted()};var selectedSkills3=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var pathLexists=(absolutePath)=>{try{lstatSync8(absolutePath);return true}catch(error2){if(error2 instanceof Error&&"code"in error2&&error2.code==="ENOENT"){return false}throw error2}};var resolveContainedReceiptPath=(rootDirectory,relativePath,{followLeaf=true}={})=>{const absoluteRoot=path33.resolve(rootDirectory);const absolutePath=path33.resolve(absoluteRoot,relativePath);const lexicalRelative=path33.relative(absoluteRoot,absolutePath);if(absolutePath===absoluteRoot||path33.isAbsolute(relativePath)||lexicalRelative===".."||lexicalRelative.startsWith(`..${path33.sep}`)||path33.isAbsolute(lexicalRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}let existingPath=followLeaf?absolutePath:path33.dirname(absolutePath);while(!pathLexists(existingPath)){const parent=path33.dirname(existingPath);if(parent===existingPath){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}existingPath=parent}const realRoot=realpathSync7(absoluteRoot);const realExistingPath=realpathSync7(existingPath);const realRelative=path33.relative(realRoot,realExistingPath);if(realRelative===".."||realRelative.startsWith(`..${path33.sep}`)||path33.isAbsolute(realRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}return absolutePath};var readManifest=(rootDirectory)=>{const manifestPath=path33.join(rootDirectory,scaffoldManifestFile);if(!existsSync15(manifestPath)){throw new Error(`Missing ${scaffoldManifestFile}. Run \`hi scaffold\` first.`)}const manifest=parseManifest(readFileSync15(manifestPath,"utf-8"));const contextPath=manifest.contextPlanFile??manifest.managedFiles?.find((file5)=>file5.kind==="context-plan")?.path;if(contextPath!==undefined){const absolutePath=resolveContainedReceiptPath(rootDirectory,contextPath,{followLeaf:false});if(!pathLexists(absolutePath)){throw new Error(`required-artifact-missing: adopted canonical context ${contextPath}; restore the canonical artifact before reconciliation.`)}if(!lstatSync8(absolutePath).isFile()){throw new Error(`required-artifact-invalid: canonical context ${contextPath} must be a regular file.`)}try{decodeUnknownSync(fromJsonString2(ContextPlan))(readFileSync15(absolutePath,"utf-8"))}catch{throw new Error(`required-artifact-invalid: canonical context ${contextPath} does not satisfy its context-plan contract.`)}}return manifest};var resolveMutableJsonPath=(rootDirectory,relativePath)=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath);if(pathLexists(absolutePath)&&lstatSync8(absolutePath).isSymbolicLink()){throw new Error(`Mutable JSON path must not be a symbolic link: ${relativePath}`)}return absolutePath};var stableJsonStringify=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(stableJsonStringify).join(",")}]`}if(value5!==null&&typeof value5==="object"){const entries=Object.entries(value5).toSorted(([left],[right])=>left.localeCompare(right));return`{${entries.map(([key,entryValue])=>`${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(",")}}`}return JSON.stringify(value5)};var lifecycleHookCommand=(value5)=>{if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return}if(!isRecord11(value5)){return}const record3=value5;if(typeof record3.command==="string"){return record3.command}if(Array.isArray(record3.hooks)){return record3.hooks.map(lifecycleHookCommand).find((command)=>command!==undefined)}return};var managedLifecycleHook=(entry)=>{if(entry.path.length!==2||entry.path[0]!=="hooks"||!Array.isArray(entry.value)){return}const value5=entry.value.length===1?entry.value[0]:undefined;const command=lifecycleHookCommand(value5);return command===undefined?undefined:{command,value:value5}};var contentForDiff=(rootDirectory,relativePath)=>{const absolutePath=path33.join(rootDirectory,relativePath);if(!pathLexists(absolutePath)){return""}const stat3=lstatSync8(absolutePath);if(stat3.isSymbolicLink()){return`symlink:${readlinkSync6(absolutePath)}
2512
2512
  `}return readFileSync15(absolutePath,"utf-8")};var jsonContentEquals=(left,right)=>{try{return stableJsonStringify(JSON.parse(left))===stableJsonStringify(JSON.parse(right))}catch{return false}};var hashPath=(rootDirectory,relativePath,{semanticJson=true}={})=>{const absolutePath=path33.join(rootDirectory,relativePath);if(!pathLexists(absolutePath)){return null}const stat3=lstatSync8(absolutePath);const content=stat3.isSymbolicLink()?`symlink:${readlinkSync6(absolutePath)}`:readFileSync15(absolutePath);return hashManagedFileContent(relativePath,content,{semanticJson})};var addOpencodePromptMirror=(output2,expectedDirectory)=>{const canonicalPrompt=path33.join(expectedDirectory,".agents/AGENTS.md");const opencodePrompt=path33.join(expectedDirectory,".opencode/AGENTS.md");if(existsSync15(canonicalPrompt)&&!pathLexists(opencodePrompt)){mkdirSync6(path33.dirname(opencodePrompt),{recursive:true});symlinkSync("../.agents/AGENTS.md",opencodePrompt);const relativePath=".opencode/AGENTS.md";const managedFile={kind:"harness",ownership:{_tag:"ScaffoldManaged"},path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""};return{...output2,generatedFiles:[...output2.generatedFiles,relativePath],harnessFiles:[...output2.harnessFiles,relativePath],managedFiles:[...output2.managedFiles,managedFile]}}return output2};var ignoredWikiAlignmentRootDirectoryNames=new Set([".next",".nitro",".output",".source",".tanstack",".turbo","build","coverage","dist","node_modules"]);var hasIgnoredWikiAlignmentRootDirectory=(relativePath)=>{const firstSegment=relativePath.split("/").find(Boolean);return firstSegment!==undefined&&ignoredWikiAlignmentRootDirectoryNames.has(firstSegment)};var wikiAlignmentRootDirectories=["apps/wiki","app/wiki","wiki"];var hasIgnoredWikiAlignmentPath=(relativePath)=>wikiAlignmentRootDirectories.some((wikiRoot)=>{const prefix=`${wikiRoot}/`;return relativePath.startsWith(prefix)&&hasIgnoredWikiAlignmentRootDirectory(relativePath.slice(prefix.length))});var collectRelativeFiles2=(rootDirectory,relativeDirectory)=>{const absoluteDirectory=path33.join(rootDirectory,relativeDirectory);if(!existsSync15(absoluteDirectory)){return[]}const files=[];const visit2=(currentDirectory)=>{for(const entry of readdirSync8(currentDirectory,{withFileTypes:true})){const absolutePath=path33.join(currentDirectory,entry.name);const relativePath=path33.relative(rootDirectory,absolutePath).split(path33.sep).join("/");const wikiRelativePath=path33.relative(absoluteDirectory,absolutePath).split(path33.sep).join("/");if(hasIgnoredWikiAlignmentRootDirectory(wikiRelativePath)){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()||entry.isSymbolicLink()){files.push(relativePath)}}};visit2(absoluteDirectory);return files.toSorted()};var copyManagedFile=({fromDirectory,toDirectory,relativePath})=>{const sourcePath=path33.join(fromDirectory,relativePath);const targetPath=path33.join(toDirectory,relativePath);const stat3=lstatSync8(sourcePath);mkdirSync6(path33.dirname(targetPath),{recursive:true});if(existsSync15(targetPath)){rmSync5(targetPath,{force:true,recursive:true})}if(stat3.isSymbolicLink()){symlinkSync(readlinkSync6(sourcePath),targetPath);return}cpSync2(sourcePath,targetPath,{force:true})};var copyManagedPathConfined=async({fromDirectory,outputDirectory,relativePath,session})=>{const sourcePath=path33.join(fromDirectory,relativePath);const targetPath=path33.join(outputDirectory,relativePath);const source=lstatSync8(sourcePath);if(source.isSymbolicLink()){const expectedAbsent=await removeConfinedPath({outputDirectory,recursive:true,session,targetPath});await replaceConfinedSymlink({...expectedAbsent===null?{}:{expectedAbsent},linkTarget:readlinkSync6(sourcePath),outputDirectory,session,targetPath});return}if(source.isDirectory()){await replaceConfinedDirectory({outputDirectory,session,sourceDirectory:sourcePath,targetPath});return}const target=lstatSync8(targetPath,{throwIfNoEntry:false});if(target!==undefined&&(target.isSymbolicLink()||!target.isFile())){await removeConfinedPath({outputDirectory,recursive:true,session,targetPath})}await writeConfinedFile({content:readFileSync15(sourcePath),mode:fileMode2(source.mode),outputDirectory,replace:lstatSync8(targetPath,{throwIfNoEntry:false})!==undefined,session,targetPath})};var hasActionablePackDrift=({finalPacks,resolvedPacks})=>{const recorded=new Set(finalPacks);return resolvedPacks.some((pack)=>!recorded.has(pack))};var acceptResolvedPacks=({baseline,finalPacks,resolvedPacks})=>{const recorded=new Set(finalPacks);const acceptedCategories=new Set(["default","detected"]);const acceptedPackIds=new Set(baseline.packs.filter((pack)=>acceptedCategories.has(pack.category)).map((pack)=>pack.id));const accepted=resolvedPacks.filter((pack)=>!recorded.has(pack)&&acceptedPackIds.has(pack));return[...new Set([...finalPacks,...accepted])].toSorted()};var summarizeCounts2=(changes)=>{const rows=new Map;for(const change of changes){const key=`${change.status} ${change.kind}`;rows.set(key,(rows.get(key)??0)+1)}return[...rows.entries()].toSorted(([left],[right])=>left.localeCompare(right)).map(([label,count])=>`• ${label}: ${count}`)};var summarizeChanges2=(changes)=>{if(changes.length===0){return"No managed file changes."}const sampleSize=20;const sample=changes.slice(0,sampleSize);const remaining=changes.length-sample.length;return[`Total changed managed files: ${changes.length}`,"","By status/kind:",...summarizeCounts2(changes),"","Sample:",...sample.map((change)=>`• ${change.path} (${change.status})`),...remaining>0?[`• ... ${remaining} more omitted from terminal summary`]:[]].join(`
2513
2513
  `)};var summarizeStaleFiles2=(staleFiles)=>{const sampleSize=20;const sample=staleFiles.slice(0,sampleSize);const remaining=staleFiles.length-sample.length;return[`Total stale managed files: ${staleFiles.length}`,"",...sample.map((file5)=>`• ${file5}`),...remaining>0?[`• ... ${remaining} more omitted from terminal summary`]:[]].join(`
2514
2514
  `)};var packDriftPrompt=({rootDirectory,finalPacks,resolvedPacks})=>["You are updating a repo whose current package manifests resolve to a different punks pack set than the recorded scaffold manifest.","",`Repo root: ${rootDirectory}`,`Recorded packs: ${finalPacks.join(", ")}`,`Currently resolved packs: ${resolvedPacks.join(", ")}`,"","Run `hi scaffold` from the repo root and intentionally accept/edit the new pack selection. Activate `writing-for-agents` before editing prompt specs, handoffs, AGENTS.md files, or subagent templates/instructions. Then inspect the generated prompt specs, skills, hooks, and subagent manifests before continuing product work."].join(`
2515
- `);var buildChanges=({rootDirectory,expectedDirectory,expectedFiles,previousFiles})=>{const previousByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));return expectedFiles.flatMap((expected)=>{const currentHash=hashPath(rootDirectory,expected.path);if(currentHash===expected.sha256){return[]}if(currentHash!==null&&expected.path.endsWith(".json")&&jsonContentEquals(contentForDiff(rootDirectory,expected.path),contentForDiff(expectedDirectory,expected.path))){return[]}const previous=previousByPath.get(expected.path);let status2="changed";if(currentHash===null){status2="missing"}else if(previous!==undefined&&currentHash!==previous.sha256){status2="local-edited"}return[{kind:expected.kind,path:expected.path,status:status2}]}).toSorted((left,right)=>left.path.localeCompare(right.path))};var syncSubagentsScriptFile=".agents/scripts/sync-subagents.mjs";var projectAuthoredWikiSyncFile="apps/wiki/scripts/sync-content.mjs";var wikiRouteMetadataPathPattern=/^(?<wikiRoot>apps\/wiki|app\/wiki|wiki)\/content\/docs(?:\/.*)?\/meta\.json$/u;var isProjectAuthoredWikiRouteMetadata=({file:file5,rootDirectory})=>{if(!wikiRouteMetadataPathPattern.test(file5.path)){return false}const wikiRoot=wikiRouteMetadataPathPattern.exec(file5.path)?.groups?.wikiRoot;if(wikiRoot===undefined){return false}return existsSync15(path33.join(rootDirectory,wikiRoot,"scripts","sync-content.mjs"))};var isWikiManagedPath=(relativePath)=>relativePath.startsWith("wiki/")||relativePath.startsWith("app/wiki/")||relativePath.startsWith("apps/wiki/");var canonicalClaudePromptSource=(relativePath)=>relativePath===".claude/CLAUDE.md"?".agents/AGENTS.md":path33.posix.join(path33.posix.dirname(relativePath),"AGENTS.md");var isConsumerOwnedClaudePrompt=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path33.posix.basename(relativePath)!=="CLAUDE.md"){return false}const absolutePath=path33.join(rootDirectory,relativePath);const targetExists=pathLexists(absolutePath);if(targetExists&&lstatSync8(absolutePath).isSymbolicLink()){const currentHash=hashPath(rootDirectory,relativePath);const canonicalTarget=path33.relative(path33.dirname(absolutePath),path33.join(rootDirectory,canonicalClaudePromptSource(relativePath)));return previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="symlink"||(currentHash===null?readlinkSync6(absolutePath)!==canonicalTarget:currentHash!==previousFile.sha256)}return targetExists&&!lstatSync8(absolutePath).isSymbolicLink()&&(previousFile===undefined||recordedFileType!=="file"||hashPath(rootDirectory,relativePath)!==previousFile.sha256)};var isManagedClaudePromptCopy=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path33.posix.basename(relativePath)!=="CLAUDE.md"||previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="file"){return false}const targetPath=path33.join(rootDirectory,relativePath);const sourceRelativePath=canonicalClaudePromptSource(relativePath);const sourcePath=path33.join(rootDirectory,sourceRelativePath);return existsSync15(targetPath)&&lstatSync8(targetPath).isFile()&&existsSync15(sourcePath)&&lstatSync8(sourcePath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&(recordedFileType==="file"||hashContent2(readFileSync15(targetPath))===hashContent2(readFileSync15(sourcePath)))};var isOrphanedManagedClaudePromptCopy=({previousFile,recordedFileType,relativePath,rootDirectory})=>{const targetPath=path33.join(rootDirectory,relativePath);return path33.posix.basename(relativePath)==="CLAUDE.md"&&previousFile!==undefined&&recordedFileType==="file"&&existsSync15(targetPath)&&lstatSync8(targetPath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&!existsSync15(path33.join(rootDirectory,canonicalClaudePromptSource(relativePath)))};var isManagedLegacyClaudeSymlink=({file:file5,rootDirectory,plannedOutputPaths})=>{if(file5.kind!=="harness"||path33.posix.basename(file5.path)!=="CLAUDE.md"||!pathLexists(path33.join(rootDirectory,file5.path))||!lstatSync8(path33.join(rootDirectory,file5.path)).isSymbolicLink()||hashPath(rootDirectory,file5.path)!==file5.sha256){return false}const canonicalSource=path33.join(rootDirectory,canonicalClaudePromptSource(file5.path));return existsSync15(canonicalSource)&&lstatSync8(canonicalSource).isFile()||plannedOutputPaths?.has(file5.path)===true&&readlinkSync6(path33.join(rootDirectory,file5.path))===path33.relative(path33.dirname(path33.join(rootDirectory,file5.path)),canonicalSource)};var hasManagedLegacyClaudeSymlink=({files,relativePath,rootDirectory,plannedOutputPaths})=>{const file5=files.get(relativePath);return file5!==undefined&&isManagedLegacyClaudeSymlink({file:file5,rootDirectory,...plannedOutputPaths===undefined?{}:{plannedOutputPaths}})};var belongsToSeparateReconciliationLane=({file:file5,manifest,receiptFiles,rootDirectory,plannedOutputPaths})=>file5.kind==="context-plan"||file5.kind==="projection-receipt"||file5.kind==="required-tools"||file5.path===agentHandoffFile2||file5.path===agentSystemPromptFile2||isManagedClaudePromptCopy({previousFile:receiptFiles.get(file5.path),recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})||isOrphanedManagedClaudePromptCopy({previousFile:receiptFiles.get(file5.path),recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})||hasManagedLegacyClaudeSymlink({files:receiptFiles,plannedOutputPaths,relativePath:file5.path,rootDirectory})||isWikiManagedPath(file5.path);var isTailoredSyncSubagentsScript=(rootDirectory)=>{const scriptPath=path33.join(rootDirectory,syncSubagentsScriptFile);if(!existsSync15(scriptPath)){return false}const content=readFileSync15(scriptPath,"utf-8");return/["'`](?:app|apps|packages|infra)\//u.test(content)};var isProjectAuthoredManagedFile=({file:file5,rootDirectory})=>{if(isProjectAuthoredWikiRouteMetadata({file:file5,rootDirectory})){return true}if(file5.path===projectAuthoredWikiSyncFile){return existsSync15(path33.join(rootDirectory,file5.path))}if(file5.path===".agents/scripts/sync-subagents.mjs"){return isTailoredSyncSubagentsScript(rootDirectory)}const obligation=file5.obligation??legacyArtifactObligation(file5.path);if(obligation.contentAuthority==="repository"||obligation.contentAuthority==="mixed"){return existsSync15(path33.join(rootDirectory,file5.path))}return file5.path===".claude/CLAUDE.md"||file5.path===".codex/AGENTS.md"||file5.path===".opencode/AGENTS.md"};var buildLegacyRequiredToolsPromptChanges=({rootDirectory})=>{const promptFiles=[agentHandoffFile2,agentSystemPromptFile2];return promptFiles.flatMap((promptFile)=>{const absolutePath=path33.join(rootDirectory,promptFile);if(!existsSync15(absolutePath)){return[]}const current=readFileSync15(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return[]}return[{kind:"handoff",path:promptFile,status:"local-edited"}]})};var rewriteLegacyRequiredToolsPrompt=async({rootDirectory,relativePath,session})=>{const absolutePath=path33.join(rootDirectory,relativePath);const currentBytes=await readConfinedRegularFile({allowMissing:true,outputDirectory:rootDirectory,session,targetPath:absolutePath});if(currentBytes===null){return}const current=currentBytes.toString("utf-8");if(!current.includes(legacyRequiredToolsFile)){return}await writeConfinedFile({content:current.replaceAll(legacyRequiredToolsFile,repoSettingsDisplayFile),outputDirectory:rootDirectory,replace:true,session,targetPath:absolutePath})};var copyIfExists=({rootDirectory,targetDirectory,relativePath,ignoreGeneratedRootDirectories=false})=>{const sourcePath=path33.join(rootDirectory,relativePath);if(!existsSync15(sourcePath)){return}const targetPath=path33.join(targetDirectory,relativePath);const stat3=lstatSync8(sourcePath);mkdirSync6(path33.dirname(targetPath),{recursive:true});if(stat3.isSymbolicLink()){symlinkSync(readlinkSync6(sourcePath),targetPath);return}cpSync2(sourcePath,targetPath,{filter:(source)=>{const relativeSource=path33.relative(sourcePath,source).split(path33.sep).join("/");return!ignoreGeneratedRootDirectories||!hasIgnoredWikiAlignmentRootDirectory(relativeSource)},recursive:true,verbatimSymlinks:true})};var readWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path33.join(wikiDirectory,"wiki-framework.md");if(!existsSync15(pinPath)){return"next"}const content=readFileSync15(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}return"next"};var wikiRootForAlignment=(rootDirectory,detection,hasRootMarkers)=>{if(hasRootMarkers("apps/wiki")){return"apps/wiki"}if(hasRootMarkers("app/wiki")){return"app/wiki"}if(existsSync15(path33.join(rootDirectory,"apps/wiki"))){return"apps/wiki"}if(existsSync15(path33.join(rootDirectory,"wiki"))){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var buildWikiAlignment=async({rootDirectory,detection,expectedDirectory,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const hasWikiRootMarkers2=(relativeRoot)=>{const absoluteRoot=path33.join(rootDirectory,relativeRoot);return["package.json","backlog-provider.md","wiki-framework.md"].some((marker)=>existsSync15(path33.join(absoluteRoot,marker)))};const wikiRoot=wikiRootForAlignment(rootDirectory,detection,hasWikiRootMarkers2);copyIfExists({ignoreGeneratedRootDirectories:true,relativePath:wikiRoot,rootDirectory,targetDirectory:expectedDirectory});copyIfExists({relativePath:"docs",rootDirectory,targetDirectory:expectedDirectory});const wikiFramework=readWikiFrameworkPin(path33.join(expectedDirectory,wikiRoot));await scaffoldWikiForDirectory({monorepo:wikiRoot==="apps/wiki",outputDirectory:expectedDirectory,wikiFramework});const syncScript=path33.join(expectedDirectory,wikiRoot,"scripts","sync-content.mjs");if(existsSync15(syncScript)){runJavaScriptFileSync({cwd:expectedDirectory,file:syncScript,...scriptEnvironment===undefined?{}:{environment:scriptEnvironment},...scriptRuntimePath2===undefined?{}:{runtimePath:scriptRuntimePath2}})}const expectedFiles=collectRelativeFiles2(expectedDirectory,wikiRoot).map((relativePath)=>({kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""}));return{changes:buildChanges({expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedDirectory,expectedFiles}};var readValidatedWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path33.join(wikiDirectory,"wiki-framework.md");if(!existsSync15(pinPath)){return"next"}const content=readFileSync15(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}throw new Error(`Invalid wiki framework pin: ${pinPath}`)};var buildGitignoreCleanup=async({rootDirectory,expectedDirectory})=>{const relativePath=".gitignore";if(!existsSync15(path33.join(rootDirectory,relativePath))){return[]}copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory});const cleanup=await removeHarnessDirectoriesFromGitignore(expectedDirectory,({content,gitignorePath})=>{writeFileSync7(gitignorePath,content)});if(cleanup.removedPatterns.length===0){return[]}const expectedFile={kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})};var semanticFile=({content,encoding="utf-8",kind="harness",mode=420,path:relativePath})=>({content,encoding,kind,...encoding==="symlink"?{}:{mode},obligation:producerObligation("baseline",[version2]),path:relativePath,provenance:{revision:version2,source:"scaffold-semantics"}});var isJsonValue=(value5)=>{if(value5===null||typeof value5==="boolean"||typeof value5==="number"||typeof value5==="string"){return true}if(Array.isArray(value5)){return value5.every(isJsonValue)}return typeof value5==="object"&&Object.values(value5).every(isJsonValue)};var isJsonObject2=(value5)=>isJsonValue(value5)&&typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var isStringArray2=(value5)=>Array.isArray(value5)&&value5.every((entry)=>typeof entry==="string");var projectionSemanticState=({desiredState})=>{const files=new Map;const structuredEntries=[];for(const projection of desiredState.projections){for(const action2 of projection.actions){const applyFileSemantics=()=>{if(action2.operation==="use-native-mirror"&&typeof action2.nativePath==="string"&&typeof action2.canonicalPath==="string"){const nativeRoot=`${action2.nativePath.split("/skills/")[0]}/skills`;const canonicalRoot=`${action2.canonicalPath.split("/skills/")[0]}/skills`;files.set(nativeRoot,semanticFile({content:path33.posix.relative(path33.posix.dirname(nativeRoot),canonicalRoot),encoding:"symlink",path:nativeRoot}))}if(action2.operation==="mirror"&&action2.id.includes(":lifecycle-hook:")&&typeof action2.source==="string"&&typeof action2.target==="string"&&action2.source!==action2.target){files.set(action2.target,semanticFile({content:path33.posix.relative(path33.posix.dirname(action2.target),action2.source),encoding:"symlink",kind:action2.target.includes("/hooks/")?"hook":"harness",path:action2.target}))}if(action2.operation==="merge-json"&&typeof action2.file==="string"&&isStringArray2(action2.path)&&isJsonValue(action2.value)){const value5=action2.file===".claude/settings.json"?[action2.value]:action2.value;structuredEntries.push({file:action2.file,kind:"field",path:action2.path,provenance:{revision:version2,source:"harness-projection"},value:value5})}};applyFileSemantics();const applyJsonKeySemantics=()=>{if(action2.operation==="merge-json"&&typeof action2.target==="string"&&action2.file===undefined&&!action2.target.includes("#")&&isJsonObject2(action2.value)){for(const[key,value5]of Object.entries(action2.value)){if(action2.target==="opencode.json"&&key==="formatter"&&isJsonObject2(value5)&&"harness-format-edited-file"in value5){structuredEntries.push({file:action2.target,kind:"key",path:["formatter","harness-format-edited-file"],provenance:{revision:version2,source:"harness-projection"},value:value5["harness-format-edited-file"]});continue}structuredEntries.push({file:action2.target,kind:"key",path:[key],provenance:{revision:version2,source:"harness-projection"},value:value5})}}};applyJsonKeySemantics();const applyHookConfigSemantics=()=>{const{config}=action2;if(action2.operation==="mirror"&&isJsonObject2(config)&&typeof config.path==="string"&&typeof config.event==="string"&&typeof config.command==="string"&&(config.timeout===undefined||typeof config.timeout==="number")){structuredEntries.push({file:config.path,kind:"field",path:["hooks",config.event],provenance:{revision:version2,source:"harness-projection"},value:[{command:config.command,...config.timeout===undefined?{}:{timeout:config.timeout}}]})}};applyHookConfigSemantics()}}const codexHookActions=desiredState.projections.flatMap(({actions})=>actions).filter((action2)=>action2.operation==="merge-toml"&&action2.id.includes(":lifecycle-hook:"));const applyCodexHookSemantics=()=>{if(codexHookActions.length===0){return}const hasUpdateCheck=codexHookActions.some((action2)=>action2.id.includes("scaffold-update-check"));const hasFormatHook=codexHookActions.some((action2)=>action2.id.includes("format-edited-file"));const lines2=["[agents]","max_depth = 1","","[features]","hooks = true","","[hooks]"];if(hasUpdateCheck||hasFormatHook){const hooks=[...hasUpdateCheck?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs\\" codex", statusMessage = "Checking Harness scaffold", timeout = 60 },']:[],...hasFormatHook?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" session-start", statusMessage = "Capturing edited-file baseline", timeout = 30 },']:[]];lines2.push("SessionStart = [",' { matcher = "startup|resume", hooks = [',...hooks," ] },","]")}if(hasFormatHook){lines2.push("PostToolUse = [",' { matcher = "Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit", hooks = [',' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" post", statusMessage = "Auto-formatting edited files", timeout = 30 },'," ] },","]")}lines2.push("");files.set(".codex/config.toml",semanticFile({content:lines2.join(`
2516
- `),path:".codex/config.toml"}))};applyCodexHookSemantics();return{files:[...files.values()],structuredEntries}};var wikiRootForDetection=(detection)=>{const detectedManifestPaths=new Set(detection.manifests.map(({relativePath})=>relativePath.split(path33.sep).join("/")));if(detectedManifestPaths.has("apps/wiki/package.json")){return"apps/wiki"}if(detectedManifestPaths.has("app/wiki/package.json")){return"app/wiki"}if(detectedManifestPaths.has("wiki/package.json")){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var wikiSemanticState=({detection,finalPacks,framework,settings})=>{if(!finalPacks.includes("docs")){return{files:[],structuredEntries:[]}}const wikiRoot=wikiRootForDetection(detection);const template=makeWikiScaffoldTemplate(wikiRoot,framework);const files=[...template.files.map((file5)=>semanticFile({...file5,path:path33.posix.join(wikiRoot,file5.path)})),...template.rawSubdirectories.map((directory3)=>semanticFile({content:"",path:path33.posix.join(wikiRoot,"raw",directory3,".gitkeep")})),semanticFile({content:"",path:path33.posix.join(wikiRoot,"content/docs/project/.gitkeep")}),semanticFile({content:"",path:path33.posix.join(wikiRoot,"specs/.gitkeep")}),semanticFile({content:"AGENTS.md",encoding:"symlink",path:path33.posix.join(wikiRoot,"CLAUDE.md")}),semanticFile({content:template.indexMarkdown,path:path33.posix.join(wikiRoot,"index.md")}),semanticFile({content:template.logMarkdown,path:path33.posix.join(wikiRoot,"log.md")}),semanticFile({content:renderBacklogProviderMarkdown(settings.backlogProvider),path:path33.posix.join(wikiRoot,"backlog-provider.md")}),semanticFile({content:renderWikiFrameworkMarkdown(framework),path:path33.posix.join(wikiRoot,"wiki-framework.md")})];return{files,structuredEntries:[]}};var lintOwnedWikiConfigPath=(desiredState,detection)=>{const file5=path33.posix.join(wikiRootForDetection(detection),"oxlint.config.ts");return desiredState.files.some(({path:relativePath})=>relativePath===file5)?file5:undefined};var semanticDesiredState=({desiredState,detection,finalPacks,wikiFramework,settings})=>{const projection=projectionSemanticState({desiredState});const wiki=wikiSemanticState({detection,finalPacks,framework:wikiFramework,settings});const lintOwnedWikiConfig=lintOwnedWikiConfigPath(desiredState,detection);return{files:[...projection.files,...wiki.files.filter(({path:relativePath})=>relativePath!==lintOwnedWikiConfig)],structuredEntries:[...projection.structuredEntries,...wiki.structuredEntries]}};var desiredFileBytes=(file5)=>file5.encoding==="base64"?Buffer.from(file5.content,"base64"):file5.content;var desiredFileFingerprint=(file5)=>JSON.stringify({mode:file5.mode===undefined?null:fileMode2(file5.mode),sha256:hashContent2(file5.encoding==="symlink"?`symlink:${file5.content}`:desiredFileBytes(file5)),type:file5.encoding==="symlink"?"symlink":"file"});var observeManagedFile=({expectedMode,kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const projectAuthored=isProjectAuthoredManagedFile({file:{kind,path:relativePath,sha256:""},rootDirectory});if(!pathLexists(absolutePath)){return{fingerprint:"missing",kind,mode:null,path:relativePath,projectAuthored,sha256:null,type:"missing"}}const stat3=lstatSync8(absolutePath);if(!stat3.isSymbolicLink()&&!stat3.isFile()){return{fingerprint:JSON.stringify({mode:null,sha256:null,type:"other"}),kind,mode:fileMode2(stat3.mode),path:relativePath,projectAuthored,sha256:null,type:"other"}}const isSymlink=stat3.isSymbolicLink();const symlinkTarget=isSymlink?readlinkSync6(absolutePath):undefined;const bytes=isSymlink?undefined:readFileSync15(absolutePath);const sha256=hashContent2(isSymlink?`symlink:${symlinkTarget}`:bytes??"");const mode=isSymlink?null:fileMode2(stat3.mode);return{...isSymlink?{content:symlinkTarget??""}:{content:(bytes??Buffer.from("")).toString("utf-8")},fingerprint:JSON.stringify({mode:expectedMode===undefined||isSymlink?null:mode,sha256,type:isSymlink?"symlink":"file"}),kind,mode,path:relativePath,projectAuthored,sha256,type:isSymlink?"symlink":"file"}};var deriveDesiredOwnershipEvidence=fn2("Update.deriveDesiredOwnershipEvidence")(function*deriveDesiredOwnershipEvidence2(desiredState,rootDirectory){const entries=yield*all2(desiredState.files.flatMap((file5)=>file5.projectProducer===undefined?[]:[deriveProjectGeneratedOwnership({declaration:file5.projectProducer,repositoryRoot:rootDirectory}).pipe(map6((ownership)=>[file5.path,ownership]))])).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));return new Map(entries)});var ownershipObservation=(observed)=>{if(observed===undefined||observed.type==="missing"){return{_tag:"Missing"}}if(observed.type==="file"&&observed.mode!==null&&observed.sha256!==null){return{_tag:"Present",fingerprint:{_tag:"File",mode:observed.mode,sha256:observed.sha256}}}if(observed.type==="symlink"&&observed.content!==undefined&&observed.sha256!==null){return{_tag:"Present",fingerprint:{_tag:"Symlink",sha256:observed.sha256,target:observed.content}}}return{_tag:"Unsupported"}};var resolveFileOwnership=({desiredOwnership,file:file5,observed,receiptPresent,receiptOwnership,rootDirectory,scope:scope3})=>{const obligation=file5.obligation??legacyArtifactObligation(file5.path);const hasUnknownAuthority=()=>obligation.contentAuthority==="unknown"&&desiredOwnership===undefined&&receiptOwnership?._tag!=="ProjectGenerated";if(hasUnknownAuthority()){return"ownership-unknown"}const resolution=resolveManagedFileOwnership({...desiredOwnership===undefined?{}:{desiredOwnership},observed:ownershipObservation(observed),...receiptOwnership===undefined?{}:{receiptOwnership},scope:scope3});if(receiptPresent&&path33.posix.basename(file5.path)==="CLAUDE.md"&&!existsSync15(path33.join(rootDirectory,canonicalClaudePromptSource(file5.path)))){return resolution}if(receiptOwnership?._tag==="ProjectGenerated"&&desiredOwnership?._tag!=="ProjectGenerated"){return resolution}if(resolution!=="scaffold-managed"||scope3==="semantic-overlap"){return resolution}if(observed?.projectAuthored!==true&&!isProjectAuthoredManagedFile({file:{...file5,sha256:""},rootDirectory})){return resolution}if(file5.path===projectAuthoredWikiSyncFile&&(observed===undefined||observed.type==="missing")){return"scaffold-managed"}return"project-generated-current"};var packageFileForWorkspace=(workspace)=>workspace==="."?"package.json":path33.posix.join(workspace,"package.json");var compileManagedOwnershipDecisions=({candidateFiles,desiredOwnershipEvidence,desiredState,manifest,observedState,rootDirectory,semanticState})=>{const desiredFiles=new Map([...candidateFiles,...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const receiptFiles=new Map((manifest.managedFiles??[]).map((file5)=>[file5.path,file5]));const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));for(const file5 of candidateFiles){if(!observedFiles.has(file5.path)){observedFiles.set(file5.path,observeManagedFile({kind:file5.kind,relativePath:file5.path,rootDirectory}))}}const semanticPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5),...semanticState.structuredEntries.map(({file:file5})=>file5)]);const managedClaudeCopyPaths=new Set([...receiptFiles.values()].filter((file5)=>isManagedClaudePromptCopy({previousFile:file5,recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})).map(({path:relativePath})=>relativePath));const managedClaudeCanonicalSourcePaths=new Set([...managedClaudeCopyPaths].map(canonicalClaudePromptSource).filter((relativePath)=>{const previousFile=receiptFiles.get(relativePath);return desiredFiles.has(relativePath)&&previousFile!==undefined&&hashPath(rootDirectory,relativePath)===previousFile.sha256}));const paths=new Set([...desiredFiles.keys(),...receiptFiles.keys()]);return new Map([...paths].map((relativePath)=>{const desired=desiredFiles.get(relativePath);const desiredOwnership=desiredOwnershipEvidence.get(relativePath);const receipt=receiptFiles.get(relativePath);const file5=desired??receipt;if(file5===undefined){throw new Error(`Managed ownership path has no file evidence: ${relativePath}`)}if(desiredOwnership===undefined&&(managedClaudeCopyPaths.has(relativePath)||managedClaudeCanonicalSourcePaths.has(relativePath))){return[relativePath,"scaffold-managed"]}return[relativePath,resolveFileOwnership({...desiredOwnership===undefined?{}:{desiredOwnership},file:file5,observed:observedFiles.get(relativePath),receiptPresent:receipt!==undefined,...receipt?.ownership===undefined?{}:{receiptOwnership:receipt.ownership},rootDirectory,scope:semanticPaths.has(relativePath)?"semantic-overlap":"whole-file"})]}))};var readJsonObject=(absolutePath)=>{try{const value5=JSON.parse(readFileSync15(absolutePath,"utf-8"));return isRecord11(value5)?value5:null}catch{return null}};var readRequiredJsonObject=(absolutePath,description)=>{const value5=readJsonObject(absolutePath);if(value5===null){throw new Error(`${description}: ${absolutePath}`)}return value5};var managedFileOwnershipEntry=(ownership)=>ownership===undefined?{}:{ownership};var applyManagedLifecycleHook=({action:action2,entryFile,leaf,parent,priorEntry})=>{const desiredHook=action2._tag==="SafeRemoveScaffoldEntry"?undefined:managedLifecycleHook(action2.desired);let previousHook;if(action2._tag==="SafeRemoveScaffoldEntry"){previousHook=managedLifecycleHook(action2.previous)}else if(priorEntry!==undefined){previousHook=managedLifecycleHook(priorEntry)}const managedHook=desiredHook??previousHook;if(managedHook===undefined){return false}const current=parent[leaf];if(current!==undefined&&!isUnknownArray(current)){throw new Error(`Lifecycle hook configuration is not an array: ${entryFile}`)}const previousValue=(previousHook??desiredHook)?.value;let removedPrevious=false;const consumerHooks=(current??[]).filter((hook)=>{if(!removedPrevious&&previousValue!==undefined&&stableJsonStringify(hook)===stableJsonStringify(previousValue)){removedPrevious=true;return false}return true});if(action2._tag==="SafeRemoveScaffoldEntry"){if(consumerHooks.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=consumerHooks}}else{parent[leaf]=[...consumerHooks,(desiredHook??managedHook).value]}return true};var receiptForFile=({kind,ownership,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync8(absolutePath);const type2=stat3.isSymbolicLink()?"symlink":"file";return{kind,mode:type2==="symlink"?null:fileMode2(stat3.mode),ownership:ownership?._tag==="ProjectGenerated"?ownership:{_tag:"ScaffoldManaged"},path:relativePath,sha256:hashPath(rootDirectory,relativePath)??"",type:type2}};var matchesProjectGeneratedOutput=({ownership,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync8(absolutePath);const expected=ownership.evidence.outputFingerprint;if(stat3.isSymbolicLink()){if(expected._tag!=="Symlink"){return false}const target=readlinkSync6(absolutePath);return target===expected.target&&createHash12("sha256").update(`symlink:${target}`).digest("hex")===expected.sha256}return stat3.isFile()&&expected._tag==="File"&&fileMode2(stat3.mode)===expected.mode&&createHash12("sha256").update(readFileSync15(absolutePath)).digest("hex")===expected.sha256};var writeJsonDocument=async({absolutePath,document,rootDirectory,session})=>{await writeConfinedFile({content:encodePrettyJson2(document),outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"||action2._tag==="ArchiveAndReplaceScaffoldFile"?"update":"remove"};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){const stderr=result4.stderr.trim();if(result4.error!==undefined){throw new Error(result4.error.message)}throw new Error(stderr.length>0?stderr:`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path33.join(rootDirectory,lockfile);return[absolutePath,existsSync15(absolutePath)?readFileSync15(absolutePath):null]}));var restoreDependencyLockfiles=async(rootDirectory,snapshot,session)=>{for(const[absolutePath,content]of snapshot){if(content===null){await removeConfinedPath({outputDirectory:rootDirectory,recursive:false,session,targetPath:absolutePath})}else{await writeConfinedFile({content,outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})}}};var scaffoldApplicatorFailure=(action2,cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:action2.item,message:cause instanceof Error?cause.message:"Scaffold application failed.",operation:publicReconciliationOperation(action2)});var scaffoldReceiptFailure=(cause)=>new ScaffoldApplicationFailure({cause,identity:"managed-scaffold-receipt",item:"receipt",message:cause instanceof Error?cause.message:"Scaffold receipt persistence failed.",operation:"persist"});var makeScaffoldReconciliationApplicators=({dependencyProcess,desiredOwnershipEvidence,priorReceipt,rootDirectory,session})=>({applyDependency:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=isRecord11(sectionValue)?sectionValue:{};const previousPackageManifest=readFileSync15(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;await writeJsonDocument({absolutePath,document,rootDirectory,session});const installationCommand=dependencyInstallationCommand(rootDirectory);if(installationCommand!==null){try{dependencyProcess(installationCommand[0],installationCommand[1],rootDirectory)}catch(error2){await writeConfinedFile({content:previousPackageManifest,outputDirectory:rootDirectory,replace:true,session,targetPath:absolutePath});await restoreDependencyLockfiles(rootDirectory,lockfileSnapshot,session);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;let absolutePath;try{absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false})}catch(error2){throw new CliValidationError({cause:error2,message:error2 instanceof Error?error2.message:`Managed receipt path is unsafe: ${relativePath}`})}if(action2._tag==="SafeRemoveScaffoldEntry"){await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session,targetPath:absolutePath});return null}const{desired}=action2;if(desired.encoding==="symlink"){const expectedAbsent=await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session,targetPath:absolutePath});await replaceConfinedSymlink({...expectedAbsent===null?{}:{expectedAbsent},linkTarget:desired.content,outputDirectory:rootDirectory,session,targetPath:absolutePath})}else{if(pathLexists(absolutePath)&&lstatSync8(absolutePath).isSymbolicLink()){await removeConfinedPath({outputDirectory:rootDirectory,recursive:false,session,targetPath:absolutePath})}await writeConfinedFile({content:desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content,...desired.mode===undefined?{}:{mode:fileMode2(desired.mode)},outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})}const desiredOwnership=desiredOwnershipEvidence.get(relativePath);const ownership=desiredOwnership!==undefined&&matchesProjectGeneratedOutput({ownership:desiredOwnership,relativePath,rootDirectory})?desiredOwnership:undefined;return{...receiptForFile({kind:desired.kind,...ownership===undefined?{}:{ownership},relativePath,rootDirectory}),...desired.obligation===undefined?{}:{obligation:desired.obligation},...desired.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:desired.sharedPromptIdentity}}}}),applyStructuredEntry:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync15(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(segment==="workspaces"&&Array.isArray(value5)&&isOxlintCatalogStructuredEntry2(entry)){const child={packages:value5};parent[segment]=child;parent=child}else if(isRecord11(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";if(entry.kind==="required-shell-segment"){const command=entry.value;const current=parent[leaf];if(typeof command!=="string"||current!==undefined&&typeof current!=="string"){throw new Error(`Required shell segment is not a string: ${entry.file}`)}if(action2._tag==="SafeRemoveScaffoldEntry"){const next=removeShellAndCommandSegment(current??"",command);if(next.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=next}}else{const priorEntry2=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const retained=action2._tag==="SafeUpdateScaffoldEntry"&&priorEntry2?.kind==="required-shell-segment"&&typeof priorEntry2.value==="string"&&priorEntry2.value!==command?removeShellAndCommandSegment(current??"",priorEntry2.value):current??"";parent[leaf]=appendShellAndCommandSegment(retained,command)}await writeJsonDocument({absolutePath,document,rootDirectory,session});return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}await writeJsonDocument({absolutePath,document,rootDirectory,session});return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),archiveAndReplaceFile:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const replacement=action2.desired.encoding==="symlink"?{_tag:"Symlink",linkTarget:action2.desired.content}:{_tag:"File",content:action2.desired.encoding==="base64"?Buffer.from(action2.desired.content,"base64"):action2.desired.content,...action2.desired.mode===undefined?{}:{mode:fileMode2(action2.desired.mode)}};await archiveAndReplaceConfinedFile({archiveDirectory:path33.join(rootDirectory,".devpunks/replaced-scaffold"),outputDirectory:rootDirectory,replacement,session,targetPath:resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false})});const observed=receiptForFile({kind:action2.desired.kind,relativePath:action2.identity,rootDirectory});return observed.type==="symlink"?{mode:null,sha256:observed.sha256,type:"symlink"}:{mode:observed.mode??fileMode2(lstatSync8(resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false})).mode),sha256:observed.sha256,type:"file"}}}),persistReceipt:(receipt)=>tryPromise2({catch:scaffoldReceiptFailure,try:async()=>{const manifestPath=path33.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,ownership,path:relativePath,sha256,obligation,sharedPromptIdentity})=>({...obligation===undefined?{}:{obligation},...sharedPromptIdentity===undefined?{}:{sharedPromptIdentity},kind,...ownership?._tag==="ProjectGenerated"?{ownership}:{},path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;await writeJsonDocument({absolutePath:manifestPath,document:manifest,rootDirectory,session})}}),verifyFile:(action2)=>try_3({catch:(cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:"file",message:cause instanceof Error?cause.message:"Scaffold output verification failed.",operation:publicReconciliationOperation(action2)}),try:()=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){if(pathLexists(absolutePath)){throw new Error(`Removed scaffold output is still present: ${action2.identity}`)}return}const{desired}=action2;const stat3=lstatSync8(absolutePath);const expectedSymlink=desired.encoding==="symlink";if(stat3.isSymbolicLink()!==expectedSymlink||!expectedSymlink&&!stat3.isFile()||hashPath(rootDirectory,action2.identity,{semanticJson:false})!==nodeScaffoldContentHasher.sha256(desired)||!expectedSymlink&&desired.mode!==undefined&&fileMode2(stat3.mode)!==fileMode2(desired.mode)){throw new Error(`Scaffold output failed current-state verification: ${action2.identity}`)}}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var reconciliationActionPath=(action2)=>{if(action2.item==="file"){return action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path}if(action2.item==="structured-entry"){return action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file}return packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace)};var publicReconciliationActions=(plan,blockedPaths=new Set)=>plan.actions.filter((action2)=>!blockedPaths.has(reconciliationActionPath(action2))).map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index,segment]of entry.path.entries()){if(Array.isArray(value5)&&index===1&&isOxlintCatalogStructuredEntry2(entry)){return{_tag:"MissingStructuredObservation"}}if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=isRecord11(value5)?value5[segment]:undefined}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!isUnknownArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>isJsonValue(candidate)&&stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}if(entry.kind==="required-shell-segment"){if(typeof value5!=="string"||typeof entry.value!=="string"){return{_tag:"InvalidStructuredObservation",message:`Required shell segment is not a string: ${entry.file}`}}if(hasBackgroundedShellCommandSegment(value5,entry.value)){return{_tag:"InvalidStructuredObservation",message:`Lint setup cannot safely compose ${entry.file} ${entry.path.join(".")}.`}}return hasShellAndCommandSegment(value5,entry.value)?{_tag:"PresentStructuredObservation",value:entry.value}:{_tag:"MissingStructuredObservation"}}if(!isJsonValue(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured value is not valid JSON: ${entry.file}`}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const desiredStructuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries].map((entry)=>[structuredObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredStructuredEntries.values(),...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync15(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=isRecord11(section2)?section2[dependency.name]:undefined;if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync15(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const desiredEntry=desiredStructuredEntries.get(identity3);const desiredObservation=desiredEntry?.kind==="required-shell-segment"?observeStructuredValue(document,desiredEntry):undefined;const observationEntry=entry.kind==="required-shell-segment"&&desiredEntry?.kind==="required-shell-segment"&&desiredObservation?._tag==="PresentStructuredObservation"&&(entry.value===desiredEntry.value||observeStructuredValue(document,entry)._tag==="MissingStructuredObservation")?desiredEntry:entry;const observation=observeStructuredValue(document,observationEntry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));const rootPackageJson=readJsonObject(path33.join(rootDirectory,"package.json"));const workspaces=rootPackageJson?.workspaces;const catalog=isJsonObject2(workspaces)?workspaces.catalog:undefined;const legacyOxlintCatalogValue=isJsonObject2(catalog)?catalog.oxlint:undefined;const legacyOxlintCatalogReceipt=typeof legacyOxlintCatalogValue==="string"&&(manifest.managedDependencies??[]).some(({name:name2,version:dependencyVersion})=>(name2==="@effect/tsgo"||name2==="oxlint-tsgolint")&&dependencyVersion==="catalog:")?[{file:"package.json",kind:"field",path:["workspaces","catalog","oxlint"],value:legacyOxlintCatalogValue}]:[];return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync8(absolutePath).isFile()?fileMode2(lstatSync8(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&&currentMode!==undefined&&desiredMode!==undefined&&currentMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},ownership:file5.ownership,...file5.obligation===undefined?{}:{obligation:file5.obligation},...file5.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:file5.sharedPromptIdentity},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:[...(manifest.managedStructuredEntries??[]).flatMap((entry)=>isJsonValue(entry.value)?[{...entry,value:entry.value}]:[]),...legacyOxlintCatalogReceipt],version:"1"}};var changeStatus=({ownershipDecisions,path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);if(previous?.ownership?._tag==="ProjectGenerated"&&ownershipDecisions.get(relativePath)==="scaffold-managed"){return"local-edited"}return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compileUpdateContext=fn2("Update.compileContext")(function*compileUpdateContext2(options4,check2){if(check2){return yield*assessScaffoldContextPlan(options4)}return{_tag:"ContextPlanAssessment",blockedQualityConsumers:[],contextPlan:yield*compileScaffoldContextPlan(options4)}});var qualityConsumerFindings=(consumers)=>consumers.map(({scopeId,contribution:contribution2,cause})=>({code:"quality-contract-incomplete",component:"quality",consumers:[`commit-gate-verification:${scopeId}`],contribution:contribution2,detail:`${cause.message} Missing Commit Gate commands: ${cause.missing.join(", ")}.`,scopeId,status:"blocked"}));var contextPlanMatchesDesired=(desiredState,manifest,rootDirectory)=>{const relativePath=manifest.contextPlanFile??manifest.managedFiles?.find(({kind})=>kind==="context-plan")?.path;if(relativePath===undefined){return false}const observed=decodeUnknownOption2(ContextPlan)(readJsonObject(resolveContainedReceiptPath(rootDirectory,relativePath)));if(isNone2(observed)){return false}const normalized=compileDesiredScaffoldState({baseline:{...desiredState.baseline,dependencies:[],files:[],structuredEntries:[]},contextPlan:observed.value,projections:[],settings:desiredState.settings});return normalized._tag==="DesiredScaffoldStateCompiled"&&stableJsonStringify(normalized.state.contextPlan)===stableJsonStringify(desiredState.contextPlan)};var scopedAuthoringFindings=(contextPlan,rootDirectory,projectionReceiptFile)=>{const receipt=projectionReceiptFile===undefined?null:readJsonObject(resolveContainedReceiptPath(rootDirectory,projectionReceiptFile));return assessScopedAuthoring({contextPlan,proofs:readScopedAuthoringProofs(receipt)}).map((action2)=>({code:action2.trigger==="compatibility-unknown"?"scoped-authoring-compatibility-unknown":"scoped-authoring-pending",component:"artifact",consumers:["scoped-guidance",...action2.allowedAgentIds],dependencies:[action2.inputIdentity],detail:`Scope ${action2.scopeId} requires bounded authoring for ${action2.inputIdentity}: ${action2.trigger}.`,path:action2.allowedOutputs[0]??agentHandoffFile2,producer:"bounded-scoped-authoring",scopeId:action2.scopeId,status:action2.trigger==="compatibility-unknown"?"unknown":"pending"}))};var blockQualityDependentFindings=(findings,qualityFindings,contextPaths)=>{if(qualityFindings.length===0){return findings}const contributions=qualityFindings.flatMap((finding)=>finding.contribution===undefined?[]:[finding.contribution.id]);return findings.map((finding)=>{if(!contextPaths.includes(finding.path)&&finding.dependencies?.some((dependency)=>contributions.includes(dependency))!==true){return finding}return{...finding,code:"artifact-dependent-quality-blocked",consumers:[...finding.consumers,...qualityFindings.flatMap((quality)=>quality.consumers)],detail:`${finding.path??"Artifact"} depends on an unresolved quality contribution: ${contributions.join(", ")}.`,status:"blocked"}})};var qualityBlockedPaths=(findings)=>new Set(findings.flatMap((finding)=>finding.code==="artifact-dependent-quality-blocked"&&finding.path!==undefined?[finding.path]:[]));var assessQualityComparison=(comparison,qualityFindings,contextPaths)=>{const obligationFindings=blockQualityDependentFindings(comparison.obligationFindings,qualityFindings,contextPaths);const blockedPaths=qualityBlockedPaths(obligationFindings);return{changedFiles:comparison.changedFiles.filter(({path:relativePath})=>!blockedPaths.has(relativePath)),obligationFindings,staleFiles:comparison.staleFiles.filter((relativePath)=>!blockedPaths.has(relativePath))}};var compareObservedState=({desiredState,manifest,observedState,ownershipDecisions,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);const comparableFiles=new Map([...semanticState.files.filter((file5)=>!entryOwnedPaths.has(file5.path)),...desiredState.files].map((file5)=>[file5.path,file5]));const compareReceiptFile=(file5)=>{if(comparableFiles.has(file5.path)){return}const obligation=file5.obligation??legacyArtifactObligation(file5.path);const observed=observedFiles.get(file5.path);if(obligation.presence==="optional"&&(observed===undefined||observed.type==="missing")){return}if(obligation.contentAuthority==="unknown"){addChange({kind:file5.kind,path:file5.path,status:"local-edited"});return}if(obligation.contentAuthority==="repository"&&obligation.presence==="required"&&(observed===undefined||observed.type==="missing"||observed.content?.trim().length===0)){addChange({kind:file5.kind,path:file5.path,status:observed===undefined||observed.type==="missing"?"missing":"local-edited"})}};const compareDesiredFile=(file5)=>{const observed=observedFiles.get(file5.path);const ownershipDecision=ownershipDecisions.get(file5.path);if(file5.obligation?.presence==="optional"&&(observed===undefined||observed.type==="missing")){return}if(ownershipDecision==="ownership-unknown"){addChange({kind:file5.kind,path:file5.path,status:"local-edited"});return}const hasInvalidRequiredContent=()=>file5.obligation?.presence==="required"&&(observed===undefined||observed.type==="missing"||file5.obligation.validity==="authored-content"&&observed.content?.trim().length===0);const invalidRequiredContent=hasInvalidRequiredContent();if(invalidRequiredContent){addChange({kind:file5.kind,path:file5.path,status:observed===undefined||observed.type==="missing"?"missing":"local-edited"});return}if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||ownershipDecision==="project-generated-current"){return}if(ownershipDecision==="project-generated-missing"||ownershipDecision==="project-generated-stale"){addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,ownershipDecisions,path:file5.path,previousFiles})});return}const hasEquivalentContent=()=>{const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);return fingerprintMatches||jsonMatches};if(hasEquivalentContent()){return}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,ownershipDecisions,path:file5.path,previousFiles})})};for(const file5 of previousFiles){compareReceiptFile(file5)}for(const file5 of comparableFiles.values()){compareDesiredFile(file5)}const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,ownershipDecisions,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,ownershipDecisions,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter((file5)=>ownershipDecisions.get(file5.path)!=="ownership-unknown").filter((file5)=>file5.obligation?.presence!=="optional"||observedFiles.get(file5.path)?.type!=="missing").filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>ownershipDecisions.get(file5.path)!=="project-generated-current").map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();const obligationFindings=[...new Map([...previousFiles,...comparableFiles.values()].map((file5)=>[file5.path,file5])).values()].map((file5)=>{const obligation=file5.obligation??legacyArtifactObligation(file5.path);const observed=observedFiles.get(file5.path);const absent=observed===undefined||observed.type==="missing";const finding={component:"artifact",consumers:[`artifact-verification:${file5.path}`],dependencies:obligation.dependencies,path:file5.path,producer:obligation.producer};if(absent&&obligation.presence==="optional"){return{...finding,code:"optional-artifact-absent",detail:`Optional artifact ${file5.path} has no presence obligation.`,status:"healthy"}}if(obligation.contentAuthority==="unknown"||ownershipDecisions.get(file5.path)==="ownership-unknown"){return{...finding,code:"artifact-ownership-unknown",detail:`Ownership of ${file5.path} is unknown; its ${obligation.presence} obligation cannot be verified.`,status:"unknown"}}if(absent){return{...finding,code:"required-artifact-missing",detail:`Required artifact ${file5.path} is missing; producer ${obligation.producer}.`,status:"missing"}}const invalid2=observedState.invalidEntries.find((entry)=>entry.identity===file5.path);if(invalid2!==undefined){return{...finding,code:"artifact-invalid",detail:invalid2.message,status:"invalid"}}if(obligation.validity==="authored-content"&&observed.content?.trim().length===0){return{...finding,code:"authored-content-invalid",detail:`Required authored content in ${file5.path} is empty.`,status:"invalid"}}const decision=ownershipDecisions.get(file5.path);if(decision==="project-generated-stale"||decision==="project-generated-missing"){return{...finding,code:"artifact-production-pending",detail:`${file5.path} requires current ${obligation.producer} completion evidence (${decision}).`,status:"pending"}}if(changes.has(file5.path)||staleFiles.includes(file5.path)){return{...finding,code:"artifact-obligation-drift",detail:`${file5.path} does not satisfy its ${obligation.validity} obligation.`,status:"drifted"}}return{...finding,code:"artifact-obligation-current",detail:`${file5.path} satisfies its ${obligation.validity} obligation.`,status:"healthy"}});return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),obligationFindings,staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var shouldRunLintPreview=({desiredState,shouldApply})=>shouldApply&&desiredState.dependencies.some(({name:name2})=>name2==="oxlint");var lintPreviewRemovalPaths=(reconciliationPlan)=>reconciliationPlan.actions.flatMap((action2)=>action2._tag==="SafeRemoveScaffoldEntry"&&action2.item==="file"?[action2.previous.path]:[]);var executeLintPreview=({lintPreview,prepareCandidate,plannedPackageRoots,removePaths,rootDirectory,stagedRoot})=>tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Lint preview failed."}),try:async()=>await(lintPreview??runCandidateLintPreview)({liveRoot:rootDirectory,manifestSource:"live",plannedPackageRoots,...prepareCandidate===undefined?{}:{prepareCandidate},removePaths,stagedRoot})});var lintPreviewIssues=(facts)=>facts?.status==="operational-failure"&&facts.failure!==undefined?[{action:"lint-preview",code:facts.failure.kind,errorMessage:facts.failure.message,kind:"handled-failure",subject:"candidate"}]:[];var lintPreviewWarnings=(facts)=>facts?.status==="findings"?[{code:"lint-preview-findings",subject:"candidate"}]:[];var appendProjectionRecoveryChange=(changes,recovery)=>{if(!recovery.needed||!recovery.applied){return}const subject=recovery.path??".devpunks/harness-projection-receipt.json";if(!changes.some((change)=>change.subject===subject)){changes.push({action:"update",state:"completed",subject})}};var decodeGeneratedProjectionReceipt=decodeSync2(fromJsonString2(Struct({contextPlanVersion:NonEmptyString,projections:ArraySchema(Struct({actions:ArraySchema(Unknown2),adapter:Struct({id:NonEmptyString,version:NonEmptyString}),failures:ArraySchema(Never2),limitations:ArraySchema(Unknown2),matrixVersion:NonEmptyString,omissions:ArraySchema(Unknown2),warnings:ArraySchema(Unknown2)})),renderedOutputSha256:NonEmptyString,status:Literals(["success","partial"]),version:Literal2("1")})));var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,lintPreview,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check2=operation2==="check"||requestedCheck;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const filesystemSession=yield*try_3({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:"Failed to bind the repository root."}),try:()=>createConfinedFilesystemSession(rootDirectory)});const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;yield*try_3({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:"Failed to validate the repository gitignore target."}),try:()=>assertConfinedWrite({outputDirectory:rootDirectory,session:filesystemSession,targetPath:path33.join(rootDirectory,".gitignore")})});const recordedManifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});const publicationInputIdentity=scaffoldPublicationInputIdentity(baseline);const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:"Failed to verify pending scaffold publication."}),try:()=>{const pending=recordedManifest.pendingPublication;if(pending===undefined||pending.inputIdentity!==publicationInputIdentity){return recordedManifest}const dependencies=new Map((recordedManifest.managedDependencies??[]).map((entry)=>[dependencyObservationIdentity(entry),entry]));for(const entry of pending.dependencies){const document=readJsonObject(resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace)));const section2=document?.[entry.section];if(isRecord11(section2)&&section2[entry.name]===entry.version){dependencies.set(dependencyObservationIdentity(entry),entry)}}const structuredEntries=new Map((recordedManifest.managedStructuredEntries??[]).map((entry)=>[structuredObservationIdentity(entry),entry]));for(const entry of pending.structuredEntries){if(!isJsonValue(entry.value)){continue}const document=readJsonObject(resolveMutableJsonPath(rootDirectory,entry.file));if(document===null){continue}const observed=observeStructuredValue(document,{...entry,value:entry.value});if(observed._tag==="PresentStructuredObservation"&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){structuredEntries.set(structuredObservationIdentity(entry),entry)}}return{...recordedManifest,managedDependencies:[...dependencies.values()],managedStructuredEntries:[...structuredEntries.values()]}}});const projectionEvidenceNeedsRecovery=(()=>{const entry=manifest.managedFiles?.find(({kind})=>kind==="projection-receipt");const relativePath=manifest.projectionReceiptFile??entry?.path;if(relativePath===undefined){return false}try{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath);const receipt=readRequiredJsonObject(absolutePath,"Invalid projection receipt");return entry===undefined||entry.path!==relativePath||!Array.isArray(receipt.projections)||!["success","partial"].includes(String(receipt.status))||manifest.projectionStatus!==undefined&&receipt.status!==manifest.projectionStatus||hashPath(rootDirectory,relativePath)!==entry.sha256&&hashPath(rootDirectory,relativePath,{semanticJson:false})!==entry.sha256}catch{return true}})();const priorManagedDependencies=manifest.managedDependencies;yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}if(manifest.projectionReceiptFile!==undefined){resolveContainedReceiptPath(rootDirectory,manifest.projectionReceiptFile,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const priorManagedStructuredEntries=manifest.managedStructuredEntries;const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifestBaselineRecord(manifest.baseline);const assessBaselineDrift=()=>typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const baselineDrift=assessBaselineDrift();const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const selectUpdatePacks=()=>check2?finalPacks:acceptResolvedPacks({baseline,finalPacks,resolvedPacks});const updateFinalPacks=selectUpdatePacks();const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path33.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync5(path33.join(tmpdir8(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map6(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path33.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextOptions={additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:true,scanDirectory:rootDirectory};const contextAssessment=yield*compileUpdateContext(contextOptions,check2).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));let{contextPlan,blockedQualityConsumers}=contextAssessment;let qualityFindings=qualityConsumerFindings(blockedQualityConsumers);const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges(){if(isSome2(repoSettingsOnDisk)){const source=path33.join(rootDirectory,projectSettingsFile);const destination=path33.join(expectedDirectory,projectSettingsFile);mkdirSync6(path33.dirname(destination),{recursive:true});cpSync2(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];let plannedDetection=detection;let plannedPackageDocuments={};let plannedPackageDependencies=[];const materialize=(desiredState,refreshContextEvidence)=>gen2(function*materializeCandidate(){const scopedAuthoringValidationInputs=[];const projectionReceiptEntry=manifest.managedFiles?.find(({kind})=>kind==="projection-receipt");const projectionReceiptFile=manifest.projectionReceiptFile??projectionReceiptEntry?.path;let validatedProjectionReceipt=null;if(desiredState!==undefined&&projectionReceiptFile!==undefined&&!projectionEvidenceNeedsRecovery){yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage projection receipt."}),try:()=>{if(projectionReceiptEntry===undefined){throw new Error(`Projection receipt declaration has no managed file: ${projectionReceiptFile}`)}if(projectionReceiptEntry.path!==projectionReceiptFile){throw new Error(`Projection receipt declaration disagrees with managed file: ${projectionReceiptFile}`)}copyManagedFile({fromDirectory:rootDirectory,relativePath:projectionReceiptFile,toDirectory:expectedDirectory});const receipt=readRequiredJsonObject(path33.join(expectedDirectory,projectionReceiptFile),`Projection receipt is not a JSON object: ${projectionReceiptFile}`);const currentHash=hashPath(expectedDirectory,projectionReceiptFile);const legacyRawHash=hashPath(expectedDirectory,projectionReceiptFile,{semanticJson:false});if(currentHash!==projectionReceiptEntry.sha256&&legacyRawHash!==projectionReceiptEntry.sha256){throw new Error(`Recorded context evidence drifted: ${projectionReceiptFile}`)}if(manifest.projectionStatus!==undefined&&receipt.status!==manifest.projectionStatus){throw new Error(`Projection receipt status disagrees with scaffold manifest: ${projectionReceiptFile}`)}validatedProjectionReceipt=receipt}})}if(projectionEvidenceNeedsRecovery||projectionReceiptEntry!==undefined){yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage scoped authoring validation inputs."}),try:async()=>{const receiptPath=projectionReceiptFile??projectionReceiptEntry?.path;let receipt=validatedProjectionReceipt;if(projectionEvidenceNeedsRecovery&&receiptPath!==undefined){receipt=readJsonObject(resolveContainedReceiptPath(rootDirectory,receiptPath))}const supportedActions=assessScopedAuthoring({contextPlan:desiredState.contextPlan,proofs:[]}).filter((action2)=>action2.trigger!=="compatibility-unknown");const candidateSession=createConfinedFilesystemSession(expectedDirectory);const scopedAuthoring=[];const priorAuthoring=readScopedAuthoringProofs(receipt);for(const proof of priorAuthoring){const action2=supportedActions.find((entry)=>entry.scopeId===proof.scopeId&&entry.inputIdentity===proof.inputIdentity);const guidancePath=action2?.allowedOutputs.find((relativePath)=>path33.posix.basename(relativePath)==="AGENTS.md");if(guidancePath===undefined){continue}const sourcePath=resolveContainedReceiptPath(rootDirectory,guidancePath,{followLeaf:false});const source=lstatSync8(sourcePath,{throwIfNoEntry:false});if(source===undefined||!source.isFile()){continue}const content=await readConfinedRegularFile({outputDirectory:rootDirectory,session:filesystemSession,targetPath:sourcePath});if(content===null){continue}const mode=fileMode2(source.mode);await writeConfinedFile({content,mode,outputDirectory:expectedDirectory,replace:pathLexists(path33.join(expectedDirectory,guidancePath)),session:candidateSession,targetPath:path33.join(expectedDirectory,guidancePath)});scopedAuthoringValidationInputs.push({mode,path:guidancePath,sha256:hashManagedFileContent(guidancePath,content)});scopedAuthoring.push({inputIdentity:proof.inputIdentity,scopeId:proof.scopeId,status:proof.status})}const retainedAuthoring=priorAuthoring.filter((proof)=>!supportedActions.some((action2)=>action2.scopeId===proof.scopeId&&action2.inputIdentity===proof.inputIdentity)||scopedAuthoring.some((captured)=>captured.scopeId===proof.scopeId));if(projectionEvidenceNeedsRecovery||retainedAuthoring.length!==priorAuthoring.length){await writeConfinedFile({content:encodePrettyJson2(projectionEvidenceNeedsRecovery?{scopedAuthoring}:{...receipt,scopedAuthoring:retainedAuthoring}),outputDirectory:expectedDirectory,replace:pathLexists(path33.join(expectedDirectory,".devpunks/harness-projection-receipt.json")),session:candidateSession,targetPath:path33.join(expectedDirectory,".devpunks/harness-projection-receipt.json")})}}})}const output2=yield*writeScaffoldOutput({...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,desiredState,detection:plannedDetection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,plannedPackageDocuments,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredState.settings}:{}});return addOpencodePromptMirror({...output2,scopedAuthoringValidationInputs},expectedDirectory)}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map6((output2)=>{if(refreshContextEvidence||projectionEvidenceNeedsRecovery){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync5(path33.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path33.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=readRequiredJsonObject(manifestPath,"Scaffold manifest is not a JSON object");stagedManifest.generatedFiles=(isStringArray2(stagedManifest.generatedFiles)?stagedManifest.generatedFiles:[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(isUnknownArray(stagedManifest.managedFiles)?stagedManifest.managedFiles.filter((entry)=>isRecord11(entry)&&typeof entry.path==="string"):[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync7(manifestPath,encodePrettyJson2(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection:plannedDetection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,plannedPackageDocuments,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map6((plan)=>withPlannedWikiPackages({dependencies:plannedPackageDependencies,documents:plannedPackageDocuments,plan})),map6((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map6((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const preliminary=(scaffoldLifecycle.compileDesiredState??compileDesiredScaffoldState)(yield*gather());if(preliminary._tag==="DesiredScaffoldStateCompilationFailure"){return yield*new CliValidationError({message:preliminary.errors.map(({message})=>message).join(`
2517
- `)})}const preliminaryDesiredState=preliminary.state;const computeShouldAlignWiki=()=>updateFinalPacks.includes("docs")||preliminaryDesiredState.files.some((file5)=>isWikiManagedPath(file5.path));const shouldAlignWiki=computeShouldAlignWiki();let stagedWikiAlignment=shouldAlignWiki?yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage wiki alignment."}),try:async()=>{const wikiExpectedDirectory=mkdtempSync5(path33.join(tmpdir8(),"punks-wiki-update-"));wikiStagingDirectory=wikiExpectedDirectory;return await buildWikiAlignment({detection,expectedDirectory:wikiExpectedDirectory,rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2}})}}):null;const electedPackagePaths=new Set;if(stagedWikiAlignment!==null){const preliminarySemantic=semanticDesiredState({desiredState:preliminaryDesiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const preliminaryOwnership=compileManagedOwnershipDecisions({candidateFiles:stagedWikiAlignment.expectedFiles,desiredOwnershipEvidence:yield*deriveDesiredOwnershipEvidence(preliminaryDesiredState,rootDirectory),desiredState:preliminaryDesiredState,manifest,observedState:observeDesiredState({desiredState:preliminaryDesiredState,manifest,rootDirectory,semanticState:preliminarySemantic}),rootDirectory,semanticState:preliminarySemantic});for(const file5 of stagedWikiAlignment.expectedFiles){const decision=preliminaryOwnership.get(file5.path);const shouldElectPackage=()=>file5.path.endsWith("/package.json")&&decision!=="project-generated-current"&&decision!=="project-generated-missing";if(shouldElectPackage()){electedPackagePaths.add(file5.path)}}const alignmentDirectory=stagedWikiAlignment.expectedDirectory;const packageInputs=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid planned wiki package."}),try:()=>({planned:Object.fromEntries([...electedPackagePaths].map((file5)=>[file5,readRequiredJsonObject(path33.join(alignmentDirectory,file5),"Planned wiki package must be an object")])),previous:Object.fromEntries([...electedPackagePaths].filter((file5)=>pathLexists(path33.join(rootDirectory,file5))).map((file5)=>[file5,readRequiredJsonObject(path33.join(rootDirectory,file5),"Existing wiki package must be an object")]))})});plannedPackageDocuments=packageInputs.planned;const previousDocuments=packageInputs.previous;plannedPackageDependencies=generatedWikiDependencies({documents:plannedPackageDocuments,managedDependencies:manifest.managedDependencies??[],previousDocuments});const stagedDetection=yield*detectRepository(stagedWikiAlignment.expectedDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));plannedDetection=overlayWikiDetection({detection,documents:plannedPackageDocuments,stagedDetection});if(electedPackagePaths.size>0){const finalAssessment=yield*compileUpdateContext({...contextOptions,detection:plannedDetection},check2).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));({contextPlan,blockedQualityConsumers}=finalAssessment);qualityFindings=qualityConsumerFindings(blockedQualityConsumers)}}const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>gen2(function*reconcileManagedState(){if(stagedWikiAlignment!==null&&electedPackagePaths.size>0){const alignment=stagedWikiAlignment;yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to compose planned wiki package."}),try:async()=>{const session=createConfinedFilesystemSession(alignment.expectedDirectory);for(const file5 of desiredState.files.filter(({path:filePath})=>electedPackagePaths.has(filePath))){await writeConfinedFile({content:file5.content,outputDirectory:alignment.expectedDirectory,replace:true,session,targetPath:path33.join(alignment.expectedDirectory,file5.path)})}}});stagedWikiAlignment={...alignment,expectedFiles:alignment.expectedFiles.map((file5)=>electedPackagePaths.has(file5.path)?{...file5,sha256:hashPath(alignment.expectedDirectory,file5.path)??""}:file5)}}const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const contextEvidenceNeedsRefresh2=!contextPlanMatchesDesired(desiredState,manifest,rootDirectory);const output2=yield*materialize(desiredState,contextEvidenceNeedsRefresh2);if(stagedWikiAlignment!==null){const alignment=stagedWikiAlignment;yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage elected wiki package."}),try:async()=>{const session=createConfinedFilesystemSession(expectedDirectory);for(const file5 of electedPackagePaths){await copyManagedPathConfined({fromDirectory:alignment.expectedDirectory,outputDirectory:expectedDirectory,relativePath:file5,session})}}})}const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const desiredOwnershipEvidence2=yield*deriveDesiredOwnershipEvidence(desiredState,rootDirectory);const ownershipDecisions2=compileManagedOwnershipDecisions({candidateFiles:stagedWikiAlignment?.expectedFiles??[],desiredOwnershipEvidence:desiredOwnershipEvidence2,desiredState,manifest,observedState,rootDirectory,semanticState});const isVerifiedProjectGeneratedAdoption=(relativePath)=>{const desiredOwnership=desiredOwnershipEvidence2.get(relativePath);return ownershipDecisions2.get(relativePath)==="project-generated-stale"&&desiredOwnership!==undefined&&pathLexists(path33.join(rootDirectory,relativePath))&&matchesProjectGeneratedOutput({ownership:desiredOwnership,relativePath,rootDirectory})};for(const file5 of stagedWikiAlignment?.expectedFiles??[]){const decision=ownershipDecisions2.get(file5.path);if(file5.path.endsWith("/package.json")&&decision!=="project-generated-current"&&decision!=="project-generated-missing"&&!electedPackagePaths.has(file5.path)){return yield*new CliValidationError({message:`Wiki package election changed after dependency planning: ${file5.path}`})}}const wikiAlignment2=stagedWikiAlignment===null?null:(()=>{const lintOwnedWikiConfig=lintOwnedWikiConfigPath(desiredState,detection);const expectedFiles=stagedWikiAlignment.expectedFiles.filter((file5)=>{if(file5.path===lintOwnedWikiConfig){return false}const decision=ownershipDecisions2.get(file5.path);return decision!=="project-generated-current"&&decision!=="project-generated-missing"});return{...stagedWikiAlignment,changes:buildChanges({expectedDirectory:stagedWikiAlignment.expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedFiles}})();const plannedOutputPaths=new Set(output2.managedFiles.map((file5)=>file5.path));const receiptFilesByPath=new Map((manifest.managedFiles??[]).map((file5)=>[file5.path,file5]));const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&(!belongsToSeparateReconciliationLane({file:file5,manifest,plannedOutputPaths,receiptFiles:receiptFilesByPath,rootDirectory})||isVerifiedProjectGeneratedAdoption(file5.path))&&ownershipDecisions2.get(file5.path)!=="project-generated-current"&&ownershipDecisions2.get(file5.path)!=="project-generated-missing"&&(ownershipDecisions2.get(file5.path)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(file5.path)));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)&&(ownershipDecisions2.get(relativePath)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(relativePath))),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>(!belongsToSeparateReconciliationLane({file:file5,manifest,plannedOutputPaths,receiptFiles:receiptFilesByPath,rootDirectory})||isVerifiedProjectGeneratedAdoption(file5.path))&&ownershipDecisions2.get(file5.path)!=="project-generated-current"&&ownershipDecisions2.get(file5.path)!=="project-generated-missing"&&(ownershipDecisions2.get(file5.path)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(file5.path)))};const rawPlan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const fixedManagedPaths=new Set(stagedDesiredState.files.filter(({path:relativePath})=>ownershipDecisions2.get(relativePath)==="scaffold-managed").map(({path:relativePath})=>relativePath));const planned=planFixedManagedRecovery({authority:{_tag:"VerifiedDesiredBaseline",files:stagedDesiredState.files},fixedManagedPaths,plan:rawPlan});const desiredOxlintCatalogIdentities=new Set(stagedDesiredState.structuredEntries.filter(isOxlintCatalogStructuredEntry2).map(structuredObservationIdentity));const ownedOxlintCatalogIdentities=new Set(applicationReceipt.structuredEntries.filter(isOxlintCatalogStructuredEntry2).map(structuredObservationIdentity));const ownershipAwareSkips=planned.skips.map((skip)=>skip.item==="structured-entry"&&desiredOxlintCatalogIdentities.has(skip.identity)&&!ownedOxlintCatalogIdentities.has(skip.identity)?{...skip,receiptEntry:null}:skip);const verifiedAdoptionFiles=new Map(stagedDesiredState.files.filter((file5)=>isVerifiedProjectGeneratedAdoption(file5.path)).map((file5)=>[file5.path,file5]));const promotedAdoptionSkips=planned.skips.filter((skip)=>skip.item==="file"&&verifiedAdoptionFiles.has(skip.identity));const promotedAdoptionPaths=new Set(promotedAdoptionSkips.map(({identity:identity3})=>identity3));const plan={...planned,actions:[...planned.actions,...promotedAdoptionSkips.flatMap(({identity:identity3})=>{const desired=verifiedAdoptionFiles.get(identity3);return desired===undefined?[]:[{_tag:"SafeUpdateScaffoldEntry",desired,identity:identity3,item:"file"}]})],skips:ownershipAwareSkips.filter((skip)=>skip.item!=="file"||!promotedAdoptionPaths.has(skip.identity))};const comparison=compareObservedState({desiredState,manifest,observedState,ownershipDecisions:ownershipDecisions2,semanticState});return{comparison,contextEvidenceNeedsRefresh:contextEvidenceNeedsRefresh2,desiredOwnershipEvidence:desiredOwnershipEvidence2,desiredState:stagedDesiredState,output:output2,ownershipDecisions:ownershipDecisions2,plan,priorReceipt:applicationReceipt,wikiAlignment:wikiAlignment2}});if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
2515
+ `);var buildChanges=({rootDirectory,expectedDirectory,expectedFiles,previousFiles})=>{const previousByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));return expectedFiles.flatMap((expected)=>{const currentHash=hashPath(rootDirectory,expected.path);if(currentHash===expected.sha256){return[]}if(currentHash!==null&&expected.path.endsWith(".json")&&jsonContentEquals(contentForDiff(rootDirectory,expected.path),contentForDiff(expectedDirectory,expected.path))){return[]}const previous=previousByPath.get(expected.path);let status2="changed";if(currentHash===null){status2="missing"}else if(previous!==undefined&&currentHash!==previous.sha256){status2="local-edited"}return[{kind:expected.kind,path:expected.path,status:status2}]}).toSorted((left,right)=>left.path.localeCompare(right.path))};var syncSubagentsScriptFile=".agents/scripts/sync-subagents.mjs";var projectAuthoredWikiSyncFile="apps/wiki/scripts/sync-content.mjs";var wikiRouteMetadataPathPattern=/^(?<wikiRoot>apps\/wiki|app\/wiki|wiki)\/content\/docs(?:\/.*)?\/meta\.json$/u;var isProjectAuthoredWikiRouteMetadata=({file:file5,rootDirectory})=>{if(!wikiRouteMetadataPathPattern.test(file5.path)){return false}const wikiRoot=wikiRouteMetadataPathPattern.exec(file5.path)?.groups?.wikiRoot;if(wikiRoot===undefined){return false}return existsSync15(path33.join(rootDirectory,wikiRoot,"scripts","sync-content.mjs"))};var isWikiManagedPath=(relativePath)=>relativePath.startsWith("wiki/")||relativePath.startsWith("app/wiki/")||relativePath.startsWith("apps/wiki/");var canonicalClaudePromptSource=(relativePath)=>relativePath===".claude/CLAUDE.md"?".agents/AGENTS.md":path33.posix.join(path33.posix.dirname(relativePath),"AGENTS.md");var isConsumerOwnedClaudePrompt=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path33.posix.basename(relativePath)!=="CLAUDE.md"){return false}const absolutePath=path33.join(rootDirectory,relativePath);const targetExists=pathLexists(absolutePath);if(targetExists&&lstatSync8(absolutePath).isSymbolicLink()){const currentHash=hashPath(rootDirectory,relativePath);const canonicalTarget=path33.relative(path33.dirname(absolutePath),path33.join(rootDirectory,canonicalClaudePromptSource(relativePath)));return previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="symlink"||(currentHash===null?readlinkSync6(absolutePath)!==canonicalTarget:currentHash!==previousFile.sha256)}return targetExists&&!lstatSync8(absolutePath).isSymbolicLink()&&(previousFile===undefined||recordedFileType!=="file"||hashPath(rootDirectory,relativePath)!==previousFile.sha256)};var isManagedClaudePromptCopy=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path33.posix.basename(relativePath)!=="CLAUDE.md"||previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="file"){return false}const targetPath=path33.join(rootDirectory,relativePath);const sourceRelativePath=canonicalClaudePromptSource(relativePath);const sourcePath=path33.join(rootDirectory,sourceRelativePath);return existsSync15(targetPath)&&lstatSync8(targetPath).isFile()&&existsSync15(sourcePath)&&lstatSync8(sourcePath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&(recordedFileType==="file"||hashContent2(readFileSync15(targetPath))===hashContent2(readFileSync15(sourcePath)))};var isOrphanedManagedClaudePromptCopy=({previousFile,recordedFileType,relativePath,rootDirectory})=>{const targetPath=path33.join(rootDirectory,relativePath);return path33.posix.basename(relativePath)==="CLAUDE.md"&&previousFile!==undefined&&recordedFileType==="file"&&existsSync15(targetPath)&&lstatSync8(targetPath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&!existsSync15(path33.join(rootDirectory,canonicalClaudePromptSource(relativePath)))};var isManagedLegacyClaudeSymlink=({file:file5,rootDirectory,plannedOutputPaths})=>{if(file5.kind!=="harness"||path33.posix.basename(file5.path)!=="CLAUDE.md"||!pathLexists(path33.join(rootDirectory,file5.path))||!lstatSync8(path33.join(rootDirectory,file5.path)).isSymbolicLink()||hashPath(rootDirectory,file5.path)!==file5.sha256){return false}const canonicalSource=path33.join(rootDirectory,canonicalClaudePromptSource(file5.path));return existsSync15(canonicalSource)&&lstatSync8(canonicalSource).isFile()||plannedOutputPaths?.has(file5.path)===true&&readlinkSync6(path33.join(rootDirectory,file5.path))===path33.relative(path33.dirname(path33.join(rootDirectory,file5.path)),canonicalSource)};var hasManagedLegacyClaudeSymlink=({files,relativePath,rootDirectory,plannedOutputPaths})=>{const file5=files.get(relativePath);return file5!==undefined&&isManagedLegacyClaudeSymlink({file:file5,rootDirectory,...plannedOutputPaths===undefined?{}:{plannedOutputPaths}})};var belongsToSeparateReconciliationLane=({file:file5,manifest,receiptFiles,rootDirectory,plannedOutputPaths})=>file5.kind==="context-plan"||file5.kind==="projection-receipt"||file5.kind==="required-tools"||file5.path===agentHandoffFile2||file5.path===agentSystemPromptFile2||isManagedClaudePromptCopy({previousFile:receiptFiles.get(file5.path),recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})||isOrphanedManagedClaudePromptCopy({previousFile:receiptFiles.get(file5.path),recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})||hasManagedLegacyClaudeSymlink({files:receiptFiles,plannedOutputPaths,relativePath:file5.path,rootDirectory})||isWikiManagedPath(file5.path);var isTailoredSyncSubagentsScript=(rootDirectory)=>{const scriptPath=path33.join(rootDirectory,syncSubagentsScriptFile);if(!existsSync15(scriptPath)){return false}const content=readFileSync15(scriptPath,"utf-8");return/["'`](?:app|apps|packages|infra)\//u.test(content)};var isProjectAuthoredManagedFile=({file:file5,rootDirectory})=>{if(isProjectAuthoredWikiRouteMetadata({file:file5,rootDirectory})){return true}if(file5.path===projectAuthoredWikiSyncFile){return existsSync15(path33.join(rootDirectory,file5.path))}if(file5.path===".agents/scripts/sync-subagents.mjs"){return isTailoredSyncSubagentsScript(rootDirectory)}const obligation=file5.obligation??legacyArtifactObligation(file5.path);if(obligation.contentAuthority==="repository"||obligation.contentAuthority==="mixed"){return existsSync15(path33.join(rootDirectory,file5.path))}return file5.path===".claude/CLAUDE.md"||file5.path===".codex/AGENTS.md"||file5.path===".opencode/AGENTS.md"};var buildLegacyRequiredToolsPromptChanges=({rootDirectory})=>{const promptFiles=[agentHandoffFile2,agentSystemPromptFile2];return promptFiles.flatMap((promptFile)=>{const absolutePath=path33.join(rootDirectory,promptFile);if(!existsSync15(absolutePath)){return[]}const current=readFileSync15(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return[]}return[{kind:"handoff",path:promptFile,status:"local-edited"}]})};var rewriteLegacyRequiredToolsPrompt=async({rootDirectory,relativePath,session})=>{const absolutePath=path33.join(rootDirectory,relativePath);const currentBytes=await readConfinedRegularFile({allowMissing:true,outputDirectory:rootDirectory,session,targetPath:absolutePath});if(currentBytes===null){return}const current=currentBytes.toString("utf-8");if(!current.includes(legacyRequiredToolsFile)){return}await writeConfinedFile({content:current.replaceAll(legacyRequiredToolsFile,repoSettingsDisplayFile),outputDirectory:rootDirectory,replace:true,session,targetPath:absolutePath})};var copyIfExists=({rootDirectory,targetDirectory,relativePath,ignoreGeneratedRootDirectories=false})=>{const sourcePath=path33.join(rootDirectory,relativePath);if(!existsSync15(sourcePath)){return}const targetPath=path33.join(targetDirectory,relativePath);const stat3=lstatSync8(sourcePath);mkdirSync6(path33.dirname(targetPath),{recursive:true});if(stat3.isSymbolicLink()){symlinkSync(readlinkSync6(sourcePath),targetPath);return}cpSync2(sourcePath,targetPath,{filter:(source)=>{const relativeSource=path33.relative(sourcePath,source).split(path33.sep).join("/");return!ignoreGeneratedRootDirectories||!hasIgnoredWikiAlignmentRootDirectory(relativeSource)},recursive:true,verbatimSymlinks:true})};var readWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path33.join(wikiDirectory,"wiki-framework.md");if(!existsSync15(pinPath)){return"next"}const content=readFileSync15(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}return"next"};var wikiRootForAlignment=(rootDirectory,detection,hasRootMarkers)=>{if(hasRootMarkers("apps/wiki")){return"apps/wiki"}if(hasRootMarkers("app/wiki")){return"app/wiki"}if(existsSync15(path33.join(rootDirectory,"apps/wiki"))){return"apps/wiki"}if(existsSync15(path33.join(rootDirectory,"wiki"))){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var buildWikiAlignment=async({rootDirectory,detection,expectedDirectory,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const hasWikiRootMarkers2=(relativeRoot)=>{const absoluteRoot=path33.join(rootDirectory,relativeRoot);return["package.json","backlog-provider.md","wiki-framework.md"].some((marker)=>existsSync15(path33.join(absoluteRoot,marker)))};const wikiRoot=wikiRootForAlignment(rootDirectory,detection,hasWikiRootMarkers2);copyIfExists({ignoreGeneratedRootDirectories:true,relativePath:wikiRoot,rootDirectory,targetDirectory:expectedDirectory});copyIfExists({relativePath:"docs",rootDirectory,targetDirectory:expectedDirectory});const wikiFramework=readWikiFrameworkPin(path33.join(expectedDirectory,wikiRoot));await scaffoldWikiForDirectory({monorepo:wikiRoot==="apps/wiki",outputDirectory:expectedDirectory,wikiFramework});const syncScript=path33.join(expectedDirectory,wikiRoot,"scripts","sync-content.mjs");if(existsSync15(syncScript)){runJavaScriptFileSync({cwd:expectedDirectory,file:syncScript,...scriptEnvironment===undefined?{}:{environment:scriptEnvironment},...scriptRuntimePath2===undefined?{}:{runtimePath:scriptRuntimePath2}})}const expectedFiles=collectRelativeFiles2(expectedDirectory,wikiRoot).map((relativePath)=>({kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""}));return{changes:buildChanges({expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedDirectory,expectedFiles}};var readValidatedWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path33.join(wikiDirectory,"wiki-framework.md");if(!existsSync15(pinPath)){return"next"}const content=readFileSync15(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}throw new Error(`Invalid wiki framework pin: ${pinPath}`)};var buildGitignoreCleanup=async({rootDirectory,expectedDirectory})=>{const relativePath=".gitignore";if(!existsSync15(path33.join(rootDirectory,relativePath))){return[]}copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory});const cleanup=await removeHarnessDirectoriesFromGitignore(expectedDirectory,({content,gitignorePath})=>{writeFileSync7(gitignorePath,content)});if(cleanup.removedPatterns.length===0){return[]}const expectedFile={kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})};var semanticFile=({content,encoding="utf-8",kind="harness",mode,path:relativePath})=>({content,encoding,kind,...encoding==="symlink"||mode===undefined?{}:{mode},obligation:producerObligation("baseline",[version2]),path:relativePath,provenance:{revision:version2,source:"scaffold-semantics"}});var isJsonValue=(value5)=>{if(value5===null||typeof value5==="boolean"||typeof value5==="number"||typeof value5==="string"){return true}if(Array.isArray(value5)){return value5.every(isJsonValue)}return typeof value5==="object"&&Object.values(value5).every(isJsonValue)};var isJsonObject2=(value5)=>isJsonValue(value5)&&typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var isStringArray2=(value5)=>Array.isArray(value5)&&value5.every((entry)=>typeof entry==="string");var projectionSemanticState=({desiredState})=>{const files=new Map;const structuredEntries=[];for(const projection of desiredState.projections){for(const action2 of projection.actions){const applyFileSemantics=()=>{if(action2.operation==="use-native-mirror"&&typeof action2.nativePath==="string"&&typeof action2.canonicalPath==="string"){const nativeRoot=`${action2.nativePath.split("/skills/")[0]}/skills`;const canonicalRoot=`${action2.canonicalPath.split("/skills/")[0]}/skills`;files.set(nativeRoot,semanticFile({content:path33.posix.relative(path33.posix.dirname(nativeRoot),canonicalRoot),encoding:"symlink",path:nativeRoot}))}if(action2.operation==="mirror"&&action2.id.includes(":lifecycle-hook:")&&typeof action2.source==="string"&&typeof action2.target==="string"&&action2.source!==action2.target){files.set(action2.target,semanticFile({content:path33.posix.relative(path33.posix.dirname(action2.target),action2.source),encoding:"symlink",kind:action2.target.includes("/hooks/")?"hook":"harness",path:action2.target}))}if(action2.operation==="merge-json"&&typeof action2.file==="string"&&isStringArray2(action2.path)&&isJsonValue(action2.value)){const value5=action2.file===".claude/settings.json"?[action2.value]:action2.value;structuredEntries.push({file:action2.file,kind:"field",path:action2.path,provenance:{revision:version2,source:"harness-projection"},value:value5})}};applyFileSemantics();const applyJsonKeySemantics=()=>{if(action2.operation==="merge-json"&&typeof action2.target==="string"&&action2.file===undefined&&!action2.target.includes("#")&&isJsonObject2(action2.value)){for(const[key,value5]of Object.entries(action2.value)){if(action2.target==="opencode.json"&&key==="formatter"&&isJsonObject2(value5)&&"harness-format-edited-file"in value5){structuredEntries.push({file:action2.target,kind:"key",path:["formatter","harness-format-edited-file"],provenance:{revision:version2,source:"harness-projection"},value:value5["harness-format-edited-file"]});continue}structuredEntries.push({file:action2.target,kind:"key",path:[key],provenance:{revision:version2,source:"harness-projection"},value:value5})}}};applyJsonKeySemantics();const applyHookConfigSemantics=()=>{const{config}=action2;if(action2.operation==="mirror"&&isJsonObject2(config)&&typeof config.path==="string"&&typeof config.event==="string"&&typeof config.command==="string"&&(config.timeout===undefined||typeof config.timeout==="number")){structuredEntries.push({file:config.path,kind:"field",path:["hooks",config.event],provenance:{revision:version2,source:"harness-projection"},value:[{command:config.command,...config.timeout===undefined?{}:{timeout:config.timeout}}]})}};applyHookConfigSemantics()}}const codexHookActions=desiredState.projections.flatMap(({actions})=>actions).filter((action2)=>action2.operation==="merge-toml"&&action2.id.includes(":lifecycle-hook:"));const applyCodexHookSemantics=()=>{if(codexHookActions.length===0){return}const hasUpdateCheck=codexHookActions.some((action2)=>action2.id.includes("scaffold-update-check"));const hasFormatHook=codexHookActions.some((action2)=>action2.id.includes("format-edited-file"));const lines2=["[agents]","max_depth = 1","","[features]","hooks = true","","[hooks]"];if(hasUpdateCheck||hasFormatHook){const hooks=[...hasUpdateCheck?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs\\" codex", statusMessage = "Checking Harness scaffold", timeout = 60 },']:[],...hasFormatHook?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" session-start", statusMessage = "Capturing edited-file baseline", timeout = 30 },']:[]];lines2.push("SessionStart = [",' { matcher = "startup|resume", hooks = [',...hooks," ] },","]")}if(hasFormatHook){lines2.push("PostToolUse = [",' { matcher = "Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit", hooks = [',' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" post", statusMessage = "Auto-formatting edited files", timeout = 30 },'," ] },","]")}lines2.push("");files.set(".codex/config.toml",semanticFile({content:lines2.join(`
2516
+ `),path:".codex/config.toml"}))};applyCodexHookSemantics();return{files:[...files.values()],structuredEntries}};var wikiRootForDetection=(detection)=>{const detectedManifestPaths=new Set(detection.manifests.map(({relativePath})=>relativePath.split(path33.sep).join("/")));if(detectedManifestPaths.has("apps/wiki/package.json")){return"apps/wiki"}if(detectedManifestPaths.has("app/wiki/package.json")){return"app/wiki"}if(detectedManifestPaths.has("wiki/package.json")){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var wikiSemanticState=({detection,finalPacks,framework,settings,rootDirectory})=>{if(!finalPacks.includes("docs")){return{files:[],structuredEntries:[]}}const wikiRoot=wikiRootForDetection(detection);const template=makeWikiScaffoldTemplate(wikiRoot,framework);const starterFile=(file5)=>{const relativePath=path33.posix.join(wikiRoot,file5.path);const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const routeSeed=/^content\/docs\/project\/(?<project>[^/]+)\/(?:index\.mdx|meta\.json)$/u.exec(file5.path);const project2=routeSeed?.groups?.project;const flatRouteExists=project2!==undefined&&[".md",".mdx"].some((extension)=>{const flatPath=resolveContainedReceiptPath(rootDirectory,path33.posix.join(wikiRoot,"content/docs/project",`${project2}${extension}`),{followLeaf:false});return lstatSync8(flatPath,{throwIfNoEntry:false})?.isFile()===true&&readFileSync15(flatPath,"utf-8").trim().length>0});const directory3=path33.dirname(absolutePath);const populatedPlaceholder=path33.posix.basename(file5.path)===".gitkeep"&&lstatSync8(directory3,{throwIfNoEntry:false})?.isDirectory()===true&&readdirSync8(directory3).some((entry)=>!entry.startsWith("."));return{...semanticFile({...file5,path:relativePath}),obligation:{...producerObligation("wiki-starter",[version2]),presence:flatRouteExists||populatedPlaceholder?"optional":"required",validity:/\.mdx?$/u.test(file5.path)?"authored-content":"presence"}}};const files=[...template.files.map((file5)=>file5.path==="scripts/sync-content.mjs"||file5.path==="package.json"?semanticFile({...file5,path:path33.posix.join(wikiRoot,file5.path)}):starterFile(file5)),...template.rawSubdirectories.map((directory3)=>starterFile({content:"",path:path33.posix.join("raw",directory3,".gitkeep")})),starterFile({content:"",path:"content/docs/project/.gitkeep"}),starterFile({content:"",path:"specs/.gitkeep"}),semanticFile({content:"AGENTS.md",encoding:"symlink",path:path33.posix.join(wikiRoot,"CLAUDE.md")}),starterFile({content:template.indexMarkdown,path:"index.md"}),starterFile({content:template.logMarkdown,path:"log.md"}),starterFile({content:renderBacklogProviderMarkdown(settings.backlogProvider),path:"backlog-provider.md"}),starterFile({content:renderWikiFrameworkMarkdown(framework),path:"wiki-framework.md"})];return{files,structuredEntries:[]}};var lintOwnedWikiConfigPath=(desiredState,detection)=>{const file5=path33.posix.join(wikiRootForDetection(detection),"oxlint.config.ts");return desiredState.files.some(({path:relativePath})=>relativePath===file5)?file5:undefined};var semanticDesiredState=({desiredState,detection,finalPacks,wikiFramework,settings,rootDirectory})=>{const projection=projectionSemanticState({desiredState});const wiki=wikiSemanticState({detection,finalPacks,framework:wikiFramework,rootDirectory,settings});const lintOwnedWikiConfig=lintOwnedWikiConfigPath(desiredState,detection);return{files:[...projection.files,...wiki.files.filter(({path:relativePath})=>relativePath!==lintOwnedWikiConfig)],structuredEntries:[...projection.structuredEntries,...wiki.structuredEntries]}};var desiredFileBytes=(file5)=>file5.encoding==="base64"?Buffer.from(file5.content,"base64"):file5.content;var desiredFileFingerprint=(file5)=>JSON.stringify({mode:file5.mode===undefined?null:fileMode2(file5.mode),sha256:hashContent2(file5.encoding==="symlink"?`symlink:${file5.content}`:desiredFileBytes(file5)),type:file5.encoding==="symlink"?"symlink":"file"});var observeManagedFile=({expectedMode,kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const projectAuthored=isProjectAuthoredManagedFile({file:{kind,path:relativePath,sha256:""},rootDirectory});if(!pathLexists(absolutePath)){return{fingerprint:"missing",kind,mode:null,path:relativePath,projectAuthored,sha256:null,type:"missing"}}const stat3=lstatSync8(absolutePath);if(!stat3.isSymbolicLink()&&!stat3.isFile()){return{fingerprint:JSON.stringify({mode:null,sha256:null,type:"other"}),kind,mode:fileMode2(stat3.mode),path:relativePath,projectAuthored,sha256:null,type:"other"}}const isSymlink=stat3.isSymbolicLink();const symlinkTarget=isSymlink?readlinkSync6(absolutePath):undefined;const bytes=isSymlink?undefined:readFileSync15(absolutePath);const sha256=hashContent2(isSymlink?`symlink:${symlinkTarget}`:bytes??"");const mode=isSymlink?null:fileMode2(stat3.mode);return{...isSymlink?{content:symlinkTarget??""}:{content:(bytes??Buffer.from("")).toString("utf-8")},fingerprint:JSON.stringify({mode:expectedMode===undefined||isSymlink?null:mode,sha256,type:isSymlink?"symlink":"file"}),kind,mode,path:relativePath,projectAuthored,sha256,type:isSymlink?"symlink":"file"}};var deriveDesiredOwnershipEvidence=fn2("Update.deriveDesiredOwnershipEvidence")(function*deriveDesiredOwnershipEvidence2(desiredState,rootDirectory){const entries=yield*all2(desiredState.files.flatMap((file5)=>file5.projectProducer===undefined?[]:[deriveProjectGeneratedOwnership({declaration:file5.projectProducer,repositoryRoot:rootDirectory}).pipe(map6((ownership)=>[file5.path,ownership]))])).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));return new Map(entries)});var ownershipObservation=(observed)=>{if(observed===undefined||observed.type==="missing"){return{_tag:"Missing"}}if(observed.type==="file"&&observed.mode!==null&&observed.sha256!==null){return{_tag:"Present",fingerprint:{_tag:"File",mode:observed.mode,sha256:observed.sha256}}}if(observed.type==="symlink"&&observed.content!==undefined&&observed.sha256!==null){return{_tag:"Present",fingerprint:{_tag:"Symlink",sha256:observed.sha256,target:observed.content}}}return{_tag:"Unsupported"}};var resolveRepositoryFileOwnership=(file5,obligation,observed,rootDirectory)=>{if(obligation.producer==="wiki-starter"){return observed?.type==="file"||obligation.presence==="optional"&&(observed===undefined||observed.type==="missing")?"project-generated-current":"scaffold-managed"}if(observed?.projectAuthored!==true&&!isProjectAuthoredManagedFile({file:{...file5,sha256:""},rootDirectory})){return"scaffold-managed"}if(file5.path===projectAuthoredWikiSyncFile&&(observed===undefined||observed.type==="missing")){return"scaffold-managed"}return"project-generated-current"};var resolveFileOwnership=({desiredOwnership,file:file5,observed,receiptPresent,receiptOwnership,rootDirectory,scope:scope3})=>{const obligation=file5.obligation??legacyArtifactObligation(file5.path);const hasUnknownAuthority=()=>obligation.contentAuthority==="unknown"&&desiredOwnership===undefined&&receiptOwnership?._tag!=="ProjectGenerated";if(hasUnknownAuthority()){return"ownership-unknown"}const resolution=resolveManagedFileOwnership({...desiredOwnership===undefined?{}:{desiredOwnership},observed:ownershipObservation(observed),...receiptOwnership===undefined?{}:{receiptOwnership},scope:scope3});if(receiptPresent&&path33.posix.basename(file5.path)==="CLAUDE.md"&&!existsSync15(path33.join(rootDirectory,canonicalClaudePromptSource(file5.path)))){return resolution}if(receiptOwnership?._tag==="ProjectGenerated"&&desiredOwnership?._tag!=="ProjectGenerated"){return resolution}if(resolution!=="scaffold-managed"||scope3==="semantic-overlap"){return resolution}return resolveRepositoryFileOwnership(file5,obligation,observed,rootDirectory)};var packageFileForWorkspace=(workspace)=>workspace==="."?"package.json":path33.posix.join(workspace,"package.json");var compileManagedOwnershipDecisions=({candidateFiles,desiredOwnershipEvidence,desiredState,manifest,observedState,rootDirectory,semanticState})=>{const desiredFiles=new Map([...candidateFiles,...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const receiptFiles=new Map((manifest.managedFiles??[]).map((file5)=>[file5.path,file5]));const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));for(const file5 of candidateFiles){if(!observedFiles.has(file5.path)){observedFiles.set(file5.path,observeManagedFile({kind:file5.kind,relativePath:file5.path,rootDirectory}))}}const semanticPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5),...semanticState.structuredEntries.map(({file:file5})=>file5)]);const managedClaudeCopyPaths=new Set([...receiptFiles.values()].filter((file5)=>isManagedClaudePromptCopy({previousFile:file5,recordedFileType:manifest.managedFileTypes?.[file5.path],relativePath:file5.path,rootDirectory})).map(({path:relativePath})=>relativePath));const managedClaudeCanonicalSourcePaths=new Set([...managedClaudeCopyPaths].map(canonicalClaudePromptSource).filter((relativePath)=>{const previousFile=receiptFiles.get(relativePath);return desiredFiles.has(relativePath)&&previousFile!==undefined&&hashPath(rootDirectory,relativePath)===previousFile.sha256}));const paths=new Set([...desiredFiles.keys(),...receiptFiles.keys()]);return new Map([...paths].map((relativePath)=>{const desired=desiredFiles.get(relativePath);const desiredOwnership=desiredOwnershipEvidence.get(relativePath);const receipt=receiptFiles.get(relativePath);const file5=desired??receipt;if(file5===undefined){throw new Error(`Managed ownership path has no file evidence: ${relativePath}`)}if(desiredOwnership===undefined&&(managedClaudeCopyPaths.has(relativePath)||managedClaudeCanonicalSourcePaths.has(relativePath))){return[relativePath,"scaffold-managed"]}return[relativePath,resolveFileOwnership({...desiredOwnership===undefined?{}:{desiredOwnership},file:file5,observed:observedFiles.get(relativePath),receiptPresent:receipt!==undefined,...receipt?.ownership===undefined?{}:{receiptOwnership:receipt.ownership},rootDirectory,scope:semanticPaths.has(relativePath)?"semantic-overlap":"whole-file"})]}))};var readJsonObject=(absolutePath)=>{try{const value5=JSON.parse(readFileSync15(absolutePath,"utf-8"));return isRecord11(value5)?value5:null}catch{return null}};var readRequiredJsonObject=(absolutePath,description)=>{const value5=readJsonObject(absolutePath);if(value5===null){throw new Error(`${description}: ${absolutePath}`)}return value5};var managedFileOwnershipEntry=(ownership)=>ownership===undefined?{}:{ownership};var applyManagedLifecycleHook=({action:action2,entryFile,leaf,parent,priorEntry})=>{const desiredHook=action2._tag==="SafeRemoveScaffoldEntry"?undefined:managedLifecycleHook(action2.desired);let previousHook;if(action2._tag==="SafeRemoveScaffoldEntry"){previousHook=managedLifecycleHook(action2.previous)}else if(priorEntry!==undefined){previousHook=managedLifecycleHook(priorEntry)}const managedHook=desiredHook??previousHook;if(managedHook===undefined){return false}const current=parent[leaf];if(current!==undefined&&!isUnknownArray(current)){throw new Error(`Lifecycle hook configuration is not an array: ${entryFile}`)}const previousValue=(previousHook??desiredHook)?.value;let removedPrevious=false;const consumerHooks=(current??[]).filter((hook)=>{if(!removedPrevious&&previousValue!==undefined&&stableJsonStringify(hook)===stableJsonStringify(previousValue)){removedPrevious=true;return false}return true});if(action2._tag==="SafeRemoveScaffoldEntry"){if(consumerHooks.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=consumerHooks}}else{parent[leaf]=[...consumerHooks,(desiredHook??managedHook).value]}return true};var receiptForFile=({kind,ownership,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync8(absolutePath);const type2=stat3.isSymbolicLink()?"symlink":"file";return{kind,mode:type2==="symlink"?null:fileMode2(stat3.mode),ownership:ownership?._tag==="ProjectGenerated"?ownership:{_tag:"ScaffoldManaged"},path:relativePath,sha256:hashPath(rootDirectory,relativePath)??"",type:type2}};var matchesProjectGeneratedOutput=({ownership,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync8(absolutePath);const expected=ownership.evidence.outputFingerprint;if(stat3.isSymbolicLink()){if(expected._tag!=="Symlink"){return false}const target=readlinkSync6(absolutePath);return target===expected.target&&createHash12("sha256").update(`symlink:${target}`).digest("hex")===expected.sha256}return stat3.isFile()&&expected._tag==="File"&&fileMode2(stat3.mode)===expected.mode&&createHash12("sha256").update(readFileSync15(absolutePath)).digest("hex")===expected.sha256};var writeJsonDocument=async({absolutePath,document,rootDirectory,session})=>{await writeConfinedFile({content:encodePrettyJson2(document),outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"||action2._tag==="ArchiveAndReplaceScaffoldFile"?"update":"remove"};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){const stderr=result4.stderr.trim();if(result4.error!==undefined){throw new Error(result4.error.message)}throw new Error(stderr.length>0?stderr:`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path33.join(rootDirectory,lockfile);return[absolutePath,existsSync15(absolutePath)?readFileSync15(absolutePath):null]}));var restoreDependencyLockfiles=async(rootDirectory,snapshot,session)=>{for(const[absolutePath,content]of snapshot){if(content===null){await removeConfinedPath({outputDirectory:rootDirectory,recursive:false,session,targetPath:absolutePath})}else{await writeConfinedFile({content,outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})}}};var scaffoldApplicatorFailure=(action2,cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:action2.item,message:cause instanceof Error?cause.message:"Scaffold application failed.",operation:publicReconciliationOperation(action2)});var scaffoldReceiptFailure=(cause)=>new ScaffoldApplicationFailure({cause,identity:"managed-scaffold-receipt",item:"receipt",message:cause instanceof Error?cause.message:"Scaffold receipt persistence failed.",operation:"persist"});var makeScaffoldReconciliationApplicators=({dependencyProcess,desiredOwnershipEvidence,priorReceipt,rootDirectory,session})=>({applyDependency:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=isRecord11(sectionValue)?sectionValue:{};const previousPackageManifest=readFileSync15(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;await writeJsonDocument({absolutePath,document,rootDirectory,session});const installationCommand=dependencyInstallationCommand(rootDirectory);if(installationCommand!==null){try{dependencyProcess(installationCommand[0],installationCommand[1],rootDirectory)}catch(error2){await writeConfinedFile({content:previousPackageManifest,outputDirectory:rootDirectory,replace:true,session,targetPath:absolutePath});await restoreDependencyLockfiles(rootDirectory,lockfileSnapshot,session);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;let absolutePath;try{absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false})}catch(error2){throw new CliValidationError({cause:error2,message:error2 instanceof Error?error2.message:`Managed receipt path is unsafe: ${relativePath}`})}if(action2._tag==="SafeRemoveScaffoldEntry"){await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session,targetPath:absolutePath});return null}const{desired}=action2;if(desired.encoding==="symlink"){const expectedAbsent=await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session,targetPath:absolutePath});await replaceConfinedSymlink({...expectedAbsent===null?{}:{expectedAbsent},linkTarget:desired.content,outputDirectory:rootDirectory,session,targetPath:absolutePath})}else{if(pathLexists(absolutePath)&&lstatSync8(absolutePath).isSymbolicLink()){await removeConfinedPath({outputDirectory:rootDirectory,recursive:false,session,targetPath:absolutePath})}await writeConfinedFile({content:desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content,...desired.mode===undefined?{}:{mode:fileMode2(desired.mode)},outputDirectory:rootDirectory,replace:lstatSync8(absolutePath,{throwIfNoEntry:false})!==undefined,session,targetPath:absolutePath})}const desiredOwnership=desiredOwnershipEvidence.get(relativePath);const ownership=desiredOwnership!==undefined&&matchesProjectGeneratedOutput({ownership:desiredOwnership,relativePath,rootDirectory})?desiredOwnership:undefined;return{...receiptForFile({kind:desired.kind,...ownership===undefined?{}:{ownership},relativePath,rootDirectory}),...desired.obligation===undefined?{}:{obligation:desired.obligation},...desired.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:desired.sharedPromptIdentity}}}}),applyStructuredEntry:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync15(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(segment==="workspaces"&&Array.isArray(value5)&&isOxlintCatalogStructuredEntry2(entry)){const child={packages:value5};parent[segment]=child;parent=child}else if(isRecord11(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";if(entry.kind==="required-shell-segment"){const command=entry.value;const current=parent[leaf];if(typeof command!=="string"||current!==undefined&&typeof current!=="string"){throw new Error(`Required shell segment is not a string: ${entry.file}`)}if(action2._tag==="SafeRemoveScaffoldEntry"){const next=removeShellAndCommandSegment(current??"",command);if(next.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=next}}else{const priorEntry2=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const retained=action2._tag==="SafeUpdateScaffoldEntry"&&priorEntry2?.kind==="required-shell-segment"&&typeof priorEntry2.value==="string"&&priorEntry2.value!==command?removeShellAndCommandSegment(current??"",priorEntry2.value):current??"";parent[leaf]=appendShellAndCommandSegment(retained,command)}await writeJsonDocument({absolutePath,document,rootDirectory,session});return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}await writeJsonDocument({absolutePath,document,rootDirectory,session});return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),archiveAndReplaceFile:(action2)=>tryPromise2({catch:(cause)=>scaffoldApplicatorFailure(action2,cause),try:async()=>{const replacement=action2.desired.encoding==="symlink"?{_tag:"Symlink",linkTarget:action2.desired.content}:{_tag:"File",content:action2.desired.encoding==="base64"?Buffer.from(action2.desired.content,"base64"):action2.desired.content,...action2.desired.mode===undefined?{}:{mode:fileMode2(action2.desired.mode)}};await archiveAndReplaceConfinedFile({archiveDirectory:path33.join(rootDirectory,".devpunks/replaced-scaffold"),outputDirectory:rootDirectory,replacement,session,targetPath:resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false})});const observed=receiptForFile({kind:action2.desired.kind,relativePath:action2.identity,rootDirectory});return observed.type==="symlink"?{mode:null,sha256:observed.sha256,type:"symlink"}:{mode:observed.mode??fileMode2(lstatSync8(resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false})).mode),sha256:observed.sha256,type:"file"}}}),persistReceipt:(receipt)=>tryPromise2({catch:scaffoldReceiptFailure,try:async()=>{const manifestPath=path33.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,ownership,path:relativePath,sha256,obligation,sharedPromptIdentity})=>({...obligation===undefined?{}:{obligation},...sharedPromptIdentity===undefined?{}:{sharedPromptIdentity},kind,...ownership?._tag==="ProjectGenerated"?{ownership}:{},path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;await writeJsonDocument({absolutePath:manifestPath,document:manifest,rootDirectory,session})}}),verifyFile:(action2)=>try_3({catch:(cause)=>new ScaffoldApplicationFailure({cause,identity:action2.identity,item:"file",message:cause instanceof Error?cause.message:"Scaffold output verification failed.",operation:publicReconciliationOperation(action2)}),try:()=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,action2.identity,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){if(pathLexists(absolutePath)){throw new Error(`Removed scaffold output is still present: ${action2.identity}`)}return}const{desired}=action2;const stat3=lstatSync8(absolutePath);const expectedSymlink=desired.encoding==="symlink";if(stat3.isSymbolicLink()!==expectedSymlink||!expectedSymlink&&!stat3.isFile()||hashPath(rootDirectory,action2.identity,{semanticJson:false})!==nodeScaffoldContentHasher.sha256(desired)||!expectedSymlink&&desired.mode!==undefined&&fileMode2(stat3.mode)!==fileMode2(desired.mode)){throw new Error(`Scaffold output failed current-state verification: ${action2.identity}`)}}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var reconciliationActionPath=(action2)=>{if(action2.item==="file"){return action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path}if(action2.item==="structured-entry"){return action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file}return packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace)};var publicReconciliationActions=(plan,blockedPaths=new Set)=>plan.actions.filter((action2)=>!blockedPaths.has(reconciliationActionPath(action2))).map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index,segment]of entry.path.entries()){if(Array.isArray(value5)&&index===1&&isOxlintCatalogStructuredEntry2(entry)){return{_tag:"MissingStructuredObservation"}}if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=isRecord11(value5)?value5[segment]:undefined}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!isUnknownArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>isJsonValue(candidate)&&stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}if(entry.kind==="required-shell-segment"){if(typeof value5!=="string"||typeof entry.value!=="string"){return{_tag:"InvalidStructuredObservation",message:`Required shell segment is not a string: ${entry.file}`}}if(hasBackgroundedShellCommandSegment(value5,entry.value)){return{_tag:"InvalidStructuredObservation",message:`Lint setup cannot safely compose ${entry.file} ${entry.path.join(".")}.`}}return hasShellAndCommandSegment(value5,entry.value)?{_tag:"PresentStructuredObservation",value:entry.value}:{_tag:"MissingStructuredObservation"}}if(!isJsonValue(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured value is not valid JSON: ${entry.file}`}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const desiredStructuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries].map((entry)=>[structuredObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredStructuredEntries.values(),...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync15(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=isRecord11(section2)?section2[dependency.name]:undefined;if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync15(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const desiredEntry=desiredStructuredEntries.get(identity3);const desiredObservation=desiredEntry?.kind==="required-shell-segment"?observeStructuredValue(document,desiredEntry):undefined;const observationEntry=entry.kind==="required-shell-segment"&&desiredEntry?.kind==="required-shell-segment"&&desiredObservation?._tag==="PresentStructuredObservation"&&(entry.value===desiredEntry.value||observeStructuredValue(document,entry)._tag==="MissingStructuredObservation")?desiredEntry:entry;const observation=observeStructuredValue(document,observationEntry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));const rootPackageJson=readJsonObject(path33.join(rootDirectory,"package.json"));const workspaces=rootPackageJson?.workspaces;const catalog=isJsonObject2(workspaces)?workspaces.catalog:undefined;const legacyOxlintCatalogValue=isJsonObject2(catalog)?catalog.oxlint:undefined;const legacyOxlintCatalogReceipt=typeof legacyOxlintCatalogValue==="string"&&(manifest.managedDependencies??[]).some(({name:name2,version:dependencyVersion})=>(name2==="@effect/tsgo"||name2==="oxlint-tsgolint")&&dependencyVersion==="catalog:")?[{file:"package.json",kind:"field",path:["workspaces","catalog","oxlint"],value:legacyOxlintCatalogValue}]:[];return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync8(absolutePath).isFile()?fileMode2(lstatSync8(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&&currentMode!==undefined&&desiredMode!==undefined&&currentMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},ownership:file5.ownership,...file5.obligation===undefined?{}:{obligation:file5.obligation},...file5.sharedPromptIdentity===undefined?{}:{sharedPromptIdentity:file5.sharedPromptIdentity},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:[...(manifest.managedStructuredEntries??[]).flatMap((entry)=>isJsonValue(entry.value)?[{...entry,value:entry.value}]:[]),...legacyOxlintCatalogReceipt],version:"1"}};var changeStatus=({ownershipDecisions,path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);if(previous?.ownership?._tag==="ProjectGenerated"&&ownershipDecisions.get(relativePath)==="scaffold-managed"){return"local-edited"}return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compileUpdateContext=fn2("Update.compileContext")(function*compileUpdateContext2(options4,check2){if(check2){return yield*assessScaffoldContextPlan(options4)}return{_tag:"ContextPlanAssessment",blockedQualityConsumers:[],contextPlan:yield*compileScaffoldContextPlan(options4)}});var qualityConsumerFindings=(consumers)=>consumers.map(({scopeId,contribution:contribution2,cause})=>({code:"quality-contract-incomplete",component:"quality",consumers:[`commit-gate-verification:${scopeId}`],contribution:contribution2,detail:`${cause.message} Missing Commit Gate commands: ${cause.missing.join(", ")}.`,scopeId,status:"blocked"}));var contextPlanMatchesDesired=(desiredState,manifest,rootDirectory)=>{const relativePath=manifest.contextPlanFile??manifest.managedFiles?.find(({kind})=>kind==="context-plan")?.path;if(relativePath===undefined){return false}const observed=decodeUnknownOption2(ContextPlan)(readJsonObject(resolveContainedReceiptPath(rootDirectory,relativePath)));if(isNone2(observed)){return false}const normalized=compileDesiredScaffoldState({baseline:{...desiredState.baseline,dependencies:[],files:[],structuredEntries:[]},contextPlan:observed.value,projections:[],settings:desiredState.settings});return normalized._tag==="DesiredScaffoldStateCompiled"&&stableJsonStringify(normalized.state.contextPlan)===stableJsonStringify(desiredState.contextPlan)};var scopedAuthoringFindings=(contextPlan,rootDirectory,projectionReceiptFile)=>{const receipt=projectionReceiptFile===undefined?null:readJsonObject(resolveContainedReceiptPath(rootDirectory,projectionReceiptFile));return assessScopedAuthoring({contextPlan,proofs:readScopedAuthoringProofs(receipt)}).map((action2)=>({code:action2.trigger==="compatibility-unknown"?"scoped-authoring-compatibility-unknown":"scoped-authoring-pending",component:"artifact",consumers:["scoped-guidance",...action2.allowedAgentIds],dependencies:[action2.inputIdentity],detail:`Scope ${action2.scopeId} requires bounded authoring for ${action2.inputIdentity}: ${action2.trigger}.`,path:action2.allowedOutputs[0]??agentHandoffFile2,producer:"bounded-scoped-authoring",scopeId:action2.scopeId,status:action2.trigger==="compatibility-unknown"?"unknown":"pending"}))};var blockQualityDependentFindings=(findings,qualityFindings,contextPaths)=>{if(qualityFindings.length===0){return findings}const contributions=qualityFindings.flatMap((finding)=>finding.contribution===undefined?[]:[finding.contribution.id]);return findings.map((finding)=>{if(!contextPaths.includes(finding.path)&&finding.dependencies?.some((dependency)=>contributions.includes(dependency))!==true){return finding}return{...finding,code:"artifact-dependent-quality-blocked",consumers:[...finding.consumers,...qualityFindings.flatMap((quality)=>quality.consumers)],detail:`${finding.path??"Artifact"} depends on an unresolved quality contribution: ${contributions.join(", ")}.`,status:"blocked"}})};var qualityBlockedPaths=(findings)=>new Set(findings.flatMap((finding)=>finding.code==="artifact-dependent-quality-blocked"&&finding.path!==undefined?[finding.path]:[]));var assessQualityComparison=(comparison,qualityFindings,contextPaths)=>{const obligationFindings=blockQualityDependentFindings(comparison.obligationFindings,qualityFindings,contextPaths);const blockedPaths=qualityBlockedPaths(obligationFindings);return{changedFiles:comparison.changedFiles.filter(({path:relativePath})=>!blockedPaths.has(relativePath)),obligationFindings,staleFiles:comparison.staleFiles.filter((relativePath)=>!blockedPaths.has(relativePath))}};var compareObservedState=({desiredState,manifest,observedState,ownershipDecisions,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);const comparableFiles=new Map([...semanticState.files.filter((file5)=>!entryOwnedPaths.has(file5.path)),...desiredState.files].map((file5)=>[file5.path,file5]));const compareReceiptFile=(file5)=>{if(comparableFiles.has(file5.path)){return}const obligation=file5.obligation??legacyArtifactObligation(file5.path);const observed=observedFiles.get(file5.path);if(obligation.presence==="optional"&&(observed===undefined||observed.type==="missing")){return}if(obligation.contentAuthority==="unknown"){addChange({kind:file5.kind,path:file5.path,status:"local-edited"});return}if(obligation.contentAuthority==="repository"&&obligation.presence==="required"&&(observed===undefined||observed.type==="missing"||observed.content?.trim().length===0)){addChange({kind:file5.kind,path:file5.path,status:observed===undefined||observed.type==="missing"?"missing":"local-edited"})}};const compareDesiredFile=(file5)=>{const observed=observedFiles.get(file5.path);const ownershipDecision=ownershipDecisions.get(file5.path);if(file5.obligation?.presence==="optional"&&(observed===undefined||observed.type==="missing")){return}if(ownershipDecision==="ownership-unknown"){addChange({kind:file5.kind,path:file5.path,status:"local-edited"});return}const hasInvalidRequiredContent=()=>file5.obligation?.presence==="required"&&(observed===undefined||observed.type==="missing"||file5.obligation.validity==="authored-content"&&observed.content?.trim().length===0);const invalidRequiredContent=hasInvalidRequiredContent();if(invalidRequiredContent){addChange({kind:file5.kind,path:file5.path,status:observed===undefined||observed.type==="missing"?"missing":"local-edited"});return}if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||ownershipDecision==="project-generated-current"){return}if(ownershipDecision==="project-generated-missing"||ownershipDecision==="project-generated-stale"){addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,ownershipDecisions,path:file5.path,previousFiles})});return}const hasEquivalentContent=()=>{const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);return fingerprintMatches||jsonMatches};if(hasEquivalentContent()){return}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,ownershipDecisions,path:file5.path,previousFiles})})};for(const file5 of previousFiles){compareReceiptFile(file5)}for(const file5 of comparableFiles.values()){compareDesiredFile(file5)}const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,ownershipDecisions,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,ownershipDecisions,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter((file5)=>ownershipDecisions.get(file5.path)!=="ownership-unknown").filter((file5)=>file5.obligation?.presence!=="optional"||observedFiles.get(file5.path)?.type!=="missing").filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>ownershipDecisions.get(file5.path)!=="project-generated-current").map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();const obligationFindings=[...new Map([...previousFiles,...comparableFiles.values()].map((file5)=>[file5.path,file5])).values()].map((file5)=>{const obligation=file5.obligation??legacyArtifactObligation(file5.path);const observed=observedFiles.get(file5.path);const absent=observed===undefined||observed.type==="missing";const finding={component:"artifact",consumers:[`artifact-verification:${file5.path}`],dependencies:obligation.dependencies,path:file5.path,producer:obligation.producer};if(absent&&obligation.presence==="optional"){return{...finding,code:"optional-artifact-absent",detail:`Optional artifact ${file5.path} has no presence obligation.`,status:"healthy"}}if(obligation.contentAuthority==="unknown"||ownershipDecisions.get(file5.path)==="ownership-unknown"){return{...finding,code:"artifact-ownership-unknown",detail:`Ownership of ${file5.path} is unknown; its ${obligation.presence} obligation cannot be verified.`,status:"unknown"}}if(absent){return{...finding,code:"required-artifact-missing",detail:`Required artifact ${file5.path} is missing; producer ${obligation.producer}.`,status:"missing"}}const invalid2=observedState.invalidEntries.find((entry)=>entry.identity===file5.path);if(invalid2!==undefined){return{...finding,code:"artifact-invalid",detail:invalid2.message,status:"invalid"}}if(obligation.validity==="authored-content"&&observed.content?.trim().length===0){return{...finding,code:"authored-content-invalid",detail:`Required authored content in ${file5.path} is empty.`,status:"invalid"}}const decision=ownershipDecisions.get(file5.path);if(decision==="project-generated-stale"||decision==="project-generated-missing"){return{...finding,code:"artifact-production-pending",detail:`${file5.path} requires current ${obligation.producer} completion evidence (${decision}).`,status:"pending"}}if(changes.has(file5.path)||staleFiles.includes(file5.path)){return{...finding,code:"artifact-obligation-drift",detail:`${file5.path} does not satisfy its ${obligation.validity} obligation.`,status:"drifted"}}return{...finding,code:"artifact-obligation-current",detail:`${file5.path} satisfies its ${obligation.validity} obligation.`,status:"healthy"}});return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),obligationFindings,staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var shouldRunLintPreview=({desiredState,shouldApply})=>shouldApply&&desiredState.dependencies.some(({name:name2})=>name2==="oxlint");var lintPreviewRemovalPaths=(reconciliationPlan)=>reconciliationPlan.actions.flatMap((action2)=>action2._tag==="SafeRemoveScaffoldEntry"&&action2.item==="file"?[action2.previous.path]:[]);var executeLintPreview=({lintPreview,prepareCandidate,plannedPackageRoots,removePaths,rootDirectory,stagedRoot})=>tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Lint preview failed."}),try:async()=>await(lintPreview??runCandidateLintPreview)({liveRoot:rootDirectory,manifestSource:"live",plannedPackageRoots,...prepareCandidate===undefined?{}:{prepareCandidate},removePaths,stagedRoot})});var lintPreviewIssues=(facts)=>facts?.status==="operational-failure"&&facts.failure!==undefined?[{action:"lint-preview",code:facts.failure.kind,errorMessage:facts.failure.message,kind:"handled-failure",subject:"candidate"}]:[];var lintPreviewWarnings=(facts)=>facts?.status==="findings"?[{code:"lint-preview-findings",subject:"candidate"}]:[];var appendProjectionRecoveryChange=(changes,recovery)=>{if(!recovery.needed||!recovery.applied){return}const subject=recovery.path??".devpunks/harness-projection-receipt.json";if(!changes.some((change)=>change.subject===subject)){changes.push({action:"update",state:"completed",subject})}};var decodeGeneratedProjectionReceipt=decodeSync2(fromJsonString2(Struct({contextPlanVersion:NonEmptyString,projections:ArraySchema(Struct({actions:ArraySchema(Unknown2),adapter:Struct({id:NonEmptyString,version:NonEmptyString}),failures:ArraySchema(Never2),limitations:ArraySchema(Unknown2),matrixVersion:NonEmptyString,omissions:ArraySchema(Unknown2),warnings:ArraySchema(Unknown2)})),renderedOutputSha256:NonEmptyString,status:Literals(["success","partial"]),version:Literal2("1")})));var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,lintPreview,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check2=operation2==="check"||requestedCheck;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const filesystemSession=yield*try_3({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:"Failed to bind the repository root."}),try:()=>createConfinedFilesystemSession(rootDirectory)});const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;yield*try_3({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:"Failed to validate the repository gitignore target."}),try:()=>assertConfinedWrite({outputDirectory:rootDirectory,session:filesystemSession,targetPath:path33.join(rootDirectory,".gitignore")})});const recordedManifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});const publicationInputIdentity=scaffoldPublicationInputIdentity(baseline);const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:"Failed to verify pending scaffold publication."}),try:()=>{const pending=recordedManifest.pendingPublication;if(pending===undefined||pending.inputIdentity!==publicationInputIdentity){return recordedManifest}const dependencies=new Map((recordedManifest.managedDependencies??[]).map((entry)=>[dependencyObservationIdentity(entry),entry]));for(const entry of pending.dependencies){const document=readJsonObject(resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace)));const section2=document?.[entry.section];if(isRecord11(section2)&&section2[entry.name]===entry.version){dependencies.set(dependencyObservationIdentity(entry),entry)}}const structuredEntries=new Map((recordedManifest.managedStructuredEntries??[]).map((entry)=>[structuredObservationIdentity(entry),entry]));for(const entry of pending.structuredEntries){if(!isJsonValue(entry.value)){continue}const document=readJsonObject(resolveMutableJsonPath(rootDirectory,entry.file));if(document===null){continue}const observed=observeStructuredValue(document,{...entry,value:entry.value});if(observed._tag==="PresentStructuredObservation"&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){structuredEntries.set(structuredObservationIdentity(entry),entry)}}return{...recordedManifest,managedDependencies:[...dependencies.values()],managedStructuredEntries:[...structuredEntries.values()]}}});const projectionEvidenceNeedsRecovery=(()=>{const entry=manifest.managedFiles?.find(({kind})=>kind==="projection-receipt");const relativePath=manifest.projectionReceiptFile??entry?.path;if(relativePath===undefined){return false}try{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath);const receipt=readRequiredJsonObject(absolutePath,"Invalid projection receipt");return entry===undefined||entry.path!==relativePath||!Array.isArray(receipt.projections)||!["success","partial"].includes(String(receipt.status))||manifest.projectionStatus!==undefined&&receipt.status!==manifest.projectionStatus||hashPath(rootDirectory,relativePath)!==entry.sha256&&hashPath(rootDirectory,relativePath,{semanticJson:false})!==entry.sha256}catch{return true}})();const priorManagedDependencies=manifest.managedDependencies;yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}if(manifest.projectionReceiptFile!==undefined){resolveContainedReceiptPath(rootDirectory,manifest.projectionReceiptFile,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const priorManagedStructuredEntries=manifest.managedStructuredEntries;const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifestBaselineRecord(manifest.baseline);const assessBaselineDrift=()=>typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const baselineDrift=assessBaselineDrift();const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const selectUpdatePacks=()=>check2?finalPacks:acceptResolvedPacks({baseline,finalPacks,resolvedPacks});const updateFinalPacks=selectUpdatePacks();const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path33.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync5(path33.join(tmpdir8(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map6(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path33.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextOptions={additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:true,scanDirectory:rootDirectory};const contextAssessment=yield*compileUpdateContext(contextOptions,check2).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));let{contextPlan,blockedQualityConsumers}=contextAssessment;let qualityFindings=qualityConsumerFindings(blockedQualityConsumers);const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges(){if(isSome2(repoSettingsOnDisk)){const source=path33.join(rootDirectory,projectSettingsFile);const destination=path33.join(expectedDirectory,projectSettingsFile);mkdirSync6(path33.dirname(destination),{recursive:true});cpSync2(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];let plannedDetection=detection;let plannedPackageDocuments={};let plannedPackageDependencies=[];const materialize=(desiredState,refreshContextEvidence)=>gen2(function*materializeCandidate(){const scopedAuthoringValidationInputs=[];const projectionReceiptEntry=manifest.managedFiles?.find(({kind})=>kind==="projection-receipt");const projectionReceiptFile=manifest.projectionReceiptFile??projectionReceiptEntry?.path;let validatedProjectionReceipt=null;if(desiredState!==undefined&&projectionReceiptFile!==undefined&&!projectionEvidenceNeedsRecovery){yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage projection receipt."}),try:()=>{if(projectionReceiptEntry===undefined){throw new Error(`Projection receipt declaration has no managed file: ${projectionReceiptFile}`)}if(projectionReceiptEntry.path!==projectionReceiptFile){throw new Error(`Projection receipt declaration disagrees with managed file: ${projectionReceiptFile}`)}copyManagedFile({fromDirectory:rootDirectory,relativePath:projectionReceiptFile,toDirectory:expectedDirectory});const receipt=readRequiredJsonObject(path33.join(expectedDirectory,projectionReceiptFile),`Projection receipt is not a JSON object: ${projectionReceiptFile}`);const currentHash=hashPath(expectedDirectory,projectionReceiptFile);const legacyRawHash=hashPath(expectedDirectory,projectionReceiptFile,{semanticJson:false});if(currentHash!==projectionReceiptEntry.sha256&&legacyRawHash!==projectionReceiptEntry.sha256){throw new Error(`Recorded context evidence drifted: ${projectionReceiptFile}`)}if(manifest.projectionStatus!==undefined&&receipt.status!==manifest.projectionStatus){throw new Error(`Projection receipt status disagrees with scaffold manifest: ${projectionReceiptFile}`)}validatedProjectionReceipt=receipt}})}if(projectionEvidenceNeedsRecovery||projectionReceiptEntry!==undefined){yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage scoped authoring validation inputs."}),try:async()=>{const receiptPath=projectionReceiptFile??projectionReceiptEntry?.path;let receipt=validatedProjectionReceipt;if(projectionEvidenceNeedsRecovery&&receiptPath!==undefined){receipt=readJsonObject(resolveContainedReceiptPath(rootDirectory,receiptPath))}const supportedActions=assessScopedAuthoring({contextPlan:desiredState.contextPlan,proofs:[]}).filter((action2)=>action2.trigger!=="compatibility-unknown");const candidateSession=createConfinedFilesystemSession(expectedDirectory);const scopedAuthoring=[];const priorAuthoring=readScopedAuthoringProofs(receipt);for(const proof of priorAuthoring){const action2=supportedActions.find((entry)=>entry.scopeId===proof.scopeId&&entry.inputIdentity===proof.inputIdentity);const guidancePath=action2?.allowedOutputs.find((relativePath)=>path33.posix.basename(relativePath)==="AGENTS.md");if(guidancePath===undefined){continue}const sourcePath=resolveContainedReceiptPath(rootDirectory,guidancePath,{followLeaf:false});const source=lstatSync8(sourcePath,{throwIfNoEntry:false});if(source===undefined||!source.isFile()){continue}const content=await readConfinedRegularFile({outputDirectory:rootDirectory,session:filesystemSession,targetPath:sourcePath});if(content===null){continue}const mode=fileMode2(source.mode);await writeConfinedFile({content,mode,outputDirectory:expectedDirectory,replace:pathLexists(path33.join(expectedDirectory,guidancePath)),session:candidateSession,targetPath:path33.join(expectedDirectory,guidancePath)});scopedAuthoringValidationInputs.push({mode,path:guidancePath,sha256:hashManagedFileContent(guidancePath,content)});scopedAuthoring.push({inputIdentity:proof.inputIdentity,scopeId:proof.scopeId,status:proof.status})}const retainedAuthoring=priorAuthoring.filter((proof)=>!supportedActions.some((action2)=>action2.scopeId===proof.scopeId&&action2.inputIdentity===proof.inputIdentity)||scopedAuthoring.some((captured)=>captured.scopeId===proof.scopeId));if(projectionEvidenceNeedsRecovery||retainedAuthoring.length!==priorAuthoring.length){await writeConfinedFile({content:encodePrettyJson2(projectionEvidenceNeedsRecovery?{scopedAuthoring}:{...receipt,scopedAuthoring:retainedAuthoring}),outputDirectory:expectedDirectory,replace:pathLexists(path33.join(expectedDirectory,".devpunks/harness-projection-receipt.json")),session:candidateSession,targetPath:path33.join(expectedDirectory,".devpunks/harness-projection-receipt.json")})}}})}const output2=yield*writeScaffoldOutput({...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,desiredState,detection:plannedDetection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,plannedPackageDocuments,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredState.settings}:{}});return addOpencodePromptMirror({...output2,scopedAuthoringValidationInputs},expectedDirectory)}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map6((output2)=>{if(refreshContextEvidence||projectionEvidenceNeedsRecovery){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync5(path33.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path33.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=readRequiredJsonObject(manifestPath,"Scaffold manifest is not a JSON object");stagedManifest.generatedFiles=(isStringArray2(stagedManifest.generatedFiles)?stagedManifest.generatedFiles:[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(isUnknownArray(stagedManifest.managedFiles)?stagedManifest.managedFiles.filter((entry)=>isRecord11(entry)&&typeof entry.path==="string"):[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync7(manifestPath,encodePrettyJson2(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({...priorManagedDependencies===undefined?{}:{priorManagedDependencies},...priorManagedStructuredEntries===undefined?{}:{priorManagedStructuredEntries},additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection:plannedDetection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,plannedPackageDocuments,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map6((plan)=>withPlannedWikiPackages({dependencies:plannedPackageDependencies,documents:plannedPackageDocuments,plan})),map6((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map6((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,rootDirectory,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const preliminary=(scaffoldLifecycle.compileDesiredState??compileDesiredScaffoldState)(yield*gather());if(preliminary._tag==="DesiredScaffoldStateCompilationFailure"){return yield*new CliValidationError({message:preliminary.errors.map(({message})=>message).join(`
2517
+ `)})}const preliminaryDesiredState=preliminary.state;const computeShouldAlignWiki=()=>updateFinalPacks.includes("docs")||preliminaryDesiredState.files.some((file5)=>isWikiManagedPath(file5.path));const shouldAlignWiki=computeShouldAlignWiki();let stagedWikiAlignment=shouldAlignWiki?yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage wiki alignment."}),try:async()=>{const wikiExpectedDirectory=mkdtempSync5(path33.join(tmpdir8(),"punks-wiki-update-"));wikiStagingDirectory=wikiExpectedDirectory;return await buildWikiAlignment({detection,expectedDirectory:wikiExpectedDirectory,rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2}})}}):null;const electedPackagePaths=new Set;if(stagedWikiAlignment!==null){const preliminarySemantic=semanticDesiredState({desiredState:preliminaryDesiredState,detection,finalPacks:updateFinalPacks,rootDirectory,settings:desiredSettings,wikiFramework});const preliminaryOwnership=compileManagedOwnershipDecisions({candidateFiles:stagedWikiAlignment.expectedFiles,desiredOwnershipEvidence:yield*deriveDesiredOwnershipEvidence(preliminaryDesiredState,rootDirectory),desiredState:preliminaryDesiredState,manifest,observedState:observeDesiredState({desiredState:preliminaryDesiredState,manifest,rootDirectory,semanticState:preliminarySemantic}),rootDirectory,semanticState:preliminarySemantic});for(const file5 of stagedWikiAlignment.expectedFiles){const decision=preliminaryOwnership.get(file5.path);const shouldElectPackage=()=>file5.path.endsWith("/package.json")&&decision!=="project-generated-current"&&decision!=="project-generated-missing";if(shouldElectPackage()){electedPackagePaths.add(file5.path)}}const alignmentDirectory=stagedWikiAlignment.expectedDirectory;const packageInputs=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid planned wiki package."}),try:()=>({planned:Object.fromEntries([...electedPackagePaths].map((file5)=>[file5,readRequiredJsonObject(path33.join(alignmentDirectory,file5),"Planned wiki package must be an object")])),previous:Object.fromEntries([...electedPackagePaths].filter((file5)=>pathLexists(path33.join(rootDirectory,file5))).map((file5)=>[file5,readRequiredJsonObject(path33.join(rootDirectory,file5),"Existing wiki package must be an object")]))})});plannedPackageDocuments=packageInputs.planned;const previousDocuments=packageInputs.previous;plannedPackageDependencies=generatedWikiDependencies({documents:plannedPackageDocuments,managedDependencies:manifest.managedDependencies??[],previousDocuments});const stagedDetection=yield*detectRepository(stagedWikiAlignment.expectedDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));plannedDetection=overlayWikiDetection({detection,documents:plannedPackageDocuments,stagedDetection});if(electedPackagePaths.size>0){const finalAssessment=yield*compileUpdateContext({...contextOptions,detection:plannedDetection},check2).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));({contextPlan,blockedQualityConsumers}=finalAssessment);qualityFindings=qualityConsumerFindings(blockedQualityConsumers)}}const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>gen2(function*reconcileManagedState(){if(stagedWikiAlignment!==null&&electedPackagePaths.size>0){const alignment=stagedWikiAlignment;yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to compose planned wiki package."}),try:async()=>{const session=createConfinedFilesystemSession(alignment.expectedDirectory);for(const file5 of desiredState.files.filter(({path:filePath})=>electedPackagePaths.has(filePath))){await writeConfinedFile({content:file5.content,outputDirectory:alignment.expectedDirectory,replace:true,session,targetPath:path33.join(alignment.expectedDirectory,file5.path)})}}});stagedWikiAlignment={...alignment,expectedFiles:alignment.expectedFiles.map((file5)=>electedPackagePaths.has(file5.path)?{...file5,sha256:hashPath(alignment.expectedDirectory,file5.path)??""}:file5)}}const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,rootDirectory,settings:desiredSettings,wikiFramework});const contextEvidenceNeedsRefresh2=!contextPlanMatchesDesired(desiredState,manifest,rootDirectory);const output2=yield*materialize(desiredState,contextEvidenceNeedsRefresh2);if(stagedWikiAlignment!==null){const alignment=stagedWikiAlignment;yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to stage elected wiki package."}),try:async()=>{const session=createConfinedFilesystemSession(expectedDirectory);for(const file5 of electedPackagePaths){await copyManagedPathConfined({fromDirectory:alignment.expectedDirectory,outputDirectory:expectedDirectory,relativePath:file5,session})}}})}const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const desiredOwnershipEvidence2=yield*deriveDesiredOwnershipEvidence(desiredState,rootDirectory);const ownershipDecisions2=compileManagedOwnershipDecisions({candidateFiles:stagedWikiAlignment?.expectedFiles??[],desiredOwnershipEvidence:desiredOwnershipEvidence2,desiredState,manifest,observedState,rootDirectory,semanticState});const isVerifiedProjectGeneratedAdoption=(relativePath)=>{const desiredOwnership=desiredOwnershipEvidence2.get(relativePath);return ownershipDecisions2.get(relativePath)==="project-generated-stale"&&desiredOwnership!==undefined&&pathLexists(path33.join(rootDirectory,relativePath))&&matchesProjectGeneratedOutput({ownership:desiredOwnership,relativePath,rootDirectory})};for(const file5 of stagedWikiAlignment?.expectedFiles??[]){const decision=ownershipDecisions2.get(file5.path);if(file5.path.endsWith("/package.json")&&decision!=="project-generated-current"&&decision!=="project-generated-missing"&&!electedPackagePaths.has(file5.path)){return yield*new CliValidationError({message:`Wiki package election changed after dependency planning: ${file5.path}`})}}const wikiAlignment2=stagedWikiAlignment===null?null:(()=>{const lintOwnedWikiConfig=lintOwnedWikiConfigPath(desiredState,detection);const expectedFiles=stagedWikiAlignment.expectedFiles.filter((file5)=>{if(file5.path===lintOwnedWikiConfig){return false}const decision=ownershipDecisions2.get(file5.path);return decision!=="project-generated-current"&&decision!=="project-generated-missing"});return{...stagedWikiAlignment,changes:buildChanges({expectedDirectory:stagedWikiAlignment.expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedFiles}})();const plannedOutputPaths=new Set(output2.managedFiles.map((file5)=>file5.path));const receiptFilesByPath=new Map((manifest.managedFiles??[]).map((file5)=>[file5.path,file5]));const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&(!belongsToSeparateReconciliationLane({file:file5,manifest,plannedOutputPaths,receiptFiles:receiptFilesByPath,rootDirectory})||isVerifiedProjectGeneratedAdoption(file5.path))&&ownershipDecisions2.get(file5.path)!=="project-generated-current"&&ownershipDecisions2.get(file5.path)!=="project-generated-missing"&&(ownershipDecisions2.get(file5.path)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(file5.path)));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)&&(ownershipDecisions2.get(relativePath)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(relativePath))),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>(!belongsToSeparateReconciliationLane({file:file5,manifest,plannedOutputPaths,receiptFiles:receiptFilesByPath,rootDirectory})||isVerifiedProjectGeneratedAdoption(file5.path))&&ownershipDecisions2.get(file5.path)!=="project-generated-current"&&ownershipDecisions2.get(file5.path)!=="project-generated-missing"&&(ownershipDecisions2.get(file5.path)!=="project-generated-stale"||isVerifiedProjectGeneratedAdoption(file5.path)))};const rawPlan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const fixedManagedPaths=new Set(stagedDesiredState.files.filter(({path:relativePath})=>ownershipDecisions2.get(relativePath)==="scaffold-managed").map(({path:relativePath})=>relativePath));const planned=planFixedManagedRecovery({authority:{_tag:"VerifiedDesiredBaseline",files:stagedDesiredState.files},fixedManagedPaths,plan:rawPlan});const desiredOxlintCatalogIdentities=new Set(stagedDesiredState.structuredEntries.filter(isOxlintCatalogStructuredEntry2).map(structuredObservationIdentity));const ownedOxlintCatalogIdentities=new Set(applicationReceipt.structuredEntries.filter(isOxlintCatalogStructuredEntry2).map(structuredObservationIdentity));const ownershipAwareSkips=planned.skips.map((skip)=>skip.item==="structured-entry"&&desiredOxlintCatalogIdentities.has(skip.identity)&&!ownedOxlintCatalogIdentities.has(skip.identity)?{...skip,receiptEntry:null}:skip);const verifiedAdoptionFiles=new Map(stagedDesiredState.files.filter((file5)=>isVerifiedProjectGeneratedAdoption(file5.path)).map((file5)=>[file5.path,file5]));const promotedAdoptionSkips=planned.skips.filter((skip)=>skip.item==="file"&&verifiedAdoptionFiles.has(skip.identity));const promotedAdoptionPaths=new Set(promotedAdoptionSkips.map(({identity:identity3})=>identity3));const plan={...planned,actions:[...planned.actions,...promotedAdoptionSkips.flatMap(({identity:identity3})=>{const desired=verifiedAdoptionFiles.get(identity3);return desired===undefined?[]:[{_tag:"SafeUpdateScaffoldEntry",desired,identity:identity3,item:"file"}]})],skips:ownershipAwareSkips.filter((skip)=>skip.item!=="file"||!promotedAdoptionPaths.has(skip.identity))};const comparison=compareObservedState({desiredState,manifest,observedState,ownershipDecisions:ownershipDecisions2,semanticState});return{comparison,contextEvidenceNeedsRefresh:contextEvidenceNeedsRefresh2,desiredOwnershipEvidence:desiredOwnershipEvidence2,desiredState:stagedDesiredState,output:output2,ownershipDecisions:ownershipDecisions2,plan,priorReceipt:applicationReceipt,wikiAlignment:wikiAlignment2}});if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
2518
2518
  `)}))}return lifecycle2.comparison}const lifecycle=yield*runUpdateScaffoldLifecycle({...compiler,gather,observe,reconcile});if(lifecycle._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle.compilation.errors.map(({message})=>message).join(`
2519
2519
  `)}))}return lifecycle.reconciliation});const{comparison:rawObservedComparison,contextEvidenceNeedsRefresh,desiredOwnershipEvidence,output:expectedOutput,ownershipDecisions,plan:reconciliationPlan,wikiAlignment:expectedWikiAlignment}=expected;const projectionEvidenceNeedsPublication=projectionEvidenceNeedsRecovery||contextEvidenceNeedsRefresh;const authoringFindings=scopedAuthoringFindings(expected.desiredState.contextPlan,projectionEvidenceNeedsPublication?expectedDirectory:rootDirectory,projectionEvidenceNeedsPublication?expectedOutput.managedFiles.find(({kind})=>kind==="projection-receipt")?.path:manifest.projectionReceiptFile);const observedComparison=assessQualityComparison({...rawObservedComparison,obligationFindings:[...rawObservedComparison.obligationFindings,...authoringFindings]},qualityFindings,[manifest.contextPlanFile,manifest.projectionReceiptFile]);const blockedQualityPaths=qualityBlockedPaths(observedComparison.obligationFindings);const reportedReconciliationActions=publicReconciliationActions(reconciliationPlan,blockedQualityPaths);const receiptEntryOwnedPaths=new Set([...expected.desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...expected.desiredState.structuredEntries.map(({file:file5})=>file5)]);const reconciliationPaths=reconciliationControlledPaths({desiredState:expected.desiredState,plan:reconciliationPlan,priorReceipt:expected.priorReceipt});const previousFiles=manifest.managedFiles??[];const previousFilesByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));const explicitProjectGeneratedPaths=new Set(desiredOwnershipEvidence.keys());const receiptOnlyProjectGeneratedLegacyPromptPaths=new Set(previousFiles.filter(({ownership})=>ownership?._tag==="ProjectGenerated").map(({path:relativePath})=>relativePath).filter((relativePath)=>!explicitProjectGeneratedPaths.has(relativePath)&&(relativePath===agentHandoffFile2||relativePath===agentSystemPromptFile2)));const stageLegacyClaudeSymlinks=()=>{const stagedLegacyClaudeSymlinkFiles2=previousFiles.filter((file5)=>!existsSync15(path33.join(expectedDirectory,file5.path))&&isManagedLegacyClaudeSymlink({file:file5,rootDirectory}));for(const file5 of stagedLegacyClaudeSymlinkFiles2){copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory})}return stagedLegacyClaudeSymlinkFiles2};const stagedLegacyClaudeSymlinkFiles=stageLegacyClaudeSymlinks();const claudeCandidatePaths=new Set([...previousFiles.filter(({kind,path:relativePath})=>kind==="harness"&&path33.posix.basename(relativePath)==="CLAUDE.md").map(({path:relativePath})=>relativePath),...collectRelativeFiles2(expectedDirectory,".").filter((relativePath)=>path33.posix.basename(relativePath)==="CLAUDE.md")]);const managedClaudeCopyPaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return isManagedClaudePromptCopy({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const orphanedManagedClaudeCopyPaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return isOrphanedManagedClaudePromptCopy({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const stageManagedClaudeCopies=()=>{for(const relativePath of managedClaudeCopyPaths){const canonicalSourceRelativePath=canonicalClaudePromptSource(relativePath);const stagedCanonicalSource=path33.join(expectedDirectory,canonicalSourceRelativePath);const currentCanonicalSource=path33.join(rootDirectory,canonicalSourceRelativePath);const previousCanonicalSource=previousFilesByPath.get(canonicalSourceRelativePath);const canonicalSource=previousCanonicalSource!==undefined&&hashPath(rootDirectory,canonicalSourceRelativePath)===previousCanonicalSource.sha256?stagedCanonicalSource:currentCanonicalSource;if(existsSync15(canonicalSource)&&lstatSync8(canonicalSource).isFile()){const stagedTarget=path33.join(expectedDirectory,relativePath);mkdirSync6(path33.dirname(stagedTarget),{recursive:true});rmSync5(stagedTarget,{force:true,recursive:true});cpSync2(canonicalSource,stagedTarget)}else{copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory})}}};stageManagedClaudeCopies();const preservedManagedClaudeCopyFiles=[...managedClaudeCopyPaths].filter((relativePath)=>!expectedOutput.managedFiles.some(({path:expectedPath})=>expectedPath===relativePath)).flatMap((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return previousFile===undefined?[]:[{kind:previousFile.kind,...managedFileOwnershipEntry(previousFile.ownership),path:previousFile.path,sha256:hashPath(expectedDirectory,relativePath)??""}]});const consumerOwnedClaudePaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{if(managedClaudeCopyPaths.has(relativePath)){return false}const previousFile=previousFilesByPath.get(relativePath);return isConsumerOwnedClaudePrompt({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const recordedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"||kind==="projection-receipt"&&!projectionEvidenceNeedsRecovery);yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Recorded context evidence drifted."}),try:()=>{for(const file5 of recordedContextEvidence){const currentHash=hashPath(rootDirectory,file5.path);const legacyRawHash=hashPath(rootDirectory,file5.path,{semanticJson:false});const formatterOnly=jsonContentEquals(contentForDiff(rootDirectory,file5.path),contentForDiff(expectedDirectory,file5.path));const equivalentContext=file5.kind==="context-plan"&&!contextEvidenceNeedsRefresh;if(currentHash!==file5.sha256&&legacyRawHash!==file5.sha256&&!formatterOnly&&!equivalentContext){throw new Error(`Recorded context evidence drifted: ${file5.path}`)}}}});const prepareManagedState=()=>{const expectedOutputPaths=new Set(expectedOutput.managedFiles.map(({path:relativePath})=>relativePath));const reconciledSubagentManifestPath=expectedOutput.managedFiles.find((file5)=>file5.kind==="subagent"&&file5.path===".agents/subagents/manifest.mjs")?.path;const preservedExplicitProjectGeneratedFiles=previousFiles.filter(({path:relativePath})=>explicitProjectGeneratedPaths.has(relativePath)&&ownershipDecisions.get(relativePath)==="project-generated-current"&&!expectedOutputPaths.has(relativePath)).map((file5)=>{copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});return file5});const preservedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"&&!contextEvidenceNeedsRefresh||kind==="projection-receipt"&&!projectionEvidenceNeedsPublication).map((file5)=>{copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});return file5});const expectedManagedFiles2=[...expectedOutput.managedFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({path:relativePath})=>!orphanedManagedClaudeCopyPaths.has(relativePath)).filter(({path:relativePath})=>!receiptEntryOwnedPaths.has(relativePath)).filter(({path:relativePath})=>!consumerOwnedClaudePaths.has(relativePath)&&!preservedContextEvidence.some(({path:preservedPath})=>preservedPath===relativePath)).filter((file5)=>ownershipDecisions.get(file5.path)!=="project-generated-missing"&&(ownershipDecisions.get(file5.path)!=="project-generated-current"||pathLexists(path33.join(rootDirectory,file5.path)))).map((file5)=>{if(receiptOnlyProjectGeneratedLegacyPromptPaths.has(file5.path)&&pathLexists(path33.join(rootDirectory,file5.path))){copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});const{ownership:_ownership,...scaffoldFile}=file5;return{...scaffoldFile,sha256:hashPath(expectedDirectory,file5.path)??""}}if(ownershipDecisions.get(file5.path)==="project-generated-current"&&file5.path!==reconciledSubagentManifestPath&&!(projectionEvidenceNeedsPublication&&file5.kind==="projection-receipt"&&file5.obligation?.producer==="harness-projection")){copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});const ownership=desiredOwnershipEvidence.get(file5.path)??previousFilesByPath.get(file5.path)?.ownership;return{...file5,...ownership===undefined?{}:{ownership},sha256:hashPath(expectedDirectory,file5.path)??""}}return managedClaudeCopyPaths.has(file5.path)?{...file5,sha256:hashPath(expectedDirectory,file5.path)??""}:file5}),...stagedLegacyClaudeSymlinkFiles,...preservedManagedClaudeCopyFiles,...preservedExplicitProjectGeneratedFiles,...preservedContextEvidence].toSorted((left,right)=>left.path.localeCompare(right.path));const expectedManifestPath=path33.join(expectedDirectory,scaffoldManifestFile);const expectedManifest=readRequiredJsonObject(expectedManifestPath,"Scaffold manifest is not a JSON object");if(preservedContextEvidence.length>0){expectedManifest.generatedFiles=[...new Set([...isStringArray2(expectedManifest.generatedFiles)?expectedManifest.generatedFiles:[],...preservedContextEvidence.map(({path:relativePath})=>relativePath)])].toSorted();if(preservedContextEvidence.some(({kind})=>kind==="context-plan")){expectedManifest.contextPlanFile=".devpunks/context-plan.json"}if(preservedContextEvidence.some(({kind})=>kind==="projection-receipt")){const projectionReceiptFile=".devpunks/harness-projection-receipt.json";const projectionReceipt=readRequiredJsonObject(path33.join(expectedDirectory,projectionReceiptFile),`Projection receipt is not a JSON object: ${projectionReceiptFile}`);expectedManifest.projectionReceiptFile=projectionReceiptFile;if(typeof projectionReceipt.status==="string"){expectedManifest.projectionStatus=projectionReceipt.status}}}const expectedManagedPaths=new Set(expectedManagedFiles2.map(({path:relativePath})=>relativePath));const expectedManagedFileTypes2=Object.fromEntries([...expectedManagedPaths].map((relativePath)=>[relativePath,lstatSync8(path33.join(expectedDirectory,relativePath)).isSymbolicLink()?"symlink":"file"]));expectedManifest.managedFiles=(manifest.managedFiles??[]).map(({ownership,...file5})=>ownership?._tag==="ProjectGenerated"?{...file5,ownership}:file5);expectedManifest.managedFileTypes=manifest.managedFileTypes??{};expectedManifest.managedFileModes=manifest.managedFileModes??{};expectedManifest.managedDependencies=manifest.managedDependencies??[];expectedManifest.managedStructuredEntries=manifest.managedStructuredEntries??[];writeFileSync7(expectedManifestPath,encodePrettyJson2(expectedManifest));const reconciliationFilePaths=new Set(expected.desiredState.files.map(({path:relativePath})=>relativePath));const applicationPriorReceipt2={...expected.priorReceipt,files:[...expected.priorReceipt.files.filter(({path:relativePath})=>!consumerOwnedClaudePaths.has(relativePath)&&(reconciliationFilePaths.has(relativePath)||ownershipDecisions.get(relativePath)==="ownership-unknown"||ownershipDecisions.get(relativePath)==="project-generated-missing")),...expectedManagedFiles2.filter(({path:relativePath,kind})=>!reconciliationFilePaths.has(relativePath)&&!(projectionEvidenceNeedsPublication&&kind==="projection-receipt")).map((file5)=>{const absolutePath=path33.join(expectedDirectory,file5.path);const type2=lstatSync8(absolutePath).isSymbolicLink()?"symlink":"file";return{...file5,mode:type2==="symlink"?null:fileMode2(lstatSync8(absolutePath).mode),ownership:file5.ownership??{_tag:"ScaffoldManaged"},type:type2}})].toSorted((left,right)=>left.path.localeCompare(right.path))};const stagedChanges2=buildChanges({expectedDirectory,expectedFiles:expectedManagedFiles2.filter((file5)=>(file5.kind!=="context-plan"||contextEvidenceNeedsRefresh)&&file5.kind!=="projection-receipt"&&(ownershipDecisions.get(file5.path)!=="project-generated-current"||file5.path===reconciledSubagentManifestPath)),previousFiles,rootDirectory});return{applicationPriorReceipt:applicationPriorReceipt2,expectedManagedFileTypes:expectedManagedFileTypes2,expectedManagedFiles:expectedManagedFiles2,stagedChanges:stagedChanges2}};const{applicationPriorReceipt,expectedManagedFiles,expectedManagedFileTypes,stagedChanges}=prepareManagedState();const compileManagedChanges=async()=>{const changesByPath=new Map;const applicableObservedChanges=observedComparison.changedFiles.filter(({path:relativePath})=>ownershipDecisions.get(relativePath)!=="project-generated-missing"&&pathLexists(path33.join(expectedDirectory,relativePath)));const reportedMissingOwnershipChanges=observedComparison.changedFiles.filter(({path:relativePath})=>ownershipDecisions.get(relativePath)==="project-generated-missing"||!pathLexists(path33.join(expectedDirectory,relativePath)));mergePrioritizedChanges(changesByPath,[...stagedChanges,...applicableObservedChanges]);const changes2=[...changesByPath.values()].toSorted((left,right)=>left.path.localeCompare(right.path));const legacyRequiredToolsPromptChanges2=buildLegacyRequiredToolsPromptChanges({rootDirectory}).filter(({path:relativePath})=>ownershipDecisions.get(relativePath)!=="project-generated-current"||!explicitProjectGeneratedPaths.has(relativePath));const gitignoreChanges2=await buildGitignoreCleanup({expectedDirectory,rootDirectory});const wikiAlignment2=expectedWikiAlignment;const allChangesByPath=new Map;mergePrioritizedChanges(allChangesByPath,[...changes2,...reportedMissingOwnershipChanges,...legacyRequiredToolsPromptChanges2,...gitignoreChanges2,...wikiAlignment2?.changes??[],...settingsChanges]);const allChanges2=[...allChangesByPath.values()].filter(({path:relativePath})=>!blockedQualityPaths.has(relativePath)).toSorted((left,right)=>left.path.localeCompare(right.path));const expectedPaths=new Set([...expectedManagedFiles.map((file5)=>file5.path),...legacyRequiredToolsPromptChanges2.map((file5)=>file5.path),...wikiAlignment2?.expectedFiles.map((file5)=>file5.path)??[]]);const structuredConfigurationFiles=new Set([".claude/settings.json",".cursor/hooks.json",repoSettingsDisplayFile]);const staleFiles2=removableStaleManagedFiles({plan:reconciliationPlan,reconciliationPaths,staleFiles:[...new Set(previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter((file5)=>ownershipDecisions.get(file5.path)!=="project-generated-current"&&ownershipDecisions.get(file5.path)!=="project-generated-missing"&&ownershipDecisions.get(file5.path)!=="ownership-unknown").filter((file5)=>!consumerOwnedClaudePaths.has(file5.path)).map((file5)=>file5.path).filter((file5)=>!hasIgnoredWikiAlignmentPath(file5)).filter((file5)=>!structuredConfigurationFiles.has(file5)).filter((file5)=>!expectedPaths.has(file5)).filter((file5)=>!blockedQualityPaths.has(file5)))]});const ownershipMetadata=(files,fileTypes)=>{const ownedFiles=files.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile&&!reconciliationPaths.has(relativePath)&&ownershipDecisions.get(relativePath)!=="project-generated-missing");const ownedPaths=new Set(ownedFiles.map(({path:relativePath})=>relativePath));return stableJsonStringify({fileTypes:Object.fromEntries(Object.entries(fileTypes).filter(([relativePath])=>ownedPaths.has(relativePath)).toSorted(([left],[right])=>left.localeCompare(right))),files:ownedFiles.map(({path:relativePath,kind,ownership})=>({kind,ownership:ownership?._tag==="ProjectGenerated"?ownership:null,path:relativePath})).toSorted((left,right)=>left.path.localeCompare(right.path))})};const hasOwnershipMetadataUpdate2=previousFiles.some(({path:relativePath})=>relativePath===scaffoldManifestFile)||manifest.managedFileTypes?.[scaffoldManifestFile]!==undefined||previousFiles.some(({path:relativePath})=>consumerOwnedClaudePaths.has(relativePath))||(()=>{const previousPaths=new Set(previousFiles.map(({path:relativePath})=>relativePath));const expectedMetadataPaths=new Set(expectedManagedFiles.map(({path:relativePath})=>relativePath));return ownershipMetadata(previousFiles.filter(({path:relativePath})=>expectedMetadataPaths.has(relativePath)),manifest.managedFileTypes??{})!==ownershipMetadata(expectedManagedFiles.filter(({path:relativePath})=>previousPaths.has(relativePath)),expectedManagedFileTypes)})();const hasManagedUpdates2=allChanges2.length>0||staleFiles2.length>0||hasOwnershipMetadataUpdate2||reconciliationPlan.actions.length>0||reconciliationPlan.conflicts.length>0||reconciliationPlan.failures.length>0;const hasReceiptRefresh2=manifest.pendingPublication!==undefined||(manifest.scaffoldDegradations?.length??0)>0||reconciliationPlan.skips.some((skip)=>{if(skip.item!=="file"||skip.receiptEntry===null||ownershipDecisions.get(skip.identity)!=="scaffold-managed"){return false}const previous=applicationPriorReceipt.files.find(({path:relativePath})=>relativePath===skip.identity);return previous!==undefined&&stableJsonStringify(previous)!==stableJsonStringify(skip.receiptEntry)});const needsAttention2=[hasManagedUpdates2,packDrift,baselineDrift,qualityFindings.length>0].some(Boolean);const driftPrompt2=packDrift?packDriftPrompt({finalPacks,resolvedPacks,rootDirectory}):null;return{allChanges:allChanges2,changes:changes2,driftPrompt:driftPrompt2,gitignoreChanges:gitignoreChanges2,hasManagedUpdates:hasManagedUpdates2,hasOwnershipMetadataUpdate:hasOwnershipMetadataUpdate2,hasReceiptRefresh:hasReceiptRefresh2,legacyRequiredToolsPromptChanges:legacyRequiredToolsPromptChanges2,needsAttention:needsAttention2,staleFiles:staleFiles2,wikiAlignment:wikiAlignment2}};const{allChanges,changes,driftPrompt,gitignoreChanges,hasManagedUpdates,hasOwnershipMetadataUpdate,hasReceiptRefresh,legacyRequiredToolsPromptChanges,needsAttention,staleFiles,wikiAlignment}=yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to build scaffold update plan."}),try:compileManagedChanges});const directApplicationPaths=new Set([...changes.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath)),...gitignoreChanges,...legacyRequiredToolsPromptChanges,...wikiAlignment?.changes??[],...settingsChanges.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))].map(({path:relativePath})=>relativePath));const decideApplication=()=>gen2(function*decideScaffoldApplication(){const presentUpdatePlan=()=>gen2(function*presentScaffoldUpdatePlan(){if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"RecordedPacks",packs:finalPacks});yield*interaction.emit({_tag:"Baseline",active:baseline.summary,drift:baselineDrift,recordedVersion:typeof manifestBaseline?.version==="string"?manifestBaseline.version:null});if(packDrift){yield*interaction.emit({_tag:"PackDrift",baseline,prompt:driftPrompt??"",resolved})}yield*interaction.emit({_tag:"ManagedChanges",changes:allChanges});if(staleFiles.length>0){yield*interaction.emit({_tag:"StaleFiles",files:staleFiles})}}yield*writeHuman(renderCommandSection("Update Detection",formatDetectionSummary(detection)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Recorded Packs",finalPacks.length===0?"∅":finalPacks.map((pack)=>`• ${pack}`).join(`
2520
2520
  `)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Baseline",[`active: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}`,`recorded: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}`,`drift: ${baselineDrift?"yes":"no"}`].join(`
2521
2521
  `)));if(packDrift){yield*writeHuman("");yield*writeHuman(renderCommandSection("Pack Drift",["Current package manifests resolve to a different scaffold pack set.","",formatResolvedPackSummary({baseline,defaultPacks:resolved.defaultPacks,detectedPacks:resolved.detectedPacks,languagePacks:resolved.languagePacks,optionalPacks:resolved.optionalPacks,surfacePacks:resolved.surfacePacks}),"","Re-setup prompt:",driftPrompt].join(`
2522
2522
  `)))}yield*writeHuman("");yield*writeHuman(renderCommandSection("Managed Changes",summarizeChanges2(allChanges)));if(staleFiles.length>0){yield*writeHuman("");yield*writeHuman(renderCommandSection("Stale Managed Files",summarizeStaleFiles2(staleFiles)))}});yield*presentUpdatePlan();const applyRequested2=!check2;const unsafeBundledBaselineDrift=applyRequested2&&baselineDrift&&baseline.summary.source==="bundled"&&!allowBundledBaselineDriftApply;if(unsafeBundledBaselineDrift){return yield*fail6(new CliValidationError({message:["Refusing to apply bundled scaffold assets because the recorded scaffold baseline differs from the active bundled baseline.",`Recorded baseline: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}.`,`Active baseline: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}.`,"Run `hi update --baseline stable --refresh-baseline` when online, upgrade the global `hi`/`hint` CLI if it cannot resolve stable, or pass `--baseline bundled` only when you intentionally want the bundled baseline."].join(`
2523
2523
  `)}))}return applyRequested2});const applyRequested=yield*decideApplication();const shouldApply=applyRequested&&(hasManagedUpdates||baselineDrift||hasReceiptRefresh||projectionEvidenceNeedsRecovery||needsLocalQualitySetup(expected.desiredState,rootDirectory));const bootstrapRequiredTools=()=>gen2(function*bootstrapScaffoldTools(){if(!applyRequested||!ensureTools2||settingsRequiredTools.length===0){return[]}const requiredTools=settingsRequiredTools;if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"EnsuringTools",toolIds:requiredTools})}yield*writeHuman("");yield*writeHuman(renderHint(`Ensuring required tools: ${requiredTools.join(", ")}`));const statuses=ensureToolsInstalledBestEffort(requiredTools,baseline,resolvedToolRuntime,{stdio:toolStdio});yield*writeHuman(renderCommandSection("Tool bootstrap",statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
2524
- `)));const failureDetails=formatToolBootstrapFailureDetails(statuses);if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"ToolBootstrap",statuses});if(failureDetails!==null){yield*interaction.emit({_tag:"ToolBootstrapWarning",statuses})}}if(failureDetails!==null){yield*writeHuman("");yield*writeHuman(renderCommandSection("Tool Bootstrap Warning",failureDetails))}return statuses});const plannedReconciliation={outcomes:scaffoldReconciliationPlanOutcomes(reconciliationPlan),plannedActions:reportedReconciliationActions,receipt:null,receiptPersisted:false,status:"planned"};const toolBootstrapStatuses=yield*bootstrapRequiredTools();const candidatePreparationPlan={...reconciliationPlan,actions:reconciliationPlan.actions.filter((action2)=>action2.item==="dependency"||action2.item==="structured-entry"),dependencies:reconciliationPlan.dependencies.filter(({action:action2,prerequisite})=>(action2.item==="dependency"||action2.item==="structured-entry")&&(prerequisite.item==="dependency"||prerequisite.item==="structured-entry")),skips:reconciliationPlan.skips.filter((skip)=>skip.item==="dependency"||skip.item==="structured-entry")};const prepareLintCandidate=async(candidate)=>{const candidateSession=createConfinedFilesystemSession(candidate);if(wikiAlignment!==null){for(const change of wikiAlignment.changes){await copyManagedPathConfined({fromDirectory:wikiAlignment.expectedDirectory,outputDirectory:candidate,relativePath:change.path,session:candidateSession})}}const adapters=makeScaffoldReconciliationApplicators({dependencyProcess:()=>{},desiredOwnershipEvidence,priorReceipt:applicationPriorReceipt,rootDirectory:candidate,session:candidateSession});await runPromise2(applyScaffoldReconciliation({adapters:{...adapters,persistReceipt:()=>void_3},plan:candidatePreparationPlan,priorReceipt:applicationPriorReceipt}))};const lintPreviewFacts=shouldRunLintPreview({desiredState:expected.desiredState,shouldApply})?yield*executeLintPreview({lintPreview,plannedPackageRoots:[...new Set([...expected.desiredState.dependencies.map(({workspace})=>workspace),...expected.desiredState.contextPlan.scopes.filter(({contributions})=>contributions.some(({kind})=>kind==="commit-gate")).map((scope3)=>scope3.authoring?.path??(scope3.id==="root"?".":scope3.id)).filter((root)=>plannedDetection.manifests.some(({relativePath})=>path33.posix.basename(relativePath.replaceAll("\\","/"))==="package.json"&&path33.posix.dirname(relativePath.replaceAll("\\","/"))===root))])].toSorted(),prepareCandidate:prepareLintCandidate,removePaths:lintPreviewRemovalPaths(reconciliationPlan),rootDirectory,stagedRoot:expectedDirectory}):undefined;const lintPreviewBlocked=lintPreviewFacts?.status==="operational-failure";const canApply=shouldApply&&!lintPreviewBlocked;const applyManagedChanges=()=>gen2(function*applyScaffoldChanges(){if(!canApply){return plannedReconciliation}const invalidManagedShellFailure=reconciliationPlan.failures.find((failure)=>failure._tag==="InvalidScaffoldObservationFailure"&&failure.item==="structured-entry"&&(manifest.managedStructuredEntries??[]).some((entry)=>entry.kind==="required-shell-segment"&&structuredObservationIdentity(entry)===failure.identity));if(invalidManagedShellFailure!==undefined){return yield*fail6(new CliValidationError({message:invalidManagedShellFailure.message}))}yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:"Failed to record pending scaffold publication."}),try:async()=>{const current=readRequiredJsonObject(path33.join(rootDirectory,scaffoldManifestFile),"Scaffold manifest is missing before publication.");current.pendingPublication={dependencies:expected.desiredState.dependencies.map(({name:name2,section:section2,version:dependencyVersion,workspace})=>({name:name2,section:section2,version:dependencyVersion,workspace})),inputIdentity:publicationInputIdentity,structuredEntries:expected.desiredState.structuredEntries.map(({file:file5,kind,path:entryPath,value:value5})=>({file:file5,kind,path:entryPath,value:value5})),version:"1"};await writeJsonDocument({absolutePath:path33.join(rootDirectory,scaffoldManifestFile),document:current,rootDirectory,session:filesystemSession})}});yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to snapshot pre-existing skill homes."}),try:async()=>{await snapshotPreExistingSkillHomes(rootDirectory,filesystemSession)}});yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to apply managed files."}),try:async()=>{for(const change of changes.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const change of gitignoreChanges){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const change of legacyRequiredToolsPromptChanges){await rewriteLegacyRequiredToolsPrompt({relativePath:change.path,rootDirectory,session:filesystemSession})}if(wikiAlignment!==null){for(const change of wikiAlignment.changes){await copyManagedPathConfined({fromDirectory:wikiAlignment.expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}}for(const change of settingsChanges.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const staleFile of staleFiles){await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session:filesystemSession,targetPath:resolveContainedReceiptPath(rootDirectory,staleFile,{followLeaf:false})})}}});const applicationPlan={...reconciliationPlan,skips:reconciliationPlan.skips.filter((skip)=>skip.item!=="file"||!consumerOwnedClaudePaths.has(skip.identity))};const defaultApplicators=makeScaffoldReconciliationApplicators({dependencyProcess,desiredOwnershipEvidence,priorReceipt:applicationPriorReceipt,rootDirectory,session:filesystemSession});const applicationApplicators=reconciliationApplicators?.(defaultApplicators)??defaultApplicators;const application=yield*applyScaffoldReconciliation({adapters:{...applicationApplicators,persistReceipt:(receipt)=>completeLocalQualitySetup({desiredState:expected.desiredState,process:dependencyProcess,rootDirectory,session:filesystemSession}).pipe(mapError3(scaffoldReceiptFailure),andThen2(applicationApplicators.persistReceipt(receipt)))},plan:applicationPlan,priorReceipt:applicationPriorReceipt}).pipe(catchTag2("@punks/cli/scaffold-state/ScaffoldApplicationFailures",({failures,partialResult})=>{const validationFailure=scaffoldApplicationValidationFailure(failures);return validationFailure===undefined?succeed6(partialResult):fail6(validationFailure)}));let publishedReceipt=application.receipt;if(application.receiptPersisted&&reconciliationStatus(application.outcomes)==="succeeded"){if(projectionEvidenceNeedsPublication){publishedReceipt=yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to verify projection recovery."}),try:async()=>{for(const file5 of expectedManagedFiles.filter(({kind})=>kind!=="projection-receipt"&&kind!=="manifest")){const livePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const stagedPath=path33.join(expectedDirectory,file5.path);const live=lstatSync8(livePath);const staged=lstatSync8(stagedPath);if(hashPath(rootDirectory,file5.path)!==hashPath(expectedDirectory,file5.path)||live.isSymbolicLink()!==staged.isSymbolicLink()||!live.isSymbolicLink()&&fileMode2(live.mode)!==fileMode2(staged.mode)){throw new Error(`Current output failed projection recovery verification: ${file5.path}`)}}for(const input2 of expectedOutput.scopedAuthoringValidationInputs){const content=await readConfinedRegularFile({outputDirectory:rootDirectory,session:filesystemSession,targetPath:path33.join(rootDirectory,input2.path)});if(content===null||hashManagedFileContent(input2.path,content)!==input2.sha256||fileMode2(lstatSync8(path33.join(rootDirectory,input2.path)).mode)!==input2.mode){throw new Error(`Scoped authoring input changed before receipt publication: ${input2.path}`)}}const proof=expectedManagedFiles.find(({kind})=>kind==="projection-receipt");if(proof===undefined){throw new Error("Projection recovery produced no verified receipt.")}const generatedProof=expectedOutput.managedFiles.find((file5)=>file5.path===proof.path&&file5.kind==="projection-receipt"&&file5.obligation?.producer==="harness-projection");if(generatedProof===undefined||hashPath(expectedDirectory,proof.path)!==generatedProof.sha256){throw new Error("Generated projection receipt changed before publication.")}const receipt=decodeGeneratedProjectionReceipt(readFileSync15(path33.join(expectedDirectory,proof.path),"utf-8"));const contextPlanPath=expectedOutput.managedFiles.find(({kind})=>kind==="context-plan")?.path;if(contextPlanPath===undefined||readRequiredJsonObject(path33.join(expectedDirectory,contextPlanPath),"Generated context plan is invalid.").version!==receipt.contextPlanVersion){throw new Error("Generated projection receipt disagrees with its context plan.")}await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:proof.path,session:filesystemSession});if(hashPath(rootDirectory,proof.path)!==proof.sha256){throw new Error("Projection receipt changed during publication.")}return{...application.receipt,files:[...application.receipt.files.filter(({path:relativePath})=>relativePath!==proof.path),{...proof,...receiptForFile({kind:proof.kind,relativePath:proof.path,rootDirectory})}].toSorted((left,right)=>left.path.localeCompare(right.path))}}});yield*applicationApplicators.persistReceipt(publishedReceipt).pipe(mapError3((cause)=>new CliValidationError({cause,message:"Failed to publish recovered projection receipt."})))}yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to publish scaffold adoption."}),try:async()=>{const current=readRequiredJsonObject(path33.join(rootDirectory,scaffoldManifestFile),"Scaffold receipt is missing after application.");const adopted=readRequiredJsonObject(path33.join(expectedDirectory,scaffoldManifestFile),"Planned scaffold manifest is missing.");delete adopted.pendingPublication;for(const key of["managedFiles","managedFileTypes","managedFileModes","managedDependencies","managedStructuredEntries","scaffoldDegradations"]){adopted[key]=current[key]}await writeJsonDocument({absolutePath:path33.join(rootDirectory,scaffoldManifestFile),document:adopted,rootDirectory,session:filesystemSession})}})}return{...application,plannedActions:reportedReconciliationActions,receipt:publishedReceipt,status:reconciliationStatus(application.outcomes)}});const reconciliation=yield*applyManagedChanges();const hasMissingOwnershipDrift=allChanges.some(({path:relativePath})=>ownershipDecisions.get(relativePath)==="project-generated-missing");const operationChangeState=(change)=>canApply&&ownershipDecisions.get(change.path)!=="project-generated-missing"?"completed":"planned";const buildManagedDriftDegradations=()=>[...projectionEvidenceNeedsRecovery&&(!canApply||reconciliation.status!=="succeeded")?[{code:"projection-evidence-invalid",subject:manifest.projectionReceiptFile??".devpunks/harness-projection-receipt.json"}]:[],...check2&&hasManagedUpdates||hasMissingOwnershipDrift?[{code:"managed-drift",subject:"managed-scaffold"}]:[],...manifest.pendingPublication!==undefined&&(!canApply||reconciliation.status!=="succeeded")?[{code:manifest.pendingPublication.inputIdentity===publicationInputIdentity?"publication-pending":"publication-stale",subject:scaffoldManifestFile}]:[]];const managedDriftDegradations=buildManagedDriftDegradations();const finalizeUpdateResult=()=>{const checkResultDetails=check2?{obligationFindings:observedComparison.obligationFindings,qualityFindings}:{};const checkFailed=check2&&(needsAttention||projectionEvidenceNeedsRecovery||qualityFindings.length>0||observedComparison.obligationFindings.some((finding)=>finding.status!=="healthy"));const buildFinalResult=()=>{const toolBootstrapFailed=toolBootstrapStatuses.some((entry)=>entry.status==="failed");const operationIssues=[...lintPreviewIssues(lintPreviewFacts),...reconciliation.outcomes.flatMap((outcome)=>outcome._tag==="ScaffoldActionFailed"&&is2(LocalQualitySetupFailure)(outcome.failure.cause)?[{action:"setup-local-quality",code:"local-quality-setup-failed",errorMessage:outcome.failure.cause.message,kind:"handled-failure",subject:outcome.identity}]:[]),...toolBootstrapStatuses.filter((entry)=>entry.status==="failed").map((entry)=>({action:"bootstrap",code:entry.toolId,errorMessage:entry.errorMessage,kind:"handled-failure",subject:entry.toolId})),...reconciliation?.status==="failed"?[{action:"reconcile",code:"reconciliation-failed",kind:"handled-failure",subject:"managed-scaffold"}]:[]];const finalBaselineDrift=baselineDrift&&(!shouldApply||reconciliation.status!=="succeeded");const unresolvedPackDrift=packDrift&&(!shouldApply||reconciliation.status!=="succeeded");const operationDegradations=[...managedDriftDegradations,...authoringFindings.map((finding)=>({code:finding.code,subject:finding.scopeId??agentHandoffFile2})),...unresolvedPackDrift?[{code:"pack-drift",subject:"packs"}]:[],...finalBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[],...reconciliation?.status==="partial"?[{code:"reconciliation-partial",subject:"managed-scaffold"}]:[],...reconciliation.outcomes.filter((outcome)=>outcome._tag==="ScaffoldConflictPreserved").map((outcome)=>({code:"scaffold-conflict-preserved",subject:outcome.identity}))];const operationChanges=[...allChanges.filter((change)=>!reconciliationPaths.has(change.path)||directApplicationPaths.has(change.path)).map((change)=>({action:change.status,state:operationChangeState(change),subject:change.path})),...staleFiles.filter((subject)=>!reconciliationPaths.has(subject)).map((subject)=>({action:"remove",state:canApply?"completed":"planned",subject})),...reportedReconciliationActions.map((action2)=>({action:action2.operation,state:canApply&&reconciliation.outcomes.some((outcome)=>outcome._tag==="ScaffoldActionSucceeded"&&outcome.identity===action2.identity&&outcome.item===action2.item&&outcome.operation===action2.operation)?"completed":"planned",subject:action2.identity})),...ownershipMetadataOperationChanges({allChanges,applied:canApply,required:hasOwnershipMetadataUpdate})];appendProjectionRecoveryChange(operationChanges,{applied:canApply&&reconciliation.status==="succeeded",needed:projectionEvidenceNeedsRecovery,path:manifest.projectionReceiptFile});const applied=operationChanges.some(({state})=>state==="completed");const operationStatus=(()=>{if(operationIssues.length>0){return operationChanges.some(({state})=>state==="completed")?"partial":"failed"}if(operationDegradations.length>0){return"degraded"}if(applied){return"success"}return operationChanges.length>0?"planned":"no-op"})();const operationResult={changes:operationChanges,degradations:operationDegradations,issues:operationIssues,nextActions:operationStatus==="no-op"||operationStatus==="success"?[{kind:"none"}]:[...toolBootstrapFailed?[{kind:"run",subject:"hi tools ensure"}]:[],...operationDegradations.length>0||operationIssues.some((issue)=>issue.action!=="bootstrap")?[{kind:"review",subject:"managed-scaffold"}]:[]],status:operationStatus,warnings:[...lintPreviewWarnings(lintPreviewFacts),...finalBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[]],...lintPreviewFacts===undefined?{}:{facts:lintPreviewFacts}};const result4={applied,baselineDrift:finalBaselineDrift,changedFiles:allChanges,checkFailed,driftPrompt,finalPacks:updateFinalPacks,...checkResultDetails,operation:operationResult,packDrift,reconciliation,repoShapeMode,resolvedPacks,rootDirectory,scaffoldManifestFile,staleFiles,toolBootstrapStatuses};return result4};return gen2(function*finalizeScaffoldUpdate(){const result4=buildFinalResult();yield*writeHuman("");yield*writeHuman(renderCommandSection("Update Complete",[updateCompleteMessage({applied:result4.applied,applyRequested,hasManagedUpdates}),`Changed files: ${allChanges.length}`,`Stale files: ${staleFiles.length}`,`Manifests scanned: ${manifestPaths(detection).join(", ")||"∅"}`,"Agent-facing authoring: activate `writing-for-agents`, then `rule-authoring`, before reconciling prompt specs, scoped guidance, or `.agents/rules/`.","Guidance: preserve project-owned `.agents/rules/`; each scoped `AGENTS.md` carries one exhaustive Rule Registry pointer.","Guidance: root `AGENTS.md` stays skill-table-free.","Guidance: final scoped `AGENTS.md` files use `## Skills`.","Guidance: `Skill | Exact trigger` rows point to installed `.agents/skills/<skill-id>/SKILL.md`; invoke phase skills from the parent goal/handoff flow.","Guidance: update does not detect overlapping skills; follow-up agent owns skill reconciliation.","Skill homes: `.agents/skills`, `.claude/skills`, `.codex/skills`, `.cursor/skills`, `.opencode/skills`.","Exact name/id overlap: keep HI baseline active, remove active local copies or mirrors, archive evidence.","Archive target: `.devpunks/replaced-skills/<skill-id>/...`; inspect `.devpunks/pre-existing-skills` when present.","Non-overlaps stay mirrored; semantic overlap or baseline integration goes to `hi report`."].join(`
2524
+ `)));const failureDetails=formatToolBootstrapFailureDetails(statuses);if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"ToolBootstrap",statuses});if(failureDetails!==null){yield*interaction.emit({_tag:"ToolBootstrapWarning",statuses})}}if(failureDetails!==null){yield*writeHuman("");yield*writeHuman(renderCommandSection("Tool Bootstrap Warning",failureDetails))}return statuses});const plannedReconciliation={outcomes:scaffoldReconciliationPlanOutcomes(reconciliationPlan),plannedActions:reportedReconciliationActions,receipt:null,receiptPersisted:false,status:"planned"};const toolBootstrapStatuses=yield*bootstrapRequiredTools();const candidatePreparationPlan={...reconciliationPlan,actions:reconciliationPlan.actions.filter((action2)=>action2.item==="dependency"||action2.item==="structured-entry"),dependencies:reconciliationPlan.dependencies.filter(({action:action2,prerequisite})=>(action2.item==="dependency"||action2.item==="structured-entry")&&(prerequisite.item==="dependency"||prerequisite.item==="structured-entry")),skips:reconciliationPlan.skips.filter((skip)=>skip.item==="dependency"||skip.item==="structured-entry")};const prepareLintCandidate=async(candidate)=>{const candidateSession=createConfinedFilesystemSession(candidate);if(wikiAlignment!==null){for(const change of wikiAlignment.changes){await copyManagedPathConfined({fromDirectory:wikiAlignment.expectedDirectory,outputDirectory:candidate,relativePath:change.path,session:candidateSession})}}const adapters=makeScaffoldReconciliationApplicators({dependencyProcess:()=>{},desiredOwnershipEvidence,priorReceipt:applicationPriorReceipt,rootDirectory:candidate,session:candidateSession});await runPromise2(applyScaffoldReconciliation({adapters:{...adapters,persistReceipt:()=>void_3},plan:candidatePreparationPlan,priorReceipt:applicationPriorReceipt}))};const lintPreviewFacts=shouldRunLintPreview({desiredState:expected.desiredState,shouldApply})?yield*executeLintPreview({lintPreview,plannedPackageRoots:[...new Set([...expected.desiredState.dependencies.map(({workspace})=>workspace),...expected.desiredState.contextPlan.scopes.filter(({contributions})=>contributions.some(({kind})=>kind==="commit-gate")).map((scope3)=>scope3.authoring?.path??(scope3.id==="root"?".":scope3.id)).filter((root)=>plannedDetection.manifests.some(({relativePath})=>path33.posix.basename(relativePath.replaceAll("\\","/"))==="package.json"&&path33.posix.dirname(relativePath.replaceAll("\\","/"))===root))])].toSorted(),prepareCandidate:prepareLintCandidate,removePaths:lintPreviewRemovalPaths(reconciliationPlan),rootDirectory,stagedRoot:expectedDirectory}):undefined;const lintPreviewBlocked=lintPreviewFacts?.status==="operational-failure";const canApply=shouldApply&&!lintPreviewBlocked;const applyManagedChanges=()=>gen2(function*applyScaffoldChanges(){if(!canApply){return plannedReconciliation}const invalidManagedShellFailure=reconciliationPlan.failures.find((failure)=>failure._tag==="InvalidScaffoldObservationFailure"&&failure.item==="structured-entry"&&(manifest.managedStructuredEntries??[]).some((entry)=>entry.kind==="required-shell-segment"&&structuredObservationIdentity(entry)===failure.identity));if(invalidManagedShellFailure!==undefined){return yield*fail6(new CliValidationError({message:invalidManagedShellFailure.message}))}yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:"Failed to record pending scaffold publication."}),try:async()=>{const current=readRequiredJsonObject(path33.join(rootDirectory,scaffoldManifestFile),"Scaffold manifest is missing before publication.");current.pendingPublication={dependencies:expected.desiredState.dependencies.map(({name:name2,section:section2,version:dependencyVersion,workspace})=>({name:name2,section:section2,version:dependencyVersion,workspace})),inputIdentity:publicationInputIdentity,structuredEntries:expected.desiredState.structuredEntries.map(({file:file5,kind,path:entryPath,value:value5})=>({file:file5,kind,path:entryPath,value:value5})),version:"1"};await writeJsonDocument({absolutePath:path33.join(rootDirectory,scaffoldManifestFile),document:current,rootDirectory,session:filesystemSession})}});yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to snapshot pre-existing skill homes."}),try:async()=>{await snapshotPreExistingSkillHomes(rootDirectory,filesystemSession)}});yield*tryPromise2({catch:(cause)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to apply managed files."}),try:async()=>{for(const change of changes.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const change of gitignoreChanges){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const change of legacyRequiredToolsPromptChanges){await rewriteLegacyRequiredToolsPrompt({relativePath:change.path,rootDirectory,session:filesystemSession})}if(wikiAlignment!==null){for(const change of wikiAlignment.changes){await copyManagedPathConfined({fromDirectory:wikiAlignment.expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}}for(const change of settingsChanges.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:change.path,session:filesystemSession})}for(const staleFile of staleFiles){await removeConfinedPath({outputDirectory:rootDirectory,recursive:true,session:filesystemSession,targetPath:resolveContainedReceiptPath(rootDirectory,staleFile,{followLeaf:false})})}}});const applicationPlan={...reconciliationPlan,skips:reconciliationPlan.skips.filter((skip)=>skip.item!=="file"||!consumerOwnedClaudePaths.has(skip.identity))};const defaultApplicators=makeScaffoldReconciliationApplicators({dependencyProcess,desiredOwnershipEvidence,priorReceipt:applicationPriorReceipt,rootDirectory,session:filesystemSession});const applicationApplicators=reconciliationApplicators?.(defaultApplicators)??defaultApplicators;const application=yield*applyScaffoldReconciliation({adapters:{...applicationApplicators,persistReceipt:(receipt)=>completeLocalQualitySetup({desiredState:expected.desiredState,process:dependencyProcess,rootDirectory,session:filesystemSession}).pipe(mapError3(scaffoldReceiptFailure),andThen2(applicationApplicators.persistReceipt(receipt)))},plan:applicationPlan,priorReceipt:applicationPriorReceipt}).pipe(catchTag2("@punks/cli/scaffold-state/ScaffoldApplicationFailures",({failures,partialResult})=>{const validationFailure=scaffoldApplicationValidationFailure(failures);return validationFailure===undefined?succeed6(partialResult):fail6(validationFailure)}));let publishedReceipt=application.receipt;if(application.receiptPersisted&&reconciliationStatus(application.outcomes)==="succeeded"){if(projectionEvidenceNeedsPublication){publishedReceipt=yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to verify projection recovery."}),try:async()=>{const declaredModes=new Map(expected.desiredState.files.map((file5)=>[file5.path,file5.mode]));for(const file5 of expectedManagedFiles.filter(({kind})=>kind!=="projection-receipt"&&kind!=="manifest")){const livePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const stagedPath=path33.join(expectedDirectory,file5.path);const live=lstatSync8(livePath);const staged=lstatSync8(stagedPath);const declaredMode=declaredModes.get(file5.path);if(hashPath(rootDirectory,file5.path)!==hashPath(expectedDirectory,file5.path)||live.isSymbolicLink()!==staged.isSymbolicLink()||!live.isSymbolicLink()&&declaredMode!==undefined&&fileMode2(live.mode)!==fileMode2(declaredMode)){throw new Error(`Current output failed projection recovery verification: ${file5.path}`)}}for(const input2 of expectedOutput.scopedAuthoringValidationInputs){const content=await readConfinedRegularFile({outputDirectory:rootDirectory,session:filesystemSession,targetPath:path33.join(rootDirectory,input2.path)});if(content===null||hashManagedFileContent(input2.path,content)!==input2.sha256||fileMode2(lstatSync8(path33.join(rootDirectory,input2.path)).mode)!==input2.mode){throw new Error(`Scoped authoring input changed before receipt publication: ${input2.path}`)}}const proof=expectedManagedFiles.find(({kind})=>kind==="projection-receipt");if(proof===undefined){throw new Error("Projection recovery produced no verified receipt.")}const generatedProof=expectedOutput.managedFiles.find((file5)=>file5.path===proof.path&&file5.kind==="projection-receipt"&&file5.obligation?.producer==="harness-projection");if(generatedProof===undefined||hashPath(expectedDirectory,proof.path)!==generatedProof.sha256){throw new Error("Generated projection receipt changed before publication.")}const receipt=decodeGeneratedProjectionReceipt(readFileSync15(path33.join(expectedDirectory,proof.path),"utf-8"));const contextPlanPath=expectedOutput.managedFiles.find(({kind})=>kind==="context-plan")?.path;if(contextPlanPath===undefined||readRequiredJsonObject(path33.join(expectedDirectory,contextPlanPath),"Generated context plan is invalid.").version!==receipt.contextPlanVersion){throw new Error("Generated projection receipt disagrees with its context plan.")}await copyManagedPathConfined({fromDirectory:expectedDirectory,outputDirectory:rootDirectory,relativePath:proof.path,session:filesystemSession});if(hashPath(rootDirectory,proof.path)!==proof.sha256){throw new Error("Projection receipt changed during publication.")}return{...application.receipt,files:[...application.receipt.files.filter(({path:relativePath})=>relativePath!==proof.path),{...proof,...receiptForFile({kind:proof.kind,relativePath:proof.path,rootDirectory})}].toSorted((left,right)=>left.path.localeCompare(right.path))}}});yield*applicationApplicators.persistReceipt(publishedReceipt).pipe(mapError3((cause)=>new CliValidationError({cause,message:"Failed to publish recovered projection receipt."})))}yield*tryPromise2({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to publish scaffold adoption."}),try:async()=>{const current=readRequiredJsonObject(path33.join(rootDirectory,scaffoldManifestFile),"Scaffold receipt is missing after application.");const adopted=readRequiredJsonObject(path33.join(expectedDirectory,scaffoldManifestFile),"Planned scaffold manifest is missing.");delete adopted.pendingPublication;for(const key of["managedFiles","managedFileTypes","managedFileModes","managedDependencies","managedStructuredEntries","scaffoldDegradations"]){adopted[key]=current[key]}await writeJsonDocument({absolutePath:path33.join(rootDirectory,scaffoldManifestFile),document:adopted,rootDirectory,session:filesystemSession})}})}return{...application,plannedActions:reportedReconciliationActions,receipt:publishedReceipt,status:reconciliationStatus(application.outcomes)}});const reconciliation=yield*applyManagedChanges();const hasMissingOwnershipDrift=allChanges.some(({path:relativePath})=>ownershipDecisions.get(relativePath)==="project-generated-missing");const operationChangeState=(change)=>canApply&&ownershipDecisions.get(change.path)!=="project-generated-missing"?"completed":"planned";const buildManagedDriftDegradations=()=>[...projectionEvidenceNeedsRecovery&&(!canApply||reconciliation.status!=="succeeded")?[{code:"projection-evidence-invalid",subject:manifest.projectionReceiptFile??".devpunks/harness-projection-receipt.json"}]:[],...check2&&hasManagedUpdates||hasMissingOwnershipDrift?[{code:"managed-drift",subject:"managed-scaffold"}]:[],...manifest.pendingPublication!==undefined&&(!canApply||reconciliation.status!=="succeeded")?[{code:manifest.pendingPublication.inputIdentity===publicationInputIdentity?"publication-pending":"publication-stale",subject:scaffoldManifestFile}]:[]];const managedDriftDegradations=buildManagedDriftDegradations();const finalizeUpdateResult=()=>{const checkResultDetails=check2?{obligationFindings:observedComparison.obligationFindings,qualityFindings}:{};const checkFailed=check2&&(needsAttention||projectionEvidenceNeedsRecovery||qualityFindings.length>0||observedComparison.obligationFindings.some((finding)=>finding.status!=="healthy"));const buildFinalResult=()=>{const toolBootstrapFailed=toolBootstrapStatuses.some((entry)=>entry.status==="failed");const operationIssues=[...lintPreviewIssues(lintPreviewFacts),...reconciliation.outcomes.flatMap((outcome)=>outcome._tag==="ScaffoldActionFailed"&&is2(LocalQualitySetupFailure)(outcome.failure.cause)?[{action:"setup-local-quality",code:"local-quality-setup-failed",errorMessage:outcome.failure.cause.message,kind:"handled-failure",subject:outcome.identity}]:[]),...toolBootstrapStatuses.filter((entry)=>entry.status==="failed").map((entry)=>({action:"bootstrap",code:entry.toolId,errorMessage:entry.errorMessage,kind:"handled-failure",subject:entry.toolId})),...reconciliation?.status==="failed"?[{action:"reconcile",code:"reconciliation-failed",kind:"handled-failure",subject:"managed-scaffold"}]:[]];const finalBaselineDrift=baselineDrift&&(!shouldApply||reconciliation.status!=="succeeded");const unresolvedPackDrift=packDrift&&(!shouldApply||reconciliation.status!=="succeeded");const operationDegradations=[...managedDriftDegradations,...authoringFindings.map((finding)=>({code:finding.code,subject:finding.scopeId??agentHandoffFile2})),...unresolvedPackDrift?[{code:"pack-drift",subject:"packs"}]:[],...finalBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[],...reconciliation?.status==="partial"?[{code:"reconciliation-partial",subject:"managed-scaffold"}]:[],...reconciliation.outcomes.filter((outcome)=>outcome._tag==="ScaffoldConflictPreserved").map((outcome)=>({code:"scaffold-conflict-preserved",subject:outcome.identity}))];const operationChanges=[...allChanges.filter((change)=>!reconciliationPaths.has(change.path)||directApplicationPaths.has(change.path)).map((change)=>({action:change.status,state:operationChangeState(change),subject:change.path})),...staleFiles.filter((subject)=>!reconciliationPaths.has(subject)).map((subject)=>({action:"remove",state:canApply?"completed":"planned",subject})),...reportedReconciliationActions.map((action2)=>({action:action2.operation,state:canApply&&reconciliation.outcomes.some((outcome)=>outcome._tag==="ScaffoldActionSucceeded"&&outcome.identity===action2.identity&&outcome.item===action2.item&&outcome.operation===action2.operation)?"completed":"planned",subject:action2.identity})),...ownershipMetadataOperationChanges({allChanges,applied:canApply,required:hasOwnershipMetadataUpdate})];appendProjectionRecoveryChange(operationChanges,{applied:canApply&&reconciliation.status==="succeeded",needed:projectionEvidenceNeedsRecovery,path:manifest.projectionReceiptFile});const applied=operationChanges.some(({state})=>state==="completed");const operationStatus=(()=>{if(operationIssues.length>0){return operationChanges.some(({state})=>state==="completed")?"partial":"failed"}if(operationDegradations.length>0){return"degraded"}if(applied){return"success"}return operationChanges.length>0?"planned":"no-op"})();const operationResult={changes:operationChanges,degradations:operationDegradations,issues:operationIssues,nextActions:operationStatus==="no-op"||operationStatus==="success"?[{kind:"none"}]:[...toolBootstrapFailed?[{kind:"run",subject:"hi tools ensure"}]:[],...operationDegradations.length>0||operationIssues.some((issue)=>issue.action!=="bootstrap")?[{kind:"review",subject:"managed-scaffold"}]:[]],status:operationStatus,warnings:[...lintPreviewWarnings(lintPreviewFacts),...finalBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[]],...lintPreviewFacts===undefined?{}:{facts:lintPreviewFacts}};const result4={applied,baselineDrift:finalBaselineDrift,changedFiles:allChanges,checkFailed,driftPrompt,finalPacks:updateFinalPacks,...checkResultDetails,operation:operationResult,packDrift,reconciliation,repoShapeMode,resolvedPacks,rootDirectory,scaffoldManifestFile,staleFiles,toolBootstrapStatuses};return result4};return gen2(function*finalizeScaffoldUpdate(){const result4=buildFinalResult();yield*writeHuman("");yield*writeHuman(renderCommandSection("Update Complete",[updateCompleteMessage({applied:result4.applied,applyRequested,hasManagedUpdates}),`Changed files: ${allChanges.length}`,`Stale files: ${staleFiles.length}`,`Manifests scanned: ${manifestPaths(detection).join(", ")||"∅"}`,"Agent-facing authoring: activate `writing-for-agents`, then `rule-authoring`, before reconciling prompt specs, scoped guidance, or `.agents/rules/`.","Guidance: preserve project-owned `.agents/rules/`; each scoped `AGENTS.md` carries one exhaustive Rule Registry pointer.","Guidance: root `AGENTS.md` stays skill-table-free.","Guidance: final scoped `AGENTS.md` files use `## Skills`.","Guidance: `Skill | Exact trigger` rows point to installed `.agents/skills/<skill-id>/SKILL.md`; invoke phase skills from the parent goal/handoff flow.","Guidance: update does not detect overlapping skills; follow-up agent owns skill reconciliation.","Skill homes: `.agents/skills`, `.claude/skills`, `.codex/skills`, `.cursor/skills`, `.opencode/skills`.","Exact name/id overlap: keep HI baseline active, remove active local copies or mirrors, archive evidence.","Archive target: `.devpunks/replaced-skills/<skill-id>/...`; inspect `.devpunks/pre-existing-skills` when present.","Non-overlaps stay mirrored; semantic overlap or baseline integration goes to `hi report`."].join(`
2525
2525
  `)));if(emitOutput&&emitJson){yield*interaction.emit({_tag:"Json",result:result4})}else if(emitOutput){yield*interaction.emit({_tag:"Complete",applied:result4.applied,applyRequested,changedFiles:allChanges.length,hasManagedUpdates,manifestPaths:manifestPaths(detection),operationStatus:result4.operation.status,staleFiles:staleFiles.length})}if(result4.applied){yield*submitCliEventEffect("cli.scaffold.update.applied",{baseline:{version:baseline.summary.version},configuration,cwd:rootDirectory})}return result4})};return yield*finalizeUpdateResult()}).pipe(ensuring2(sync2(()=>{if(updateStagingDirectory!==null){rmSync5(updateStagingDirectory,{force:true,recursive:true})}if(wikiStagingDirectory!==null){rmSync5(wikiStagingDirectory,{force:true,recursive:true})}})))};var runUpdate=(options4)=>runScaffoldOperation({...options4,operation:"update"});var failureMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var silentUpdateInteraction={emit:()=>void_3};var nonBlankEnvironmentValue=(value5)=>value5!==undefined&&value5.trim().length>0?value5:undefined;var operatorSkillOperationsLayer=effect(OperatorSkillOperations,gen2(function*makeOperatorSkillOperations(){const runtime=yield*CliRuntimeConfig;const skillsCli=yield*SkillsCli;return{run:(action2,targetSelection)=>gen2(function*runOperatorSkillOperation(){const cwd=process.cwd();const migrationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MIGRATION_RETRY);const mutationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MUTATION_RETRY);return yield*executeOperatorAction({action:action2,input:{activeCliVersion:version2,cwd,projectRoot:findOperatorProjectRoot(cwd),targetSelection},...migrationRetryToken===undefined?{}:{migrationRetryToken},...mutationRetryToken===undefined?{}:{mutationRetryToken}})}).pipe(provideService2(SkillsCli,skillsCli))}}));var resolveFeatureBaseline=({baseline,refreshBaseline,rootDirectory,controlPlane,release,runtime,httpClient})=>resolveBaseline(baselineResolveOptions(fromNullishOr(baseline),refreshBaseline,rootDirectory,{controlPlane,release,runtime})).pipe(provideService2(HttpClient,httpClient));var reportSubmissionOperationsLayer=effect(ReportSubmissionOperations,gen2(function*makeReportSubmissionOperations(){const controlPlane=yield*CliControlPlaneConfig;const httpClient=yield*HttpClient;return{cliVersion:version2,observeRepository:observedRepository,recordSubmitted:(rootDirectory)=>submitCliEventEffect("cli.harness.report.submitted",{configuration:controlPlane,cwd:rootDirectory}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"record-submitted"}))),resolveControlPlaneUrl:()=>succeed6(resolveControlPlaneUrl(undefined,controlPlane)),submit:(baseUrl2,report)=>submitHarnessReport({baseUrl:baseUrl2,report}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"submit-report"})))}}));var repositoryCheckOperationsLayer=effect(RepositoryCheckOperations,gen2(function*makeRepositoryCheckOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectProducer=yield*ProjectProducer;const projectSettings=yield*ProjectSettings;return{...release.baseline===undefined?{}:{configuredBaseline:release.baseline},checkUpdate:(input2)=>gen2(function*checkUpdate(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});const update2=yield*runUpdate({baseline,check:true,configuration:controlPlane,emitJson:false,emitOutput:false,interaction:silentUpdateInteraction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,write:false,yes:false}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectProducer,projectProducer));const{operation:_operation,reconciliation:_reconciliation,...publicUpdate}=update2;return{baselineVersion:baseline.summary.version,update:publicUpdate}}).pipe(provideService2(ProjectSettings,projectSettings),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:failureMessage(cause),operation:"check-repository-update"}))),cliVersion:version2,updateTag:release.updateTag}}));var repositoryScaffoldingResult=(result4)=>({machinePayload:{...result4,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))},outputDirectory:result4.outputDirectory,projectionStatus:result4.projectionStatus,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))});var repositoryScaffoldingOperationsLayer=effect(RepositoryScaffoldingOperations,gen2(function*makeRepositoryScaffoldingOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;const scopedScaffoldOperation=yield*ScopedScaffoldOperation;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.kind==="init"?input2.outputDirectory:input2.scanDirectory,runtime});if(input2.kind==="init"){const result5=yield*runStageScaffold({baseline,commandId:"init",configuration:controlPlane,interaction,outputDirectory:input2.outputDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath}).pipe(provideService2(HttpClient,httpClient),provideService2(ScopedScaffoldOperation,scopedScaffoldOperation));return repositoryScaffoldingResult(result5)}const result4=yield*runScaffold({assumeYes:input2.assumeYes,baseline,configuration:controlPlane,emitJson:input2.emitJson,interaction,...input2.outputDirectory===undefined?{}:{outputDirectory:input2.outputDirectory},repoShapeMode:input2.repoShape,scanDirectory:input2.scanDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio}).pipe(provideService2(HttpClient,httpClient),provideService2(ScaffoldCapabilities,scaffoldCapabilities),provideService2(ScopedScaffoldOperation,scopedScaffoldOperation));return repositoryScaffoldingResult(result4)}).pipe(mapError3((cause)=>new RepositoryScaffoldingOperationFailure({cause,message:failureMessage(cause),operation:input2.kind==="init"?"initialize-repository":"setup-repository"})))}}));var scaffoldUpdateOperationsLayer=effect(ScaffoldUpdateOperations,gen2(function*makeScaffoldUpdateOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectProducer=yield*ProjectProducer;const projectSettings=yield*ProjectSettings;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return yield*runUpdate({allowBundledBaselineDriftApply:input2.baseline==="bundled"||release.baseline==="bundled",baseline,check:input2.check,configuration:controlPlane,emitJson:input2.emitJson,emitOutput:false,interaction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio,write:input2.write,yes:input2.yes}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectProducer,projectProducer),provideService2(ProjectSettings,projectSettings))}).pipe(mapError3((cause)=>new ScaffoldUpdateOperationFailure({cause,message:failureMessage(cause),operation:"update-scaffold"})))}}));var toolEnsureOperationsLayer=effect(ToolEnsureOperations,gen2(function*makeToolEnsureOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return ensureTools({baseline,capabilities:scaffoldCapabilities,rootDirectory:input2.rootDirectory,stdio:input2.stdio})}).pipe(mapError3((cause)=>new ToolEnsureOperationFailure({cause,message:failureMessage(cause),operation:"ensure-tools"})))}}));var featureApplicationOperationsLayer=mergeAll2(operatorSkillOperationsLayer,reportSubmissionOperationsLayer,repositoryCheckOperationsLayer,repositoryScaffoldingOperationsLayer,scaffoldUpdateOperationsLayer,toolEnsureOperationsLayer);var encodeJson2=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson3=(value5)=>JSON.stringify(JSON.parse(encodeJson2(value5)),null,2);var yesValues=new Set(["","y","yes"]);var writeLines=(prompt,lines2)=>forEach2(lines2,prompt.writeLine,{discard:true});var renderToolBootstrap=(event)=>{const failureDetails=formatToolBootstrapFailureDetails(event.statuses);return[renderCommandSection(event.phase==="base"?"Base tool check":"Tool bootstrap",event.statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
2526
2526
  `)),...failureDetails===null?[]:["",renderCommandSection("Tool Bootstrap Warning",failureDetails)]]};var renderEvent=(event)=>{switch(event._tag){case"SetupStarted":{return[renderScaffoldTitle(),"",renderSetupIntro()]}case"ToolCheck":{return["",renderHint(`${event.phase==="base"?"Checking base scaffold tools":"Ensuring selected-pack tools"}: ${event.toolIds.join(", ")}`)]}case"ToolBootstrap":{return renderToolBootstrap(event)}case"Detection":{return["",renderCommandSection("Detection",formatDetectionSummary(event.detection))]}case"ResolvedPacks":{return["",renderCommandSection("Resolved packs",formatResolvedPackSummary({...event.resolved,baseline:event.baseline}))]}case"SelectionAccepted":{return["",renderHint("Non-interactive mode: accepting prefilled pack selection.")]}case"SelectionPreview":{return["",renderCommandSection("Selection preview",formatSelectionPreview({addedPacks:event.addedPacks,baseline:event.baseline,finalPacks:event.finalPacks,outputDirectory:event.outputDirectory,preselectedPacks:event.preselectedPacks,removedPacks:event.removedPacks}))]}case"SelectionReopened":{return["",renderHint("Reopening pack selection editor.")]}case"SetupComplete":{const{result:result4}=event;return["",renderCommandSection("Scaffold Complete",["Scaffold files were written successfully.",`Output directory: \`${result4.outputDirectory}\``,`Prompt file: \`${result4.agentSystemPromptFile}\``].join(`
2527
2527
  `)),"",renderCommandSection("Selection",formatConfirmationSummary(result4,event.baseline)),"",renderNotes([`Output directory: ${result4.outputDirectory}`]),...result4.hiddenOutputDirectories.length>0?[renderNotes([`Hidden output directories: ${result4.hiddenOutputDirectories.join(", ")}`])]:[],"",renderCommandSection("Paste Into Your Next Agent",[event.clipboard.ok?`Agent prompt copied to clipboard via \`${event.clipboard.command}\`.`:"Clipboard copy failed. Open the generated prompt file and paste it manually.",`Prompt file: \`${result4.agentSystemPromptFile}\``,`Agent handoff file: \`${result4.agentHandoffFile}\``,`If you are an agent in this terminal, open \`${result4.agentSystemPromptFile}\` and follow it now.`,"Paste the generated agent prompt into your next agent now."].join(`
2528
2528
  `)),...event.emitJson?["",renderDivider(),renderJsonLabel(),encodePrettyJson3(result4)]:[]]}case"InitComplete":{const backlogProviderLabels3={"azure-devops":"Azure DevOps",github:"GitHub Projects and Issues",linear:"Linear",monday:"monday.com"};const wikiFrameworkLabels3={next:"Next.js","tanstack-start":"TanStack Start"};const repositoryManagerLabels={"azure-devops":"Azure DevOps",bitbucket:"Bitbucket",github:"GitHub",gitlab:"GitLab"};return[renderScaffoldTitle(),"",renderStageIntro({body:event.summary,title:"Requirements"}),"",renderCommandSection("Scaffolded skills",event.skillFiles.map((file5)=>`• ${file5}`).join(`
2529
2529
  `)),...event.wikiFiles.length>0?["",renderCommandSection("Scaffolded wiki files",event.wikiFiles.map((file5)=>`• ${file5}`).join(`
2530
2530
  `))]:[],"","",renderNotes([`Output directory: ${event.outputDirectory}`,`Hidden output directories: ${event.hiddenOutputDirectories.join(", ")}`]),"",renderCommandSection("Backlog provider",`${backlogProviderLabels3[event.settings.backlogProvider]} (${event.settings.backlogProvider})`),"",renderCommandSection("Wiki framework",`${wikiFrameworkLabels3[event.wikiFramework]} (${event.wikiFramework})`),"",renderCommandSection("Repository manager",`selected repository manager: ${repositoryManagerLabels[event.settings.repositoryManager]} (\`${event.settings.repositoryManager}\`)`),"",renderCommandSection("Operator prompt",event.operatorPrompt)]}}return event};var selectPacks=(prompt,request)=>{const add3=request.kind==="add";return writeLines(prompt,["",renderCommandSection(add3?"Add optional packs":"Edit prefilled packs",[add3?"Select any extra packs you want to include beyond the prefilled scaffold set.":"Select any removable packs you want to drop from the prefilled scaffold set.","",`available packs: ${request.allowed.length}`].join(`
2531
- `))]).pipe(andThen2(prompt.multiSelect({choices:request.allowed.map((packId)=>{const description=request.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add3?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add3?"Select all optional packs":"Select all removable packs",selectNone:add3?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map6(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map6(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request)=>selectPacks(prompt,request),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map6(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer==="tanstack-start"?answer:"next")});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map6(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync7}from"node:child_process";import{existsSync as existsSync16,lstatSync as lstatSync9,readFileSync as readFileSync16}from"node:fs";import path34 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path34.resolve(rootDirectory);while(true){const gitMarker=path34.join(currentDirectory,".git");if(existsSync16(gitMarker)){execFileSync7("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path34.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var projectSettingsOutputDirectory=(filePath)=>{const parentDirectory=path34.dirname(filePath);return path34.basename(filePath)==="settings.json"&&path34.basename(parentDirectory)===".devpunks"?path34.dirname(parentDirectory):parentDirectory};var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}),try:async()=>{try{await writeConfinedFile({content,outputDirectory:projectSettingsOutputDirectory(filePath),replace:false,...session===undefined?{}:{session},targetPath:filePath});return true}catch(error2){if(hasErrorCode(error2,"EEXIST")){return false}throw error2}}}),directoryExists:(directoryPath,session)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to inspect directory ${directoryPath}.`,operation:"read",path:directoryPath}),try:()=>{if(session!==undefined){assertConfinedDirectory({directoryPath,outputDirectory:session.outputRoot,session})}const exists=existsSync16(directoryPath);if(session!==undefined){assertConfinedFilesystemSession({outputDirectory:session.outputRoot,session})}return exists}}),joinPath:(...segments)=>path34.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync7("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}),try:async()=>{if(session===undefined){try{return some2(readFileSync16(filePath,"utf-8"))}catch(error2){if(isMissingFile2(error2)){return none2()}throw error2}}const content=await readConfinedRegularFile({allowMissing:true,outputDirectory:session.outputRoot,session,targetPath:filePath});return content===null?none2():some2(content.toString("utf-8"))}}),removeEmptyDirectory:(directoryPath,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}),try:async()=>{if(session===undefined&&lstatSync9(directoryPath,{throwIfNoEntry:false})===undefined){return}try{await removeConfinedEmptyDirectory({directoryPath,outputDirectory:session?.outputRoot??path34.dirname(directoryPath),...session===undefined?{}:{session}})}catch(error2){if(!hasErrorCode(error2,"ENOTEMPTY")){throw error2}}}}),removeTextFileIfContent:(filePath,expectedContent,session)=>tryPromise2({catch:(error2)=>cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}.`),try:async()=>{if(session===undefined&&lstatSync9(filePath,{throwIfNoEntry:false})===undefined){return false}return await removeConfinedFileIfContent({expectedContent,outputDirectory:session?.outputRoot??projectSettingsOutputDirectory(filePath),...session===undefined?{}:{session},targetPath:filePath})}}),writeTextFile:(filePath,content,session)=>tryPromise2({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:async()=>{await writeConfinedFile({content,outputDirectory:projectSettingsOutputDirectory(filePath),replace:true,...session===undefined?{}:{session},targetPath:filePath})}})});import{createHash as createHash13}from"node:crypto";import{execFileSync as execFileSync8}from"node:child_process";import{lstatSync as lstatSync10,readFileSync as readFileSync17,readlinkSync as readlinkSync7,realpathSync as realpathSync8}from"node:fs";import path35 from"node:path";var projectProducerFailure=({cause,message,sourcePath})=>new ProjectProducerFailure({cause,message,operation:"derive-project-generated-ownership",sourcePath});var fingerprintRepositoryMirror=fn2("ProjectProducer.fingerprintRepositoryMirror")(function*fingerprintRepositoryMirror2({repositoryRoot,sourcePath}){const absoluteRoot=path35.resolve(repositoryRoot);if(path35.isAbsolute(sourcePath)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source must be relative: ${sourcePath}`,sourcePath})}const absolutePath=path35.resolve(absoluteRoot,sourcePath);const relativePath=path35.relative(absoluteRoot,absolutePath);if(relativePath===""){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source cannot be the repository root: ${sourcePath}`,sourcePath})}if(relativePath===".."||relativePath.startsWith(`..${path35.sep}`)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source escapes repository root: ${sourcePath}`,sourcePath})}const stat3=yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to inspect repository mirror source: ${sourcePath}`,sourcePath}),try:()=>lstatSync10(absolutePath,{throwIfNoEntry:false})});if(stat3===undefined){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source does not exist: ${sourcePath}`,sourcePath})}const[realRoot,realParent]=yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to resolve repository mirror source: ${sourcePath}`,sourcePath}),try:()=>[realpathSync8(absoluteRoot),realpathSync8(path35.dirname(absolutePath))]});const realParentRelative=path35.relative(realRoot,realParent);if(realParentRelative===".."||realParentRelative.startsWith(`..${path35.sep}`)||path35.isAbsolute(realParentRelative)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source escapes repository root through a symlink ancestor: ${sourcePath}`,sourcePath})}if(!stat3.isFile()&&!stat3.isSymbolicLink()){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source must be a regular file or symbolic link: ${sourcePath}`,sourcePath})}yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Repository mirror source must be version-controlled: ${sourcePath}`,sourcePath}),try:()=>execFileSync8("git",["--literal-pathspecs","-C",absoluteRoot,"ls-files","--error-unmatch","--",sourcePath],{stdio:"ignore"})});return yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to fingerprint repository mirror source: ${sourcePath}`,sourcePath}),try:()=>{if(stat3.isSymbolicLink()){const target=readlinkSync7(absolutePath);return{_tag:"Symlink",sha256:createHash13("sha256").update(`symlink:${target}`).digest("hex"),target}}return{_tag:"File",mode:stat3.mode%512,sha256:createHash13("sha256").update(readFileSync17(absolutePath)).digest("hex")}}})});var ProjectProducerLive=succeed5(ProjectProducer,{fingerprintRepositoryMirror});import{spawn as spawn3}from"node:child_process";import{createHash as createHash14}from"node:crypto";import{readFileSync as readFileSync18,realpathSync as realpathSync9}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir9}from"node:os";import path36 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillRelativePath=path36.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var errorCode=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&typeof cause.code==="string"?cause.code:undefined;var processError=(cause)=>{const error2=cause instanceof Error?cause:new Error(String(cause));const code=errorCode(cause);return Object.assign(error2,code===undefined?{}:{code})};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String4),name:String4,path:String4,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request)=>({operation:operation2,scope:request.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index of[0,1,2]){const difference=left[index]-right[index];if(difference!==0){return difference}}return 0};var isContainedPath=(root,candidate)=>{const relative=path36.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path36.sep}`)&&!path36.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn3(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return errorCode(error2)!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(errorCode(error2)!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap3((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??(async(directory3)=>{await rm2(directory3,{force:true,recursive:true})});const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir9();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand(operation2,request,command,args2,cwd,commandLabel,interactive){const result4=yield*callback2((resume)=>{let child;try{child=spawn3(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:interactive??false?["inherit","inherit","pipe"]:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:processError(error2),status:null,stderr:"",stdout:""}));return void_3}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const interactiveMode=interactive??false;const timeout3=timeoutEnabled&&!interactiveMode?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context3=failureContext(operation2,request);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context3,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context3,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context3,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context3,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr.length>0?result4.stderr:result4.error?.message??""})}return result4.stdout});const run6=(operation2,request,args2)=>runCommand(operation2,request,executable,args2,request.cwd,"Skills CLI",operation2!=="list"&&args2[0]!=="--version"&&request.targetSelection==="prompt");const runGit=(request,args2,cwd)=>runCommand("install",request,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request,message,cause)=>new SkillsCliExit({...failureContext("install",request),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const withMaterializedTarget=(request,use)=>acquireUseRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot create a temporary operator-skill checkout",cause),try:async()=>await mkdtemp2(path36.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>gen2(function*materializeTarget(){const checkoutRoot=path36.join(temporaryRoot,"source");yield*runGit(request,["init",checkoutRoot],request.cwd);yield*runGit(request,["remote","add","origin",operatorSkillOrigin],checkoutRoot);yield*runGit(request,["fetch","--depth=1","origin",request.target.revision],checkoutRoot);const fetchedRevision=(yield*runGit(request,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(fetchedRevision!==request.target.revision){return yield*new SkillsCliMalformedOutput({...failureContext("install",request),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync9(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync9(path36.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("install",request),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return yield*use(localSource)}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot clean up the temporary operator-skill checkout",cause),try:async()=>{await removeTemporaryDirectory(temporaryRoot)}}));const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion(operation2,request){const stdout=yield*run6(operation2,request,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(minimumVersion===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request),message:"Configured minimum Skills CLI version is malformed",stdout:minimumSkillsCliVersion})}if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}return null});const verifyListedSkill=(request,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path36.isAbsolute(skill.path)||path36.parse(skill.path).root===path36.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync9(skill.path)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request.target.contentManifest){const normalizedRelativePath=path36.normalize(entry.path);if(entry.path===""||path36.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path36.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path36.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path36.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync9(filePath)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync18(canonicalFilePath)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash14("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request.target.cliCompatibility,revision:request.target.revision,source:request.target.source,version:request.target.version}})};const list2=fn2("SkillsCli.list")(function*list(request){yield*ensureSupportedVersion("list",request);const stdout=yield*run6("list",request,["list",...scopeArguments(request.scope),"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request),message:`Skills CLI list returned a scope other than ${request.scope}`,stdout})}const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}const verification=yield*result2(verifyListedSkill(request,skill,verified()));if(isFailure2(verification)){if(verification.failure.reason==="identity-mismatch"){listed.push({...skill,name:"hi-cli",verification:"outdated"});continue}return yield*verification.failure}listed.push(verification.success)}return listed});const install=fn2("SkillsCli.install")(function*install(request){yield*ensureSupportedVersion("install",request);yield*withMaterializedTarget(request,(localSource)=>run6("install",request,["add",localSource,"--skill","hi-cli",...scopeArguments(request.scope),...request.targetSelection==="automatic"?["--yes"]:[],"--copy"]))});const remove4=fn2("SkillsCli.remove")(function*remove(request){yield*ensureSupportedVersion("remove",request);yield*run6("remove",request,["remove",request.name,...scopeArguments(request.scope),...request.targetSelection==="automatic"?["--yes"]:[]])});return succeed5(SkillsCli,{install,list:list2,remove:remove4})};import path37 from"node:path";var agentSystemPromptFile3=".devpunks/AGENT-SYSTEM-PROMPT.md";var selectedSkills4=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var failure=(operation2,cause,fallback)=>cause instanceof ScopedScaffoldOperationFailure?cause:new ScopedScaffoldOperationFailure({cause,message:cause instanceof Error?cause.message:fallback,operation:operation2});var validationFailure=(cause,fallback)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:fallback});var snapshotInspectInput=(input2)=>structuredClone(input2);var snapshotPlanInput=(input2,inspection)=>({...structuredClone(input2),inspection});var makeScopedScaffoldOperation=({adapter,projectSettings,stage})=>{const inspections=new WeakMap;const plans=new WeakMap;return ScopedScaffoldOperation.of({inspect:fn2("ScopedScaffoldOperation.inspect")(function*inspect(input2){const baselineOrigin=input2.baseline.summary.authoritySource==="bundled"?"bundled":"resolved";const ownedInput=snapshotInspectInput(input2);const binding=yield*tryPromise2({catch:(cause)=>cause instanceof RepositoryScanError?cause:failure("inspect",cause,"Could not bind scaffold output root."),try:async()=>await adapter.bindOutputRoot(ownedInput.outputDirectory,{allowCreate:path37.resolve(ownedInput.outputDirectory)!==path37.resolve(ownedInput.scanDirectory),scanDirectory:ownedInput.scanDirectory})});const inspected=yield*adapter.inspectRepository({baseline:ownedInput.baseline,repoShapeMode:ownedInput.repoShapeMode,rootDirectory:ownedInput.scanDirectory});const filesystemSession=yield*tryPromise2({catch:(cause)=>failure("inspect",cause,"Could not commit scaffold output root."),try:binding.commit});const inspection=structuredClone(inspected);inspections.set(inspection,{baselineOrigin,filesystemSession,input:ownedInput,inspection:structuredClone(inspection)});return inspection}),materialize:fn2("ScopedScaffoldOperation.materialize")(function*materialize(plan){const planned=plans.get(plan);if(planned===undefined){return yield*failure("materialize",new Error("The scaffold plan was not produced by this scoped operation."),"Unknown scaffold plan.")}plans.delete(plan);if(planned._tag==="StageScaffoldPlan"){if(stage===undefined){return yield*failure("materialize",new Error("No staged scaffold adapter is installed."),"Missing staged scaffold adapter.")}return yield*stage.materialize(planned.state)}const{input:input2,inspectionInput,outputOptions}=planned;if(input2._tag!=="PlanRepositoryScaffold"){return yield*failure("materialize",new Error("Repository scaffold plan has an invalid input kind."),"Invalid repository scaffold plan.")}const{contextPlan,desiredState,filesystemSession,settings}=outputOptions;if(desiredState===undefined||contextPlan===undefined){return yield*new CliValidationError({message:"Repository scaffold plan has no desired state."})}if(filesystemSession===undefined){return yield*failure("materialize",new Error("The scaffold plan has no confined filesystem session."),"Missing confined filesystem session.")}const settingsExist=yield*projectSettings.read(inspectionInput.outputDirectory,filesystemSession).pipe(as2(true),catchTag2("ProjectSettingsMissing",()=>succeed6(false)),mapError3((cause)=>validationFailure(cause,cause.message)));const scaffoldOutput=yield*adapter.writeOutput(outputOptions).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold output failed.")));if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Scaffold output did not produce harness projection evidence."})}yield*completeLocalQualitySetup({desiredState:{contextPlan,dependencies:desiredState.dependencies,files:desiredState.files,settings:settings??{}},rootDirectory:inspectionInput.outputDirectory,session:filesystemSession}).pipe(mapError3((cause)=>validationFailure(cause,"Local quality setup failed.")));yield*tryPromise2({catch:(cause)=>validationFailure(cause,"Scaffold gitignore cleanup failed."),try:async()=>{await adapter.cleanupGitignore(scaffoldOutput.outputDirectory,filesystemSession)}});if(settingsExist){yield*projectSettings.write(scaffoldOutput.outputDirectory,{_tag:"ScaffoldChange",baselineVersion:scaffoldOutput.baseline.version,cliVersion:version2,requiredTools:input2.requiredTools},filesystemSession).pipe(mapError3((cause)=>validationFailure(cause,cause.message)))}const{detection,packs:resolved}=input2.inspection;const resultInput={addedPacks:input2.addedPacks,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile3,baseline:scaffoldOutput.baseline,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:inspectionInput.scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks:input2.finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile3],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:adapter.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:input2.removedPacks,repoShapeMode:inspectionInput.repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses:input2.toolBootstrapStatuses};const agentSystemPrompt=formatAgentHandoffSummary(resultInput);const writtenAgentSystemPromptFile=yield*tryPromise2({catch:(cause)=>validationFailure(cause,"Agent system prompt write failed."),try:async()=>await adapter.writeAgentSystemPrompt({content:agentSystemPrompt,filesystemSession,outputDirectory:scaffoldOutput.outputDirectory})});const result4={...resultInput,agentSystemPromptFile:writtenAgentSystemPromptFile,generatedFiles:[...scaffoldOutput.generatedFiles,writtenAgentSystemPromptFile]};return{_tag:"MaterializedRepositoryScaffold",agentSystemPrompt,commitState:"committed",result:result4}}),plan:fn2("ScopedScaffoldOperation.plan")(function*plan(input2){const inspected=inspections.get(input2.inspection);if(inspected===undefined){return yield*failure("plan",new Error("The inspection was not produced by this scoped operation."),"Unknown scaffold inspection.")}const{baselineOrigin,filesystemSession,input:inspectionInput}=inspected;const selectedBaselineOrigin=input2._tag==="PlanStageScaffold"&&input2.selectedBaseline.summary.authoritySource==="bundled"?"bundled":"resolved";const ownedInput=snapshotPlanInput(input2,structuredClone(inspected.inspection));if(ownedInput._tag==="PlanStageScaffold"){if(stage===undefined){return yield*failure("plan",new Error("No staged scaffold adapter is installed."),"Missing staged scaffold adapter.")}const state=yield*stage.plan(ownedInput,{filesystemSession,inspectionInput,selectedBaselineOrigin});const scopedPlan2={_tag:"ScopedScaffoldPlan"};plans.set(scopedPlan2,{_tag:"StageScaffoldPlan",state});return scopedPlan2}const settings=yield*projectSettings.read(inspectionInput.outputDirectory,filesystemSession).pipe(map6((read3)=>read3.settings),catchTag2("ProjectSettingsMissing",()=>void_3),mapError3((cause)=>validationFailure(cause,cause.message)));const contextPlan=yield*compileScaffoldContextPlan({baseline:inspectionInput.baseline,detection:ownedInput.inspection.detection,finalPacks:ownedInput.finalPacks,preserveExistingSubagentManifest:true,scanDirectory:inspectionInput.scanDirectory}).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold context planning failed.")));const outputOptions={baseline:inspectionInput.baseline,baselineOrigin,contextPlan,detection:ownedInput.inspection.detection,...ownedInput.displayOutputDirectory===undefined?{}:{displayOutputDirectory:ownedInput.displayOutputDirectory},filesystemSession,outputDirectory:inspectionInput.outputDirectory,repoShapeMode:inspectionInput.repoShapeMode,scanDirectory:inspectionInput.scanDirectory,scriptEnvironment:ownedInput.scriptEnvironment,scriptRuntimePath:ownedInput.scriptRuntimePath,...settings===undefined?{}:{settings},toolBootstrapStatuses:ownedInput.toolBootstrapStatuses};const materializationPlan=yield*planScaffoldMaterialization(outputOptions).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold output planning failed.")));const skillIds=selectedSkills4(ownedInput.finalPacks,inspectionInput.baseline);yield*try_3({catch:(cause)=>validationFailure(cause,"Scaffold output preflight failed."),try:()=>{adapter.preflightOutputTargets({directoryPaths:[...materializationPlan.resetDirectories,".devpunks/pre-existing-skills",...preExistingSkillSnapshotDirectories,...skillIds.map((skillId)=>`.agents/skills/${skillId}`)],fileTargets:[".devpunks/AGENT-HANDOFF.md",".devpunks/scaffold-manifest.json",agentSystemPromptFile3,projectSettingsFile,".devpunks/harness-projection-receipt.json",".gitignore"].map((relativePath)=>({path:relativePath})),filesystemSession,outputDirectory:inspectionInput.outputDirectory,plan:materializationPlan.desiredInput,preserveConsumerPromptTargets:true})}});const scopedPlan={_tag:"ScopedScaffoldPlan"};plans.set(scopedPlan,{_tag:"RepositoryScaffoldPlan",input:ownedInput,inspectionInput,outputOptions:{...outputOptions,desiredState:materializationPlan.desiredState,materializationPlan}});return scopedPlan})})};import{existsSync as existsSync17}from"node:fs";import path38 from"node:path";var scanRepository=fn2("NodeRepositoryScanner.scan")(function*scanRepository2(rootDirectory){const detection=yield*result2(detectRepository(rootDirectory));if(isSuccess2(detection)){return detection.success}const error2=detection.failure;return yield*new RepositoryScanError({cause:error2.cause??error2,operation:"scan-repository",rootDirectory})});var nodeRepositoryScanner={scan:scanRepository};var inspectLocalRepository=({baseline,repoShapeMode,rootDirectory})=>inspectRepository({baseline,repoShapeMode,rootDirectory,scanner:nodeRepositoryScanner});var agentSystemPromptFile4=".devpunks/AGENT-SYSTEM-PROMPT.md";var makeScopedScaffoldOperationAdapter=()=>({bindOutputRoot:async(outputDirectory,{allowCreate,scanDirectory})=>{await Promise.resolve();if(!allowCreate&&!existsSync17(outputDirectory)){throw new RepositoryScanError({cause:new Error(`Repository root does not exist: ${scanDirectory}`),operation:"scan-repository",rootDirectory:scanDirectory})}if(!allowCreate||existsSync17(outputDirectory)){const filesystemSession=createConfinedFilesystemSession(outputDirectory);return{commit:async()=>{const current=createConfinedFilesystemSession(outputDirectory);if(current.outputRootIdentity.device!==filesystemSession.outputRootIdentity.device||current.outputRootIdentity.inode!==filesystemSession.outputRootIdentity.inode){throw new CliValidationError({message:`Refusing to write scaffold content through changed root ${outputDirectory}.`})}return await Promise.resolve(filesystemSession)}}}let existingAncestor=path38.resolve(outputDirectory);while(!existsSync17(existingAncestor)){existingAncestor=path38.dirname(existingAncestor)}const ancestorSession=createConfinedFilesystemSession(existingAncestor);return{commit:async()=>{const currentAncestor=createConfinedFilesystemSession(existingAncestor);if(currentAncestor.outputRootIdentity.device!==ancestorSession.outputRootIdentity.device||currentAncestor.outputRootIdentity.inode!==ancestorSession.outputRootIdentity.inode||existsSync17(outputDirectory)){throw new CliValidationError({message:`Refusing to create scaffold root through changed ancestor ${existingAncestor}.`})}return await bindConfinedFilesystemSessionFromAncestor(outputDirectory,ancestorSession)}}},cleanupGitignore:async(rootDirectory,filesystemSession)=>{await removeHarnessDirectoriesFromGitignore(rootDirectory,undefined,filesystemSession)},inspectRepository:inspectLocalRepository,manifestPaths,preflightOutputTargets:({directoryPaths,fileTargets,filesystemSession,outputDirectory,plan,preserveConsumerPromptTargets})=>{preflightScaffoldOutputTargets({directoryPaths,fileTargets,outputDirectory,plan,preserveConsumerPromptTargets,session:filesystemSession})},writeAgentSystemPrompt:async({outputDirectory,content,filesystemSession})=>{await writeConfinedFile({content:`${content}
2531
+ `))]).pipe(andThen2(prompt.multiSelect({choices:request.allowed.map((packId)=>{const description=request.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add3?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add3?"Select all optional packs":"Select all removable packs",selectNone:add3?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map6(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map6(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request)=>selectPacks(prompt,request),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map6(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer==="tanstack-start"?answer:"next")});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map6(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync7}from"node:child_process";import{existsSync as existsSync16,lstatSync as lstatSync9,readFileSync as readFileSync16}from"node:fs";import path34 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path34.resolve(rootDirectory);while(true){const gitMarker=path34.join(currentDirectory,".git");if(existsSync16(gitMarker)){execFileSync7("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path34.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var projectSettingsOutputDirectory=(filePath)=>{const parentDirectory=path34.dirname(filePath);return path34.basename(filePath)==="settings.json"&&path34.basename(parentDirectory)===".devpunks"?path34.dirname(parentDirectory):parentDirectory};var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}),try:async()=>{try{await writeConfinedFile({content,outputDirectory:projectSettingsOutputDirectory(filePath),replace:false,...session===undefined?{}:{session},targetPath:filePath});return true}catch(error2){if(hasErrorCode(error2,"EEXIST")){return false}throw error2}}}),directoryExists:(directoryPath,session)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to inspect directory ${directoryPath}.`,operation:"read",path:directoryPath}),try:()=>{if(session!==undefined){assertConfinedDirectory({directoryPath,outputDirectory:session.outputRoot,session})}const exists=existsSync16(directoryPath);if(session!==undefined){assertConfinedFilesystemSession({outputDirectory:session.outputRoot,session})}return exists}}),joinPath:(...segments)=>path34.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync7("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}),try:async()=>{if(session===undefined){try{return some2(readFileSync16(filePath,"utf-8"))}catch(error2){if(isMissingFile2(error2)){return none2()}throw error2}}const content=await readConfinedRegularFile({allowMissing:true,outputDirectory:session.outputRoot,session,targetPath:filePath});return content===null?none2():some2(content.toString("utf-8"))}}),removeEmptyDirectory:(directoryPath,session)=>tryPromise2({catch:(error2)=>new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}),try:async()=>{if(session===undefined&&lstatSync9(directoryPath,{throwIfNoEntry:false})===undefined){return}try{await removeConfinedEmptyDirectory({directoryPath,outputDirectory:session?.outputRoot??path34.dirname(directoryPath),...session===undefined?{}:{session}})}catch(error2){if(!hasErrorCode(error2,"ENOTEMPTY")){throw error2}}}}),removeTextFileIfContent:(filePath,expectedContent,session)=>tryPromise2({catch:(error2)=>cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}.`),try:async()=>{if(session===undefined&&lstatSync9(filePath,{throwIfNoEntry:false})===undefined){return false}return await removeConfinedFileIfContent({expectedContent,outputDirectory:session?.outputRoot??projectSettingsOutputDirectory(filePath),...session===undefined?{}:{session},targetPath:filePath})}}),writeTextFile:(filePath,content,session)=>tryPromise2({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:async()=>{await writeConfinedFile({content,outputDirectory:projectSettingsOutputDirectory(filePath),replace:true,...session===undefined?{}:{session},targetPath:filePath})}})});import{createHash as createHash13}from"node:crypto";import{execFileSync as execFileSync8}from"node:child_process";import{lstatSync as lstatSync10,readFileSync as readFileSync17,readlinkSync as readlinkSync7,realpathSync as realpathSync8}from"node:fs";import path35 from"node:path";var projectProducerFailure=({cause,message,sourcePath})=>new ProjectProducerFailure({cause,message,operation:"derive-project-generated-ownership",sourcePath});var fingerprintRepositoryMirror=fn2("ProjectProducer.fingerprintRepositoryMirror")(function*fingerprintRepositoryMirror2({repositoryRoot,sourcePath}){const absoluteRoot=path35.resolve(repositoryRoot);if(path35.isAbsolute(sourcePath)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source must be relative: ${sourcePath}`,sourcePath})}const absolutePath=path35.resolve(absoluteRoot,sourcePath);const relativePath=path35.relative(absoluteRoot,absolutePath);if(relativePath===""){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source cannot be the repository root: ${sourcePath}`,sourcePath})}if(relativePath===".."||relativePath.startsWith(`..${path35.sep}`)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source escapes repository root: ${sourcePath}`,sourcePath})}const stat3=yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to inspect repository mirror source: ${sourcePath}`,sourcePath}),try:()=>lstatSync10(absolutePath,{throwIfNoEntry:false})});if(stat3===undefined){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source does not exist: ${sourcePath}`,sourcePath})}const[realRoot,realParent]=yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to resolve repository mirror source: ${sourcePath}`,sourcePath}),try:()=>[realpathSync8(absoluteRoot),realpathSync8(path35.dirname(absolutePath))]});const realParentRelative=path35.relative(realRoot,realParent);if(realParentRelative===".."||realParentRelative.startsWith(`..${path35.sep}`)||path35.isAbsolute(realParentRelative)){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source escapes repository root through a symlink ancestor: ${sourcePath}`,sourcePath})}if(!stat3.isFile()&&!stat3.isSymbolicLink()){return yield*projectProducerFailure({cause:sourcePath,message:`Repository mirror source must be a regular file or symbolic link: ${sourcePath}`,sourcePath})}yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Repository mirror source must be version-controlled: ${sourcePath}`,sourcePath}),try:()=>execFileSync8("git",["--literal-pathspecs","-C",absoluteRoot,"ls-files","--error-unmatch","--",sourcePath],{stdio:"ignore"})});return yield*try_3({catch:(cause)=>projectProducerFailure({cause,message:`Failed to fingerprint repository mirror source: ${sourcePath}`,sourcePath}),try:()=>{if(stat3.isSymbolicLink()){const target=readlinkSync7(absolutePath);return{_tag:"Symlink",sha256:createHash13("sha256").update(`symlink:${target}`).digest("hex"),target}}return{_tag:"File",mode:stat3.mode%512,sha256:createHash13("sha256").update(readFileSync17(absolutePath)).digest("hex")}}})});var ProjectProducerLive=succeed5(ProjectProducer,{fingerprintRepositoryMirror});import{spawn as spawn3}from"node:child_process";import{createHash as createHash14}from"node:crypto";import{existsSync as existsSync17,readFileSync as readFileSync18,realpathSync as realpathSync9,statSync as statSync4}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir9}from"node:os";import path36 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillRelativePath=path36.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var errorCode=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&typeof cause.code==="string"?cause.code:undefined;var processError=(cause)=>{const error2=cause instanceof Error?cause:new Error(String(cause));const code=errorCode(cause);return Object.assign(error2,code===undefined?{}:{code})};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String4),name:String4,path:String4,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request)=>({operation:operation2,scope:request.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index of[0,1,2]){const difference=left[index]-right[index];if(difference!==0){return difference}}return 0};var isContainedPath=(root,candidate)=>{const relative=path36.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path36.sep}`)&&!path36.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn3(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return errorCode(error2)!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(errorCode(error2)!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap3((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const sourceOrigin=options4.operatorSkillOrigin??operatorSkillOrigin;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??(async(directory3)=>{await rm2(directory3,{force:true,recursive:true})});const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir9();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand(operation2,request,command,args2,cwd,commandLabel,interactive){const result4=yield*callback2((resume)=>{let child;try{child=spawn3(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:interactive??false?["inherit","inherit","pipe"]:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:processError(error2),status:null,stderr:"",stdout:""}));return void_3}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const interactiveMode=interactive??false;const timeout3=timeoutEnabled&&!interactiveMode?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context3=failureContext(operation2,request);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context3,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context3,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context3,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context3,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr.length>0?result4.stderr:result4.error?.message??""})}return result4.stdout});const run6=(operation2,request,args2)=>runCommand(operation2,request,executable,args2,request.cwd,"Skills CLI",operation2!=="list"&&args2[0]!=="--version"&&request.targetSelection==="prompt");const runGit=(request,args2,cwd)=>runCommand("resolve",request,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request,message,cause)=>new SkillsCliExit({...failureContext("resolve",request),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const acquireTargetCheckout=(request)=>acquireRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot create a temporary operator-skill checkout",cause),try:async()=>await mkdtemp2(path36.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot clean up the temporary operator-skill checkout",cause),try:async()=>{await removeTemporaryDirectory(temporaryRoot)}}).pipe(orDie2)).pipe(flatMap3((temporaryRoot)=>gen2(function*resolveTargetCheckout(){const checkoutRoot=path36.join(temporaryRoot,"source");yield*runGit(request,["init",checkoutRoot],request.cwd);yield*runGit(request,["remote","add","origin",sourceOrigin],checkoutRoot);yield*runGit(request,["fetch","--depth=1","origin","main"],checkoutRoot);const fetchedRevision=(yield*runGit(request,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(!/^[0-9a-f]{40}$/u.test(fetchedRevision)){return yield*new SkillsCliMalformedOutput({...failureContext("resolve",request),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync9(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync9(path36.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("resolve",request),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return{checkoutRoot:canonicalCheckout,localSource,revision:fetchedRevision}})));const resolveTarget=fn2("SkillsCli.resolveTarget")(function*resolveTarget(request){const checkout=yield*acquireTargetCheckout(request);const trackedFiles=(yield*runGit(request,["ls-tree","-r","--name-only","FETCH_HEAD","--","skills/agnostic/cli/hi-cli"],checkout.checkoutRoot)).split(`
2532
+ `).filter((entry)=>entry.length>0);const contentManifest=yield*all2(trackedFiles.map((trackedPath)=>try_3({catch:(cause)=>temporaryDirectoryFailure(request,`Cannot read operator-skill source file ${trackedPath}`,cause),try:()=>{const relativePath=path36.relative(path36.join("skills","agnostic","cli","hi-cli"),trackedPath);const sourcePath=realpathSync9(path36.join(checkout.checkoutRoot,trackedPath));if(relativePath===""||relativePath===".."||relativePath.startsWith(`..${path36.sep}`)||path36.isAbsolute(relativePath)||!isContainedPath(checkout.localSource,sourcePath)||!statSync4(sourcePath).isFile()){throw new Error("Operator-skill source manifest contains an unsafe path")}return{path:relativePath.split(path36.sep).join("/"),sha256:createHash14("sha256").update(readFileSync18(sourcePath)).digest("hex")}}})));let version3=operatorSkillMetadataVersion;for(const packagePath of[path36.join(checkout.localSource,"package.json"),path36.join(checkout.checkoutRoot,"package.json")]){if(!existsSync17(packagePath)){continue}const metadata=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request,"Cannot read operator-skill package metadata",cause),try:()=>JSON.parse(readFileSync18(packagePath,"utf-8"))});if(typeof metadata==="object"&&metadata!==null&&"version"in metadata&&typeof metadata.version==="string"){const{version:metadataVersion}=metadata;version3=metadataVersion;break}}const resolution=resolveOperatorSkillTarget({activeCliVersion:request.activeCliVersion,candidates:[{cliCompatibility:operatorSkillCompatibilityPolicy,contentManifest,revision:checkout.revision,source:`${operatorSkillSourceRoot}/tree/${checkout.revision}/skills/agnostic/cli/hi-cli`,version:version3}]});return resolution._tag==="Resolved"?{...resolution,localSource:checkout.localSource}:resolution});const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion(operation2,request){const stdout=yield*run6(operation2,request,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(minimumVersion===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request),message:"Configured minimum Skills CLI version is malformed",stdout:minimumSkillsCliVersion})}if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}return null});const verifyListedSkill=(request,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path36.isAbsolute(skill.path)||path36.parse(skill.path).root===path36.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync9(skill.path)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request.target.contentManifest){const normalizedRelativePath=path36.normalize(entry.path);if(entry.path===""||path36.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path36.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path36.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path36.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync9(filePath)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync18(canonicalFilePath)}catch(error2){const code=errorCode(error2);return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash14("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request.target.cliCompatibility,revision:request.target.revision,source:request.target.source,version:request.target.version}})};const list2=fn2("SkillsCli.list")(function*list(request){yield*ensureSupportedVersion("list",request);const stdout=yield*run6("list",request,["list",...scopeArguments(request.scope),"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request),message:`Skills CLI list returned a scope other than ${request.scope}`,stdout})}const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}const verification=yield*result2(verifyListedSkill(request,skill,verified()));if(isFailure2(verification)){if(verification.failure.reason==="identity-mismatch"){listed.push({...skill,name:"hi-cli",verification:"outdated"});continue}return yield*verification.failure}listed.push(verification.success)}return listed});const verifyResolvedSource=fn2("SkillsCli.verifyResolvedSource")(function*verifyResolvedSource(request){const{target}=request.resolvedTarget;let canonicalRoot;try{canonicalRoot=realpathSync9(request.resolvedTarget.localSource)}catch{return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:"Cannot resolve the captured operator-skill source",reason:"missing",skillName:"hi-cli",skillPath:request.resolvedTarget.localSource,verifiedSkills:[]})}for(const entry of target.contentManifest){const normalizedRelativePath=path36.normalize(entry.path);if(entry.path===""||path36.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path36.sep}`)||!sha256Pattern.test(entry.sha256)){return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:"Captured operator-skill manifest is malformed",reason:"malformed",skillName:"hi-cli",skillPath:canonicalRoot,verifiedSkills:[]})}let canonicalFile;try{canonicalFile=realpathSync9(path36.join(canonicalRoot,normalizedRelativePath))}catch{return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:`Cannot resolve captured operator-skill file ${entry.path}`,reason:"missing",skillName:"hi-cli",skillPath:canonicalRoot,verifiedSkills:[]})}if(!isContainedPath(canonicalRoot,canonicalFile)){return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:`Captured operator-skill file ${entry.path} escapes its source`,reason:"unsafe-path",skillName:"hi-cli",skillPath:canonicalRoot,verifiedSkills:[]})}let content;try{content=readFileSync18(canonicalFile)}catch(error2){return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:`Cannot read captured operator-skill file ${entry.path}`,reason:errorCode(error2)==="ENOENT"?"missing":"unreadable",skillName:"hi-cli",skillPath:canonicalRoot,verifiedSkills:[]})}const actualSha256=createHash14("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*new SkillsCliVerificationFailure({...failureContext("install",request),message:`Captured operator-skill file ${entry.path} changed before installation`,reason:"identity-mismatch",skillName:"hi-cli",skillPath:canonicalRoot,verifiedSkills:[]})}}return yield*void_3});const install=fn2("SkillsCli.install")(function*install(request){yield*ensureSupportedVersion("install",request);yield*verifyResolvedSource(request);yield*run6("install",request,["add",request.resolvedTarget.localSource,"--skill","hi-cli",...scopeArguments(request.scope),...request.targetSelection==="automatic"?["--yes"]:[],"--copy"])});const remove4=fn2("SkillsCli.remove")(function*remove(request){yield*ensureSupportedVersion("remove",request);yield*run6("remove",request,["remove",request.name,...scopeArguments(request.scope),...request.targetSelection==="automatic"?["--yes"]:[]])});return succeed5(SkillsCli,{install,list:list2,remove:remove4,resolveTarget})};import path37 from"node:path";var agentSystemPromptFile3=".devpunks/AGENT-SYSTEM-PROMPT.md";var selectedSkills4=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var failure=(operation2,cause,fallback)=>cause instanceof ScopedScaffoldOperationFailure?cause:new ScopedScaffoldOperationFailure({cause,message:cause instanceof Error?cause.message:fallback,operation:operation2});var validationFailure=(cause,fallback)=>cause instanceof CliValidationError?cause:new CliValidationError({cause,message:cause instanceof Error?cause.message:fallback});var snapshotInspectInput=(input2)=>structuredClone(input2);var snapshotPlanInput=(input2,inspection)=>({...structuredClone(input2),inspection});var makeScopedScaffoldOperation=({adapter,projectSettings,stage})=>{const inspections=new WeakMap;const plans=new WeakMap;return ScopedScaffoldOperation.of({inspect:fn2("ScopedScaffoldOperation.inspect")(function*inspect(input2){const baselineOrigin=input2.baseline.summary.authoritySource==="bundled"?"bundled":"resolved";const ownedInput=snapshotInspectInput(input2);const binding=yield*tryPromise2({catch:(cause)=>cause instanceof RepositoryScanError?cause:failure("inspect",cause,"Could not bind scaffold output root."),try:async()=>await adapter.bindOutputRoot(ownedInput.outputDirectory,{allowCreate:path37.resolve(ownedInput.outputDirectory)!==path37.resolve(ownedInput.scanDirectory),scanDirectory:ownedInput.scanDirectory})});const inspected=yield*adapter.inspectRepository({baseline:ownedInput.baseline,repoShapeMode:ownedInput.repoShapeMode,rootDirectory:ownedInput.scanDirectory});const filesystemSession=yield*tryPromise2({catch:(cause)=>failure("inspect",cause,"Could not commit scaffold output root."),try:binding.commit});const inspection=structuredClone(inspected);inspections.set(inspection,{baselineOrigin,filesystemSession,input:ownedInput,inspection:structuredClone(inspection)});return inspection}),materialize:fn2("ScopedScaffoldOperation.materialize")(function*materialize(plan){const planned=plans.get(plan);if(planned===undefined){return yield*failure("materialize",new Error("The scaffold plan was not produced by this scoped operation."),"Unknown scaffold plan.")}plans.delete(plan);if(planned._tag==="StageScaffoldPlan"){if(stage===undefined){return yield*failure("materialize",new Error("No staged scaffold adapter is installed."),"Missing staged scaffold adapter.")}return yield*stage.materialize(planned.state)}const{input:input2,inspectionInput,outputOptions}=planned;if(input2._tag!=="PlanRepositoryScaffold"){return yield*failure("materialize",new Error("Repository scaffold plan has an invalid input kind."),"Invalid repository scaffold plan.")}const{contextPlan,desiredState,filesystemSession,settings}=outputOptions;if(desiredState===undefined||contextPlan===undefined){return yield*new CliValidationError({message:"Repository scaffold plan has no desired state."})}if(filesystemSession===undefined){return yield*failure("materialize",new Error("The scaffold plan has no confined filesystem session."),"Missing confined filesystem session.")}const settingsExist=yield*projectSettings.read(inspectionInput.outputDirectory,filesystemSession).pipe(as2(true),catchTag2("ProjectSettingsMissing",()=>succeed6(false)),mapError3((cause)=>validationFailure(cause,cause.message)));const scaffoldOutput=yield*adapter.writeOutput(outputOptions).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold output failed.")));if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Scaffold output did not produce harness projection evidence."})}yield*completeLocalQualitySetup({desiredState:{contextPlan,dependencies:desiredState.dependencies,files:desiredState.files,settings:settings??{}},rootDirectory:inspectionInput.outputDirectory,session:filesystemSession}).pipe(mapError3((cause)=>validationFailure(cause,"Local quality setup failed.")));yield*tryPromise2({catch:(cause)=>validationFailure(cause,"Scaffold gitignore cleanup failed."),try:async()=>{await adapter.cleanupGitignore(scaffoldOutput.outputDirectory,filesystemSession)}});if(settingsExist){yield*projectSettings.write(scaffoldOutput.outputDirectory,{_tag:"ScaffoldChange",baselineVersion:scaffoldOutput.baseline.version,cliVersion:version2,requiredTools:input2.requiredTools},filesystemSession).pipe(mapError3((cause)=>validationFailure(cause,cause.message)))}const{detection,packs:resolved}=input2.inspection;const resultInput={addedPacks:input2.addedPacks,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile3,baseline:scaffoldOutput.baseline,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:inspectionInput.scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks:input2.finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile3],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:adapter.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:input2.removedPacks,repoShapeMode:inspectionInput.repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses:input2.toolBootstrapStatuses};const agentSystemPrompt=formatAgentHandoffSummary(resultInput);const writtenAgentSystemPromptFile=yield*tryPromise2({catch:(cause)=>validationFailure(cause,"Agent system prompt write failed."),try:async()=>await adapter.writeAgentSystemPrompt({content:agentSystemPrompt,filesystemSession,outputDirectory:scaffoldOutput.outputDirectory})});const result4={...resultInput,agentSystemPromptFile:writtenAgentSystemPromptFile,generatedFiles:[...scaffoldOutput.generatedFiles,writtenAgentSystemPromptFile]};return{_tag:"MaterializedRepositoryScaffold",agentSystemPrompt,commitState:"committed",result:result4}}),plan:fn2("ScopedScaffoldOperation.plan")(function*plan(input2){const inspected=inspections.get(input2.inspection);if(inspected===undefined){return yield*failure("plan",new Error("The inspection was not produced by this scoped operation."),"Unknown scaffold inspection.")}const{baselineOrigin,filesystemSession,input:inspectionInput}=inspected;const selectedBaselineOrigin=input2._tag==="PlanStageScaffold"&&input2.selectedBaseline.summary.authoritySource==="bundled"?"bundled":"resolved";const ownedInput=snapshotPlanInput(input2,structuredClone(inspected.inspection));if(ownedInput._tag==="PlanStageScaffold"){if(stage===undefined){return yield*failure("plan",new Error("No staged scaffold adapter is installed."),"Missing staged scaffold adapter.")}const state=yield*stage.plan(ownedInput,{filesystemSession,inspectionInput,selectedBaselineOrigin});const scopedPlan2={_tag:"ScopedScaffoldPlan"};plans.set(scopedPlan2,{_tag:"StageScaffoldPlan",state});return scopedPlan2}const settings=yield*projectSettings.read(inspectionInput.outputDirectory,filesystemSession).pipe(map6((read3)=>read3.settings),catchTag2("ProjectSettingsMissing",()=>void_3),mapError3((cause)=>validationFailure(cause,cause.message)));const contextPlan=yield*compileScaffoldContextPlan({baseline:inspectionInput.baseline,detection:ownedInput.inspection.detection,finalPacks:ownedInput.finalPacks,preserveExistingSubagentManifest:true,scanDirectory:inspectionInput.scanDirectory}).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold context planning failed.")));const outputOptions={baseline:inspectionInput.baseline,baselineOrigin,contextPlan,detection:ownedInput.inspection.detection,...ownedInput.displayOutputDirectory===undefined?{}:{displayOutputDirectory:ownedInput.displayOutputDirectory},filesystemSession,outputDirectory:inspectionInput.outputDirectory,repoShapeMode:inspectionInput.repoShapeMode,scanDirectory:inspectionInput.scanDirectory,scriptEnvironment:ownedInput.scriptEnvironment,scriptRuntimePath:ownedInput.scriptRuntimePath,...settings===undefined?{}:{settings},toolBootstrapStatuses:ownedInput.toolBootstrapStatuses};const materializationPlan=yield*planScaffoldMaterialization(outputOptions).pipe(mapError3((cause)=>validationFailure(cause,"Scaffold output planning failed.")));const skillIds=selectedSkills4(ownedInput.finalPacks,inspectionInput.baseline);yield*try_3({catch:(cause)=>validationFailure(cause,"Scaffold output preflight failed."),try:()=>{adapter.preflightOutputTargets({directoryPaths:[...materializationPlan.resetDirectories,".devpunks/pre-existing-skills",...preExistingSkillSnapshotDirectories,...skillIds.map((skillId)=>`.agents/skills/${skillId}`)],fileTargets:[".devpunks/AGENT-HANDOFF.md",".devpunks/scaffold-manifest.json",agentSystemPromptFile3,projectSettingsFile,".devpunks/harness-projection-receipt.json",".gitignore"].map((relativePath)=>({path:relativePath})),filesystemSession,outputDirectory:inspectionInput.outputDirectory,plan:materializationPlan.desiredInput,preserveConsumerPromptTargets:true})}});const scopedPlan={_tag:"ScopedScaffoldPlan"};plans.set(scopedPlan,{_tag:"RepositoryScaffoldPlan",input:ownedInput,inspectionInput,outputOptions:{...outputOptions,desiredState:materializationPlan.desiredState,materializationPlan}});return scopedPlan})})};import{existsSync as existsSync18}from"node:fs";import path38 from"node:path";var scanRepository=fn2("NodeRepositoryScanner.scan")(function*scanRepository2(rootDirectory){const detection=yield*result2(detectRepository(rootDirectory));if(isSuccess2(detection)){return detection.success}const error2=detection.failure;return yield*new RepositoryScanError({cause:error2.cause??error2,operation:"scan-repository",rootDirectory})});var nodeRepositoryScanner={scan:scanRepository};var inspectLocalRepository=({baseline,repoShapeMode,rootDirectory})=>inspectRepository({baseline,repoShapeMode,rootDirectory,scanner:nodeRepositoryScanner});var agentSystemPromptFile4=".devpunks/AGENT-SYSTEM-PROMPT.md";var makeScopedScaffoldOperationAdapter=()=>({bindOutputRoot:async(outputDirectory,{allowCreate,scanDirectory})=>{await Promise.resolve();if(!allowCreate&&!existsSync18(outputDirectory)){throw new RepositoryScanError({cause:new Error(`Repository root does not exist: ${scanDirectory}`),operation:"scan-repository",rootDirectory:scanDirectory})}if(!allowCreate||existsSync18(outputDirectory)){const filesystemSession=createConfinedFilesystemSession(outputDirectory);return{commit:async()=>{const current=createConfinedFilesystemSession(outputDirectory);if(current.outputRootIdentity.device!==filesystemSession.outputRootIdentity.device||current.outputRootIdentity.inode!==filesystemSession.outputRootIdentity.inode){throw new CliValidationError({message:`Refusing to write scaffold content through changed root ${outputDirectory}.`})}return await Promise.resolve(filesystemSession)}}}let existingAncestor=path38.resolve(outputDirectory);while(!existsSync18(existingAncestor)){existingAncestor=path38.dirname(existingAncestor)}const ancestorSession=createConfinedFilesystemSession(existingAncestor);return{commit:async()=>{const currentAncestor=createConfinedFilesystemSession(existingAncestor);if(currentAncestor.outputRootIdentity.device!==ancestorSession.outputRootIdentity.device||currentAncestor.outputRootIdentity.inode!==ancestorSession.outputRootIdentity.inode||existsSync18(outputDirectory)){throw new CliValidationError({message:`Refusing to create scaffold root through changed ancestor ${existingAncestor}.`})}return await bindConfinedFilesystemSessionFromAncestor(outputDirectory,ancestorSession)}}},cleanupGitignore:async(rootDirectory,filesystemSession)=>{await removeHarnessDirectoriesFromGitignore(rootDirectory,undefined,filesystemSession)},inspectRepository:inspectLocalRepository,manifestPaths,preflightOutputTargets:({directoryPaths,fileTargets,filesystemSession,outputDirectory,plan,preserveConsumerPromptTargets})=>{preflightScaffoldOutputTargets({directoryPaths,fileTargets,outputDirectory,plan,preserveConsumerPromptTargets,session:filesystemSession})},writeAgentSystemPrompt:async({outputDirectory,content,filesystemSession})=>{await writeConfinedFile({content:`${content}
2532
2533
  `,outputDirectory,replace:true,session:filesystemSession,targetPath:path38.join(outputDirectory,agentSystemPromptFile4)});return agentSystemPromptFile4},writeOutput:writeScaffoldOutput});var startupCheckWorkerEnv="HI_STARTUP_CHECK_WORKER";var startupCheckCliEnv="HI_STARTUP_CHECK_CLI";var startupCheckSkillEnv="HI_STARTUP_CHECK_SKILL";var processEnvironment=process.env;var processProvider=makeEnvironmentProvider(processEnvironment);var startupCheckCacheFile=path39.join(homedir3(),".cache","hi","startup-check.json");var effectBuiltIns=exports_GlobalFlag.BuiltIns.filter((flag)=>flag!==exports_GlobalFlag.Wizard);var rootCommands=commandRegistry.command.subcommands.flatMap(({commands})=>commands);var rootCommandNames=rootCommands.map(({name:commandName})=>commandName);var forceColorEnvironment=(runtime)=>{if(runtime.commandEnvironment.FORCE_COLOR==="0"){return{FORCE_COLOR:"0"}}if(runtime.forceColor){return{FORCE_COLOR:"1"}}return{}};var makeRootRenderEnvironment=(runtime,mode)=>makeHumanRenderEnvironment({columns:process.stdout.columns,environment:{...runtime.colorForegroundBackground===undefined?{}:{COLORFGBG:runtime.colorForegroundBackground},...forceColorEnvironment(runtime),...runtime.noColor?{NO_COLOR:"1"}:{},...runtime.terminalTheme===undefined?{}:{HI_THEME:runtime.terminalTheme}},mode,stdoutIsTTY:process.stdout.isTTY});var renderRootCommandGuide=(runtime,mode)=>renderRootScreen(renderCommandGuide(commandRegistry.discovery),makeRootRenderEnvironment(runtime,mode));var makeWizardGlobalFlag=(runtime)=>exports_GlobalFlag.action({flag:exports_Flag.boolean("wizard").pipe(exports_Flag.withDescription("Show the interactive command guide")),run:()=>sync2(()=>{const mode=selectOutputMode({jsonSelected:false,stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY});process.stdout.write(renderRootCommandGuide(runtime,mode==="interactive"?mode:"plain"))})});var makeRootCommand=(runtime)=>commandRegistry.command.pipe(exports_Command.withGlobalFlags([makeWizardGlobalFlag(runtime)]));var isRootHelpAction=(nativeAction)=>nativeAction==="--help"||nativeAction==="-h";var isHelpArgument=(argument)=>argument==="--help"||argument.startsWith("--help=")||/^-[^-]*h/u.test(argument)&&argument!=="-";var classifyRootHelp=(commandArguments,nativeAction)=>{if(!isRootHelpAction(nativeAction)){return"none"}if(commandArguments.length===1&&(commandArguments[0]==="--help"||commandArguments[0]==="-h")){return"exact"}const helpIndex=commandArguments.findIndex(isHelpArgument);const rootCommandIndex=commandArguments.findIndex((argument)=>rootCommandNames.includes(argument));return rootCommandIndex!==-1&&rootCommandIndex<helpIndex?"nested":"invalid"};var defaultCliFormatter=exports_CliOutput.defaultFormatter();var cliOutputLayer=exports_CliOutput.layer({formatCliError:defaultCliFormatter.formatCliError,formatError:defaultCliFormatter.formatError,formatErrors:defaultCliFormatter.formatErrors,formatHelpDoc:defaultCliFormatter.formatHelpDoc,formatVersion:(_name,currentVersion)=>`${currentVersion}
2533
2534
  `});var jsonCliFormatter={formatCliError:()=>"",formatError:()=>"",formatErrors:()=>"",formatHelpDoc:()=>"",formatVersion:defaultCliFormatter.formatVersion};var jsonCliConsole={...globalThis.console,error:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.error(...args2)}},log:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.log(...args2)}}};var cliArgv=process.argv.length===3&&process.argv[2]==="-v"?[...process.argv.slice(0,2),"--version"]:process.argv;var isCommandWithHelpDoc=(value5)=>typeof value5==="object"&&value5!==null&&("buildHelpDoc"in value5)&&typeof value5.buildHelpDoc==="function";var isCommandWithGlobalFlags=(value5)=>typeof value5==="object"&&value5!==null&&("globalFlags"in value5)&&Array.isArray(value5.globalFlags);var buildHelpDoc=(command,commandPath)=>{if(!isCommandWithHelpDoc(command)){throw new Error(`Command ${command.name} does not expose help metadata`)}return command.buildHelpDoc(commandPath)};var flattenCommandRegistrations=(registrations)=>registrations.flatMap((registration2)=>[registration2,...flattenCommandRegistrations(registration2.children)]);var commandOptionDescriptors=new Map(flattenCommandRegistrations(commandRegistry.registrations).map(({command,metadata})=>{const help=buildHelpDoc(command,metadata.path);return[metadata.path.join(" "),new Map(help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]}))]}));var rootOptionDescriptors=(rootCommand2)=>{if(!isCommandWithGlobalFlags(rootCommand2)){throw new Error(`Command ${rootCommand2.name} does not expose global flags`)}const declaredFlags=rootCommand2.globalFlags;const globalFlags=[...new Set([...effectBuiltIns,...declaredFlags])];return new Map(globalFlags.flatMap((globalFlag)=>{const help=buildHelpDoc(exports_Command.make("global-option-metadata",{value:globalFlag.flag}),[]);return help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,...globalFlag._tag==="Action"?{nativeAction:true}:{},takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]})}))};var commandOptionsForArguments=(arguments_)=>{const[command]=commandRegistry.reference.filter(({path:registeredPath})=>registeredPath.every((segment,index)=>arguments_[index]===segment)).toSorted((left,right)=>right.path.length-left.path.length);return command===undefined?new Map:commandOptionDescriptors.get(command.path.join(" "))??new Map};var commandHelpForArguments=(arguments_)=>{const[commandPath]=commandRegistry.reference.map(({path:registeredPath})=>registeredPath).filter((registeredPath)=>registeredPath.every((segment,index)=>arguments_[index]===segment)).toSorted((left,right)=>right.length-left.length);return`${commandPath===undefined?"hi":commandPath.join(" ")} --help`};var shouldCheckSelfUpdate=(runtime)=>runtime.updateChecksEnabled&&!process.argv.includes("--help")&&!process.argv.includes("-h")&&!process.argv.includes("--version")&&!process.argv.includes("-v");var shouldCheckHiCliSkillUpdate=(runtime)=>runtime.skillUpdateChecksEnabled&&!process.argv.includes("--help")&&!process.argv.includes("-h")&&!process.argv.includes("--version")&&!process.argv.includes("-v");var shouldAskForSelfUpdate=(runtime,outputMode)=>shouldCheckSelfUpdate(runtime)&&!process.argv.slice(2).includes("upgrade")&&outputMode!=="json"&&process.stdin.isTTY&&process.stdout.isTTY;var formatCommand=({command,environment})=>{const envPrefix=environment===undefined?[]:Object.entries(environment).map(([key,value5])=>`${key}=${value5}`);return[...envPrefix,...command].join(" ")};var askYesNo=async(question)=>{const readline2=createInterface4({input:process.stdin,output:process.stdout});try{const response=await readline2.question(renderQuestion(`${question} [y/N]: `));const answer=response.trim();return answer.toLowerCase()==="y"||answer.toLowerCase()==="yes"}finally{readline2.close()}};var isPromptAbort=(error2)=>error2 instanceof Error&&error2.name==="AbortError";var runInteractiveCliUpdate=async(runtime,outputMode)=>{if(!shouldAskForSelfUpdate(runtime,outputMode)){return false}const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag,timeoutMs:5000});if(result4.status==="current"||result4.status==="unavailable"){return false}if(result4.check===null){return false}if(result4.status!=="available"){const command="command"in result4?result4.command:null;console.error(renderSelfUpdateNotice({command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));return false}console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));if(!await askYesNo("Update CLI before running this command?")){return false}if(runCliInstallCommand({baseEnvironment:runtime.commandEnvironment,command:result4.command,environment:result4.environment})){console.log(renderCommandSection("CLI upgraded",[`${result4.check.packageName} ${result4.check.currentVersion} -> ${result4.check.latestVersion}`,`Installer: ${result4.packageManager}`,`Command: ${formatCommand(result4)}`,"Re-run your command to use the upgraded CLI."].join(`
2534
- `)));return true}console.error(renderCommandSection("CLI upgrade failed",`Command failed: ${formatCommand({command:result4.command})}`));process.exitCode=1;return true};var runCliUpdateCheck=async(runtime)=>{const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag});if(result4.status==="available"||result4.status==="manager-not-detected"||result4.status==="failed"){console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}))}};var runHiCliSkillCheck=runOperatorSkillApplication("status","automatic").pipe(tap2((result4)=>sync2(()=>{if(result4.lifecycle._tag==="Inspected"&&result4.lifecycle.installed._tag==="Absent"){console.error("hi startup checks: `hi-cli` skill not found. Run `hi operator install`, or `hi operator migrate` when legacy `dp-cli` is present.")}})),matchEffect3({onFailure:()=>void_3,onSuccess:()=>void_3}));var runStartupChecks=({checkCli,checkSkill,runtime})=>gen2(function*executeStartupChecks(){if(checkCli){yield*promise2(async()=>{await runCliUpdateCheck(runtime)})}if(checkSkill){yield*runHiCliSkillCheck}});var hasFreshStartupCheck=(runtime)=>{if(!Number.isFinite(runtime.startupCheckIntervalMs)||runtime.startupCheckIntervalMs<=0){return false}try{const parsed=JSON.parse(readFileSync19(startupCheckCacheFile,"utf-8"));return typeof parsed==="object"&&parsed!==null&&"checkedAt"in parsed&&typeof parsed.checkedAt==="number"&&Date.now()-parsed.checkedAt<runtime.startupCheckIntervalMs}catch{return false}};var markStartupCheckStarted=()=>{mkdirSync7(path39.dirname(startupCheckCacheFile),{recursive:true});writeFileSync8(startupCheckCacheFile,JSON.stringify({checkedAt:Date.now()},null,2))};var startBackgroundStartupChecks=(runtime,outputMode)=>{const checkCli=shouldCheckSelfUpdate(runtime)&&!shouldAskForSelfUpdate(runtime,outputMode);const checkSkill=shouldCheckHiCliSkillUpdate(runtime);if(!checkCli&&!checkSkill||hasFreshStartupCheck(runtime)){return}const[,entrypoint]=process.argv;if(entrypoint===undefined||!existsSync18(entrypoint)){return}try{markStartupCheckStarted();const worker=spawn4(process.execPath,[entrypoint],{cwd:process.cwd(),detached:true,env:{...runtime.commandEnvironment,[startupCheckWorkerEnv]:"1",[startupCheckCliEnv]:checkCli?"1":"0",[startupCheckSkillEnv]:checkSkill?"1":"0"},stdio:["ignore","ignore","inherit"]});worker.once("error",()=>{});worker.unref()}catch{}};var main=gen2(function*main2(){const runtime=yield*CliRuntimeConfig;configureBrand({...runtime.colorForegroundBackground===undefined?{}:{colorForegroundBackground:runtime.colorForegroundBackground},forceColor:runtime.forceColor,forceColorDisabled:runtime.commandEnvironment.FORCE_COLOR==="0",noColor:runtime.noColor,...runtime.terminalTheme===undefined?{}:{terminalTheme:runtime.terminalTheme}});const rootCommand2=makeRootCommand(runtime);const cli=exports_Command.runWith(rootCommand2,{version:version2});const commandArguments=cliArgv.slice(2);const argumentScan=analyzeCliArguments({args:commandArguments,commandOptionsForArguments,rootOptions:rootOptionDescriptors(rootCommand2),stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY});const outputMode=argumentScan.mode;const parsedArguments=argumentScan.arguments;if(runtime.startupWorker){yield*runStartupChecks({checkCli:runtime.startupCheckCli,checkSkill:runtime.startupCheckSkill,runtime});return}const stopBeforeCommand=yield*tryPromise2({catch:(cause)=>cause,try:async()=>await runInteractiveCliUpdate(runtime,outputMode)}).pipe(matchEffect3({onFailure:(error2)=>sync2(()=>{if(isPromptAbort(error2)){process.exitCode=130;return true}return false}),onSuccess:succeed6}));if(stopBeforeCommand){return}if(outputMode!=="json"){startBackgroundStartupChecks(runtime,outputMode)}const{nativeAction}=argumentScan;if(outputMode==="json"&&nativeAction!==undefined){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"json-native-action",detail:`CLI-native action \`${nativeAction}\` does not support JSON output. Remove \`--json\` and retry.`,recoverable:true,subject:nativeAction},kind:"expected-failure"}});return}const{missingOption}=argumentScan;if(missingOption!==undefined){const normalizedOption=missingOption.replace(/^-+/u,"");process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command-input",detail:`Missing value for \`${missingOption}\`.`,recoverable:true,recoveryCommand:commandHelpForArguments(argumentScan.commandArguments),subject:normalizedOption},kind:"expected-failure"}});return}const rootHelpDisposition=classifyRootHelp(commandArguments,nativeAction);if(rootHelpDisposition==="exact"){process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}if(rootHelpDisposition==="invalid"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"invalid-root-help-invocation",detail:"Root help accepts only `hi --help` or `hi -h`.",recoverable:true,recoveryCommand:"hi --help",subject:nativeAction??"--help"},kind:"expected-failure"}});return}if(parsedArguments.length===0){if(outputMode==="json"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command",detail:"Choose a Harness command.",recoverable:true,recoveryCommand:"hi --help",subject:"command"},kind:"expected-failure"}});return}process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}let capturedOutcome;const commandEffect=outputMode==="json"?cli(parsedArguments).pipe(provideService2(exports_CliOutput.Formatter,jsonCliFormatter),provideService2(Console,jsonCliConsole)):cli(parsedArguments);const outcome=yield*commandEffect.pipe(provideService2(SelectedOutputMode,outputMode),provideService2(RootPresentationSink,{publish:(publishedOutcome)=>sync2(()=>{capturedOutcome=publishedOutcome})}),match6({onFailure:presentationOutcome,onSuccess:()=>capturedOutcome}));if(outcome===undefined){return}const humanMode=outputMode==="interactive"?outputMode:"plain";const exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,humanMode),mode:outputMode,outcome});if(exitCode!==0){process.exitCode=exitCode}});var cliConfigLayer=makeCliConfigLayer(processProvider,processEnvironment);var ProjectSettingsLive=ProjectSettingsDefault.pipe(provide2(ProjectSettingsFileSystemLive));var scaffoldCapabilitiesLive=scaffoldCapabilitiesLayer.pipe(provide2(cliConfigLayer));var scopedScaffoldOperationLive=effect(ScopedScaffoldOperation,gen2(function*makeLiveScopedScaffoldOperation(){const projectSettings=yield*ProjectSettings;return makeScopedScaffoldOperation({adapter:makeScopedScaffoldOperationAdapter(),projectSettings,stage:makeStageScopedScaffoldAdapter({projectSettings})})})).pipe(provide2(ProjectSettingsLive));var skillsCliLive=makeSkillsCliLive({environment:processEnvironment});var featureApplicationDependencies=mergeAll2(exports_FetchHttpClient.layer,ProjectSettingsLive,ProjectProducerLive,cliConfigLayer,scaffoldCapabilitiesLive,scopedScaffoldOperationLive,skillsCliLive);var featureApplicationOperationsLive=featureApplicationOperationsLayer.pipe(provide2(featureApplicationDependencies));var mainLayer=mergeAll2(layer14,exports_CliConfig.layer({builtIns:effectBuiltIns}),exports_FetchHttpClient.layer,cliOutputLayer,cliPromptLayer,updateInteractionLayer.pipe(provide2(cliPromptLayer)),repositoryScaffoldingInteractionLayer.pipe(provide2(cliPromptLayer)),ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,scopedScaffoldOperationLive,repositoryCheckCapabilitiesLayer.pipe(provide2(merge2(cliConfigLayer,ProjectSettingsLive))),featureApplicationOperationsLive);if(__require.main==__require.module){main.pipe(provide4(mainLayer),(effect2)=>{runMain2(effect2)})}export{rootCommands,rootCommandNames,main};
2535
+ `)));return true}console.error(renderCommandSection("CLI upgrade failed",`Command failed: ${formatCommand({command:result4.command})}`));process.exitCode=1;return true};var runCliUpdateCheck=async(runtime)=>{const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag});if(result4.status==="available"||result4.status==="manager-not-detected"||result4.status==="failed"){console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}))}};var runHiCliSkillCheck=runOperatorSkillApplication("status","automatic").pipe(tap2((result4)=>sync2(()=>{if(result4.lifecycle._tag==="Inspected"&&result4.lifecycle.installed._tag==="Absent"){console.error("hi startup checks: `hi-cli` skill not found. Run `hi operator install`, or `hi operator migrate` when legacy `dp-cli` is present.")}})),matchEffect3({onFailure:()=>void_3,onSuccess:()=>void_3}));var runStartupChecks=({checkCli,checkSkill,runtime})=>gen2(function*executeStartupChecks(){if(checkCli){yield*promise2(async()=>{await runCliUpdateCheck(runtime)})}if(checkSkill){yield*runHiCliSkillCheck}});var hasFreshStartupCheck=(runtime)=>{if(!Number.isFinite(runtime.startupCheckIntervalMs)||runtime.startupCheckIntervalMs<=0){return false}try{const parsed=JSON.parse(readFileSync19(startupCheckCacheFile,"utf-8"));return typeof parsed==="object"&&parsed!==null&&"checkedAt"in parsed&&typeof parsed.checkedAt==="number"&&Date.now()-parsed.checkedAt<runtime.startupCheckIntervalMs}catch{return false}};var markStartupCheckStarted=()=>{mkdirSync7(path39.dirname(startupCheckCacheFile),{recursive:true});writeFileSync8(startupCheckCacheFile,JSON.stringify({checkedAt:Date.now()},null,2))};var startBackgroundStartupChecks=(runtime,outputMode)=>{const checkCli=shouldCheckSelfUpdate(runtime)&&!shouldAskForSelfUpdate(runtime,outputMode);const checkSkill=shouldCheckHiCliSkillUpdate(runtime);if(!checkCli&&!checkSkill||hasFreshStartupCheck(runtime)){return}const[,entrypoint]=process.argv;if(entrypoint===undefined||!existsSync19(entrypoint)){return}try{markStartupCheckStarted();const worker=spawn4(process.execPath,[entrypoint],{cwd:process.cwd(),detached:true,env:{...runtime.commandEnvironment,[startupCheckWorkerEnv]:"1",[startupCheckCliEnv]:checkCli?"1":"0",[startupCheckSkillEnv]:checkSkill?"1":"0"},stdio:["ignore","ignore","inherit"]});worker.once("error",()=>{});worker.unref()}catch{}};var main=gen2(function*main2(){const runtime=yield*CliRuntimeConfig;configureBrand({...runtime.colorForegroundBackground===undefined?{}:{colorForegroundBackground:runtime.colorForegroundBackground},forceColor:runtime.forceColor,forceColorDisabled:runtime.commandEnvironment.FORCE_COLOR==="0",noColor:runtime.noColor,...runtime.terminalTheme===undefined?{}:{terminalTheme:runtime.terminalTheme}});const rootCommand2=makeRootCommand(runtime);const cli=exports_Command.runWith(rootCommand2,{version:version2});const commandArguments=cliArgv.slice(2);const argumentScan=analyzeCliArguments({args:commandArguments,commandOptionsForArguments,rootOptions:rootOptionDescriptors(rootCommand2),stdinIsTTY:process.stdin.isTTY,stdoutIsTTY:process.stdout.isTTY});const outputMode=argumentScan.mode;const parsedArguments=argumentScan.arguments;if(runtime.startupWorker){yield*runStartupChecks({checkCli:runtime.startupCheckCli,checkSkill:runtime.startupCheckSkill,runtime});return}const stopBeforeCommand=yield*tryPromise2({catch:(cause)=>cause,try:async()=>await runInteractiveCliUpdate(runtime,outputMode)}).pipe(matchEffect3({onFailure:(error2)=>sync2(()=>{if(isPromptAbort(error2)){process.exitCode=130;return true}return false}),onSuccess:succeed6}));if(stopBeforeCommand){return}if(outputMode!=="json"){startBackgroundStartupChecks(runtime,outputMode)}const{nativeAction}=argumentScan;if(outputMode==="json"&&nativeAction!==undefined){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"json-native-action",detail:`CLI-native action \`${nativeAction}\` does not support JSON output. Remove \`--json\` and retry.`,recoverable:true,subject:nativeAction},kind:"expected-failure"}});return}const{missingOption}=argumentScan;if(missingOption!==undefined){const normalizedOption=missingOption.replace(/^-+/u,"");process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command-input",detail:`Missing value for \`${missingOption}\`.`,recoverable:true,recoveryCommand:commandHelpForArguments(argumentScan.commandArguments),subject:normalizedOption},kind:"expected-failure"}});return}const rootHelpDisposition=classifyRootHelp(commandArguments,nativeAction);if(rootHelpDisposition==="exact"){process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}if(rootHelpDisposition==="invalid"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"invalid-root-help-invocation",detail:"Root help accepts only `hi --help` or `hi -h`.",recoverable:true,recoveryCommand:"hi --help",subject:nativeAction??"--help"},kind:"expected-failure"}});return}if(parsedArguments.length===0){if(outputMode==="json"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command",detail:"Choose a Harness command.",recoverable:true,recoveryCommand:"hi --help",subject:"command"},kind:"expected-failure"}});return}process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}let capturedOutcome;const commandEffect=outputMode==="json"?cli(parsedArguments).pipe(provideService2(exports_CliOutput.Formatter,jsonCliFormatter),provideService2(Console,jsonCliConsole)):cli(parsedArguments);const outcome=yield*commandEffect.pipe(provideService2(SelectedOutputMode,outputMode),provideService2(RootPresentationSink,{publish:(publishedOutcome)=>sync2(()=>{capturedOutcome=publishedOutcome})}),match6({onFailure:presentationOutcome,onSuccess:()=>capturedOutcome}));if(outcome===undefined){return}const humanMode=outputMode==="interactive"?outputMode:"plain";const exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,humanMode),mode:outputMode,outcome});if(exitCode!==0){process.exitCode=exitCode}});var cliConfigLayer=makeCliConfigLayer(processProvider,processEnvironment);var ProjectSettingsLive=ProjectSettingsDefault.pipe(provide2(ProjectSettingsFileSystemLive));var scaffoldCapabilitiesLive=scaffoldCapabilitiesLayer.pipe(provide2(cliConfigLayer));var scopedScaffoldOperationLive=effect(ScopedScaffoldOperation,gen2(function*makeLiveScopedScaffoldOperation(){const projectSettings=yield*ProjectSettings;return makeScopedScaffoldOperation({adapter:makeScopedScaffoldOperationAdapter(),projectSettings,stage:makeStageScopedScaffoldAdapter({projectSettings})})})).pipe(provide2(ProjectSettingsLive));var skillsCliLive=makeSkillsCliLive({environment:processEnvironment});var featureApplicationDependencies=mergeAll2(exports_FetchHttpClient.layer,ProjectSettingsLive,ProjectProducerLive,cliConfigLayer,scaffoldCapabilitiesLive,scopedScaffoldOperationLive,skillsCliLive);var featureApplicationOperationsLive=featureApplicationOperationsLayer.pipe(provide2(featureApplicationDependencies));var mainLayer=mergeAll2(layer14,exports_CliConfig.layer({builtIns:effectBuiltIns}),exports_FetchHttpClient.layer,cliOutputLayer,cliPromptLayer,updateInteractionLayer.pipe(provide2(cliPromptLayer)),repositoryScaffoldingInteractionLayer.pipe(provide2(cliPromptLayer)),ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,scopedScaffoldOperationLive,repositoryCheckCapabilitiesLayer.pipe(provide2(merge2(cliConfigLayer,ProjectSettingsLive))),featureApplicationOperationsLive);if(__require.main==__require.module){main.pipe(provide4(mainLayer),(effect2)=>{runMain2(effect2)})}export{rootCommands,rootCommandNames,main};