@punks/cli 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/BASELINE_CHANGELOG.md +14 -1
  2. package/dist/CHANGELOG.md +15 -0
  3. package/dist/baseline/scaffold-baseline/baseline.json +5 -5
  4. package/dist/baseline/scaffold-baseline/data/catalog/lint-assets.json +48 -0
  5. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/post-command-flow.md +1 -6
  6. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/upstream/mattpocock-writing-skills.md +81 -12
  7. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/REFERENCE.md +11 -14
  8. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/SKILL.md +17 -14
  9. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/architecture-convergence.md +98 -0
  10. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/plan-schema.md +34 -0
  11. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/planner-task-graph.md +15 -12
  12. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/SKILL.md +6 -5
  13. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +10 -0
  14. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/architecture-conformance.md +100 -0
  15. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/lifecycle.md +25 -2
  16. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +17 -1
  17. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +14 -0
  18. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel.md +7 -0
  19. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/requirements-grill/SKILL.md +1 -1
  20. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-service-design/UPSTREAM.md +17 -0
  21. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/review.md +9 -34
  22. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/router.md +10 -16
  23. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/phase-handoff.md +1 -19
  24. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/AUTHORING-HANDOFF.md +11 -14
  25. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/retain-report.md +2 -9
  26. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/return-route.md +8 -6
  27. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/run-review.md +5 -8
  28. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/durable-report.md +14 -29
  29. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/state-graph.md +32 -45
  30. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/targets.md +1 -2
  31. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/scripts/review-contract.mjs +12 -86
  32. package/dist/baseline/scaffold-baseline.json +5 -5
  33. package/dist/baseline/scaffold-baseline.tgz +0 -0
  34. package/dist/index.js +5 -5
  35. package/dist/skills/agnostic/cli/hi-cli/references/post-command-flow.md +1 -6
  36. package/dist/skills/agnostic/docs/upstream/mattpocock-writing-skills.md +81 -12
  37. package/dist/skills/agnostic/planning/create-plan/REFERENCE.md +11 -14
  38. package/dist/skills/agnostic/planning/create-plan/SKILL.md +17 -14
  39. package/dist/skills/agnostic/planning/create-plan/references/architecture-convergence.md +98 -0
  40. package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +34 -0
  41. package/dist/skills/agnostic/planning/create-plan/references/planner-task-graph.md +15 -12
  42. package/dist/skills/agnostic/planning/implement-spec/SKILL.md +6 -5
  43. package/dist/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +10 -0
  44. package/dist/skills/agnostic/planning/implement-spec/references/architecture-conformance.md +100 -0
  45. package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +25 -2
  46. package/dist/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +17 -1
  47. package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +14 -0
  48. package/dist/skills/agnostic/planning/implement-spec/references/parallel.md +7 -0
  49. package/dist/skills/agnostic/requirements/requirements-grill/SKILL.md +1 -1
  50. package/dist/skills/frameworks/effect/effect-service-design/UPSTREAM.md +17 -0
  51. package/dist/skills/phases/delivery-phase/phases/review.md +9 -34
  52. package/dist/skills/phases/delivery-phase/phases/router.md +8 -14
  53. package/dist/skills/phases/delivery-phase/references/phase-handoff.md +1 -19
  54. package/dist/skills/phases/review-phase/AUTHORING-HANDOFF.md +11 -14
  55. package/dist/skills/phases/review-phase/phases/retain-report.md +2 -9
  56. package/dist/skills/phases/review-phase/phases/return-route.md +8 -6
  57. package/dist/skills/phases/review-phase/phases/run-review.md +5 -8
  58. package/dist/skills/phases/review-phase/references/durable-report.md +14 -29
  59. package/dist/skills/phases/review-phase/references/state-graph.md +5 -18
  60. package/dist/skills/phases/review-phase/references/targets.md +1 -2
  61. package/dist/skills/phases/review-phase/scripts/review-contract.mjs +11 -91
  62. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -282,7 +282,7 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
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 format3=getOption(security.annotations,Format).pipe(map((format4)=>({bearerFormat:format4})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format3}}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:()=>make38,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=make34(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 make38=(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:()=>make39,isHttpApiGroup:()=>isHttpApiGroup});var TypeId48="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId48);var Proto17={[TypeId48]:TypeId48,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,Proto17);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make39=(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="3.2.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="2a08f388158f95c204931e12530b21055aff6aac482ed798c0ac427aedfd7ca6";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 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",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:{"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"},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:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],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"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},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/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 validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=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);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})}}}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:"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:"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:"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:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",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:"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:"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:"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:"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 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={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 format3=getOption(security.annotations,Format).pipe(map((format4)=>({bearerFormat:format4})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format3}}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:()=>make38,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=make34(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 make38=(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:()=>make39,isHttpApiGroup:()=>isHttpApiGroup});var TypeId48="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId48);var Proto17={[TypeId48]:TypeId48,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,Proto17);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make39=(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="3.2.1";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="e9b8750c18fd4448034cfa52ca49bb05506d56c83ab0c6118d8a981f8102cec3";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"]},{description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],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"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},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 validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=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})}}}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:"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:"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:"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:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",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:"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:"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:"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:"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 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={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` before writing or editing prompt specs, handoffs, root/scoped `AGENTS.md`, or subagent templates/instructions.",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(`
@@ -2451,11 +2451,11 @@ for await (const line of lines) {
2451
2451
  `].join("")};var sortSubagentSpecialists=(spec)=>({...spec,specialists:spec.specialists.toSorted((left,right)=>left.id.localeCompare(right.id))});class ContextPlanCompilationFailure extends TaggedErrorClass()("@punks/cli/context-planning/ContextPlanCompilationFailure",{cause:Defect(),message:String4,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 add2=(pack,condition=true)=>{if(condition&&selectedPacks.has(pack)){packs.push(pack)}};add2("quality");add2("research");add2("typescript",relativeWorkspacePath!==".agents"&&relativeWorkspacePath!=="docs");if(relativeWorkspacePath===".agents"){add2("misc");add2("subagents");add2("docs");return uniqueSorted(packs)}if(relativeWorkspacePath==="."){return uniqueSorted([...packs,...finalPacks])}if(kind==="docs"){add2("docs");return uniqueSorted(packs)}add2("frontend",isFrontend);add2("react",isFrontend);add2("nextjs",isFrontend);add2("tanstack-query",isFrontend);add2("backend",isBackend&&!isFrontend);add2("elysia",isBackend&&!isFrontend);add2("effect",isBackend&&!isFrontend);add2("trpc",isBackend&&!isFrontend);add2("subagents",relativeWorkspacePath==="apps/cli");add2("turborepo",relativeWorkspacePath==="apps/cli");add2("better-auth",relativeWorkspacePath==="packages/auth");add2("effect",hasDependency("effect")||hasDependencyPrefix("@effect/"));add2("drizzle",hasDependency("drizzle-orm")||hasDependency("drizzle-kit"));add2("better-auth",hasDependency("better-auth"));add2("elysia",hasDependency("elysia"));add2("nextjs",hasDependency("next"));add2("react",hasDependency("react")||hasDependency("react-dom"));add2("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"));add2("trpc",hasDependencyPrefix("@trpc/"));add2("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)=>Object.fromEntries([["source",baseline.summary.source],["revision",baseline.summary.commit??baseline.summary.tag??baseline.summary.version]]);var contribution=({kind,id,references,compatibility,baseline,order})=>Object.fromEntries([["kind",kind],["identity",{id,version:baseline.summary.version}],["provenance",provenanceFor(baseline)],["compatibility",compatibility],["references",uniqueSorted(references)],["order",order]]);var promptSurfaceFor={docs:"docs-prompt-spec",root:"root-prompt-spec",shared:"shared-agents",workspace:"workspace-prompt-spec"};var contributionsForScope=({scope:scope3,packs,input:input2})=>{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:[]})))}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},order)=>contribution({baseline:input2.baseline,compatibility,id,kind,order,references}))};var compileContextPlanSync=(input2)=>Object.fromEntries([["version","1"],["scopes",input2.scopes.map((scope3)=>{const{packs}=resolveContextScopeSelectionSync({baseline:input2.baseline,finalPacks:input2.finalPacks,scope:scope3});return Object.fromEntries([["id",scope3.id],["packs",packs.map((id,order)=>({id,order}))],["contributions",contributionsForScope({input:input2,packs,scope:scope3})]])}).toSorted((left,right)=>String(left.id).localeCompare(String(right.id)))]]);var compileContextPlan=fn2("ContextPlanning.compile")(function*compileContextPlan2(input2){return yield*try_3({catch:(cause)=>cause instanceof ContextPlanResolutionFailure?cause:new ContextPlanCompilationFailure({cause,message:"Context plan compilation failed.",operation:"compile-context-plan"}),try:()=>compileContextPlanSync(input2)})});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){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",...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}]}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},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`,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";var childEnvironment=(baseEnvironment,overrides)=>{const env={};for(const[key,value5]of Object.entries(baseEnvironment??{})){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 nodeProcess={capture:(command,args2,options4)=>{const result4=spawnSync2(command,args2,{cwd:options4?.cwd,encoding:"utf-8",env:childEnvironment(options4?.baseEnvironment,options4?.env),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={},environmentOverrides={}})=>{nodeProcess.execute(scriptRuntimePath(runtimePath),[file5],{baseEnvironment:environment,cwd,env:environmentOverrides})};import{lstatSync as lstatSync3}from"node:fs";import path21 from"node:path";var preExistingSkillHomes=[".agents/skills",".claude/skills",".codex/skills",".cursor/skills",".opencode/skills"];var preExistingSkillSnapshotDirectories=preExistingSkillHomes.map((relativeDirectory)=>path21.posix.join(".devpunks/pre-existing-skills",relativeDirectory));var snapshotPreExistingSkillHomes=async(outputDirectory,session)=>{const snapshots=[];for(const relativeDirectory of preExistingSkillHomes){const sourceDirectory=path21.join(outputDirectory,relativeDirectory);assertConfinedDirectory({directoryPath:path21.dirname(sourceDirectory),outputDirectory,...session===undefined?{}:{session}});const stat3=lstatSync3(sourceDirectory,{throwIfNoEntry:false});if(stat3===undefined||stat3.isSymbolicLink()||!stat3.isDirectory()){continue}assertConfinedDirectory({directoryPath:sourceDirectory,outputDirectory,...session===undefined?{}:{session}});const targetPath=path21.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 encodeContextPlan2=encodeSync2(ContextPlan);var toPosixPath=(value5)=>value5.split(path22.sep).join("/");var relativePosixPath=(from,to)=>{const relativePath=path22.relative(from,to);return relativePath===""?".":toPosixPath(relativePath)};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 path22.posix.join(".devpunks/specs/prompts",path22.posix.dirname(promptTargetPath),"prompt.md")};var uniqueSorted2=(values)=>[...new Set(values)].toSorted();var collectOpensrcReferences=(promptSpecs)=>uniqueSorted2(promptSpecs.flatMap((spec)=>spec.opensrcReferences));var expectedPromptSpec=(promptSpecs,targetFile)=>promptSpecs.find((candidate)=>candidate.targetFile===targetFile);var fileMode=(mode)=>mode%512;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)=>existsSync8(path22.join(scanDirectory,candidate)));var oxlintStarterConfig=Object.fromEntries([["extends",["ultracite/oxlint/core"]],["configFile","oxlint.config.ts"]]);var oxlintConfigFileName="oxlint.config.ts";var ultraciteCorePreset="core";var defaultDevDependencyVersion="latest";var wikiWorkspacePaths=new Set(["wiki","app/wiki","apps/wiki"]);var isRecord5=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);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===`
2452
2452
  `){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(readFileSync8(filePath,"utf-8")));return isRecord5(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,indent=0,leadingWidth=indent)=>{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(indent+2)}${encodePrettyTsValue(entry,indent+2)},`),`${tsIndent(indent)}]`].join(`
2453
2453
  `)}if(isRecord5(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(indent+2)}${tsPropertyKey(key)}: `;return`${prefix}${encodePrettyTsValue(entry,indent+2,prefix.length)},`}),`${tsIndent(indent)}}`].join(`
2454
- `)}return JSON.stringify(value5)??"undefined"};var encodePrettyTsObject=(value5)=>encodePrettyTsValue(value5);var sourceOrOutputPath=({scanDirectory,outputDirectory,relativePath})=>{const outputPath=path22.join(outputDirectory,relativePath);if(existsSync8(outputPath)){return outputPath}const sourcePath=path22.join(scanDirectory,relativePath);return existsSync8(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 isRecord5(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 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 mergeLintAssetsIntoLocalOxlintConfig=(existingConfig,assets)=>{const{$schema:_schema,extends:_extends,...existingLocalConfig}=existingConfig;const nextConfig={...existingLocalConfig};const plugins=ensureStringArray(nextConfig.plugins);const ignorePatterns=uniqueSorted2([...ensureStringArray(nextConfig.ignorePatterns),...assets.flatMap((asset)=>asset.ignorePatterns??[])]);const jsPlugins=Array.isArray(nextConfig.jsPlugins)?[...nextConfig.jsPlugins]:[];const settings=isRecord5(nextConfig.settings)?{...nextConfig.settings}:{};const rules=isRecord5(nextConfig.rules)?{...nextConfig.rules}:{};for(const asset of assets){for(const plugin of asset.plugins){if(!plugins.includes(plugin)){plugins.push(plugin)}}for(const plugin of asset.jsPlugins){if(!jsPlugins.some((entry)=>jsPluginMatches(entry,plugin))){jsPlugins.push({name:plugin.name,specifier:plugin.specifier})}}for(const[key,value5]of Object.entries(asset.settings)){if(!(key in settings)){settings[key]=value5}}for(const[key,value5]of Object.entries(asset.rules)){if(!(key in rules)){rules[key]=value5}}}return{...nextConfig,...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})=>{const presets=lintPresetsForAssets(assets);const presetRules=lintPresetRulesForAssets(assets);const imports=presets.map((preset)=>`import ${oxlintPresetLocalName(preset)} from "ultracite/oxlint/${preset}";`);const existingExtends=ensureStringOrStringArray(existingConfig.extends);const extendsEntries=[...existingExtends.map((entry)=>JSON.stringify(entry)),...presets.map((preset)=>presetRules[preset]===undefined?oxlintPresetLocalName(preset):`${oxlintPresetLocalName(preset)}WithLocalRules`)];const localConfig=mergeLintAssetsIntoLocalOxlintConfig(existingConfig,assets);const{ignorePatterns,rules,...localConfigWithoutRules}=localConfig;const localRulesSource=rules===undefined?"":`const localRules = ${encodePrettyTsObject(rules)} satisfies OxlintConfig["rules"];
2454
+ `)}return JSON.stringify(value5)??"undefined"};var encodePrettyTsObject=(value5)=>encodePrettyTsValue(value5);var sourceOrOutputPath=({scanDirectory,outputDirectory,relativePath})=>{const outputPath=path22.join(outputDirectory,relativePath);if(existsSync8(outputPath)){return outputPath}const sourcePath=path22.join(scanDirectory,relativePath);return existsSync8(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 isRecord5(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 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 mergeLintAssetsIntoLocalOxlintConfig=(existingConfig,assets)=>{const{$schema:_schema,extends:_extends,...existingLocalConfig}=existingConfig;const nextConfig={...existingLocalConfig};const plugins=ensureStringArray(nextConfig.plugins);const ignorePatterns=uniqueSorted2([...ensureStringArray(nextConfig.ignorePatterns),...assets.flatMap((asset)=>asset.ignorePatterns??[])]);const jsPlugins=Array.isArray(nextConfig.jsPlugins)?[...nextConfig.jsPlugins]:[];const settings=isRecord5(nextConfig.settings)?{...nextConfig.settings}:{};const rules=isRecord5(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));for(const asset of orderedAssets){for(const plugin of asset.plugins){if(!plugins.includes(plugin)){plugins.push(plugin)}}for(const plugin of asset.jsPlugins){if(!jsPlugins.some((entry)=>jsPluginMatches(entry,plugin))){jsPlugins.push({name:plugin.name,specifier:plugin.specifier})}}for(const[key,value5]of Object.entries(asset.settings)){if(!(key in settings)){settings[key]=value5}}for(const[key,value5]of Object.entries(asset.rules)){if(!projectRuleNames.has(key)){rules[key]=value5}}}return{...nextConfig,...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})=>{const presets=lintPresetsForAssets(assets);const presetRules=lintPresetRulesForAssets(assets);const imports=presets.map((preset)=>`import ${oxlintPresetLocalName(preset)} from "ultracite/oxlint/${preset}";`);const existingExtends=ensureStringOrStringArray(existingConfig.extends);const extendsEntries=[...existingExtends.map((entry)=>JSON.stringify(entry)),...presets.map((preset)=>presetRules[preset]===undefined?oxlintPresetLocalName(preset):`${oxlintPresetLocalName(preset)}WithLocalRules`)];const localConfig=mergeLintAssetsIntoLocalOxlintConfig(existingConfig,assets);const{ignorePatterns,rules,...localConfigWithoutRules}=localConfig;const localRulesSource=rules===undefined?"":`const localRules = ${encodePrettyTsObject(rules)} satisfies OxlintConfig["rules"];
2455
2455
 
2456
- `;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";'];const ignorePatternsSource=ignorePatterns===undefined?" ignorePatterns: core.ignorePatterns,":[" ignorePatterns: ["," ...core.ignorePatterns,",...ensureStringArray(ignorePatterns).map((pattern)=>` ${JSON.stringify(pattern)},`)," ],"].join(`
2457
- `);return[...oxlintImports,...imports,"",...presetRulesSource,`${localRulesSource}const localConfig = ${localConfigSource}`,"","export default defineConfig({",` extends: [${extendsEntries.join(", ")}],`,ignorePatternsSource," ...localConfig,","});",""].join(`
2458
- `)};var rootPackageJsonRecord=({scanDirectory,outputDirectory})=>{const rootPackageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:"package.json",scanDirectory});return rootPackageJsonPath===null?null:readJsonRecord(rootPackageJsonPath)};var dependencyVersionFor=({rootPackageJson,packageName,isRootWorkspace})=>{const dependencySections=[rootPackageJson?.devDependencies,rootPackageJson?.dependencies,rootPackageJson?.peerDependencies,rootPackageJson?.optionalDependencies];for(const section2 of dependencySections){if(isRecord5(section2)&&typeof section2[packageName]==="string"){return section2[packageName]}}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord5(workspaces)?workspaces.catalog:undefined;if(!isRootWorkspace&&isRecord5(catalog)&&typeof catalog[packageName]==="string"){return"catalog:"}return defaultDevDependencyVersion};var packageHasDependency=(packageJson,packageName)=>[packageJson.dependencies,packageJson.devDependencies,packageJson.peerDependencies,packageJson.optionalDependencies].filter(isRecord5).some((section2)=>typeof section2[packageName]==="string");var patchPackageJsonDependencies=({packageJson,packageNames,rootPackageJson,isRootWorkspace})=>{const nextPackageJson={...packageJson};const devDependencies=isRecord5(nextPackageJson.devDependencies)?{...nextPackageJson.devDependencies}:{};for(const packageName of packageNames){if(packageHasDependency(nextPackageJson,packageName)){continue}devDependencies[packageName]=dependencyVersionFor({isRootWorkspace,packageName,rootPackageJson})}nextPackageJson.devDependencies=Object.fromEntries(Object.entries(devDependencies).toSorted(([left],[right])=>left.localeCompare(right)));return nextPackageJson};var lintTargetManifests=(detection)=>{if(!detection.monorepo){return detection.manifests}return detection.manifests.filter((manifest)=>path22.posix.dirname(toPosixPath(manifest.relativePath))!==".")};var existingJsonOxlintConfigPath=({scanDirectory,outputDirectory,workspacePath})=>{const candidates=[".oxlintrc.json",".oxlintrc.jsonc"].map((fileName)=>workspacePath==="."?fileName:path22.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=path22.join(scanDirectory,"docs");if(!existsSync8(docsDirectory)){return false}return readdirSync3(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 readdirSync3(directory3,{withFileTypes:true})){if(entry.isDirectory()){if(!ignoredPromptTargetDirectories.has(entry.name)){visit2(path22.join(directory3,entry.name))}continue}if(entry.isFile()&&entry.name==="AGENTS.md"){targets.push(relativePosixPath(scanDirectory,path22.join(directory3,entry.name)))}}};if(existsSync8(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 writeAppliedLintConfigs=({scanDirectory,outputDirectory,detection,contextPlan,baseline,planArtifact,generatedFiles,plannedDependencies,planOnly})=>{const rootPackageJson=planOnly?null:rootPackageJsonRecord({outputDirectory,scanDirectory});const applied=[];for(const manifest of lintTargetManifests(detection)){const manifestRelativePath=toPosixPath(manifest.relativePath);const workspacePath=path22.posix.dirname(manifestRelativePath);const normalizedWorkspacePath=workspacePath==="."?".":workspacePath;if(planOnly?detection.detectedLanguages.includes("python")&&!hasJavaScriptWorkspaceDependency(manifest):isPythonUvWorkspace({manifest,outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath})){continue}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"):selectedAssets;if(assets.length===0){continue}const configFile=normalizedWorkspacePath==="."?oxlintConfigFileName:path22.posix.join(normalizedWorkspacePath,oxlintConfigFileName);const existingConfigPath=planOnly?null:existingJsonOxlintConfigPath({outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath});const existingConfig=planOnly||existingConfigPath===null?{}:readJsonRecord(existingConfigPath);generatedFiles.push(planArtifact({content:isWikiWorkspace?makeWikiOxlintConfig({jsPlugins:assets.flatMap((asset)=>asset.jsPlugins),rules:Object.assign({},...assets.map((asset)=>asset.rules))}):encodeOxlintConfigTs({assets,existingConfig}),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:path22.posix.join(normalizedWorkspacePath,sourceFile.targetPath),source:"lint"}))}const packageJsonFile=manifestRelativePath;const requiredDevDependencies=uniqueSorted2(["oxlint","ultracite",...assets.flatMap((asset)=>asset.requiredDevDependencies)]);if(!planOnly){const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:packageJsonFile,scanDirectory});const packageJson=packageJsonPath===null?{}:readJsonRecord(packageJsonPath);planArtifact({content:encodePrettyJson2(patchPackageJsonDependencies({isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageNames:requiredDevDependencies,rootPackageJson})),kind:"harness",path:packageJsonFile,source:"lint"})}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:dependencyVersionFor({isRootWorkspace:normalizedWorkspacePath===".",packageName:name2,rootPackageJson}),workspace:normalizedWorkspacePath})));applied.push(Object.fromEntries([["workspace",normalizedWorkspacePath],["configFile",configFile],["packageJsonFile",packageJsonFile],["assets",assets.map((asset)=>asset.id)],["requiredDevDependencies",requiredDevDependencies]]))}return applied.toSorted((left,right)=>left.workspace.localeCompare(right.workspace))};var detectedWorkspaces=(scanDirectory,detection)=>detection.manifests.map((manifest)=>path22.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 path22.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=path22.join(scanDirectory,relativePath);const source=!forceGenerated&&existsSync8(sourcePath)?"copied":"generated";const workspacePath=workspacePathForPromptTarget(relativePath);return{opensrcReferences:opensrcReferencesForPacks(packs),packs,primarySkills,scope:promptScope(relativePath),source,specFile:specPathForPromptTarget(relativePath),targetFile:relativePath,workspacePath}};var buildSubagentManifestSpec=({detection,finalPacks,promptSpecs,workspaces=detectedWorkspaces(detection.cwd,detection)})=>{const specialists=promptSpecs.filter((spec)=>spec.scope==="docs"||spec.scope==="workspace").map((spec)=>Object.fromEntries([["id",(spec.workspacePath??spec.targetFile).replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"")],["ownedPaths",ownedPathsForPromptSpec(spec)],["guidanceFiles",[spec.targetFile]],["packs",spec.packs],["skills",spec.primarySkills.length===0?["simplify"]:spec.primarySkills],["notes",subagentSpecialistNote(spec)]]));return sortSubagentSpecialists(Object.fromEntries([["targetFile",".agents/subagents/manifest.mjs"],["specFile",".devpunks/specs/subagents/manifest-spec.json"],["finalPacks",finalPacks],["workspaces",workspaces],["specialists",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,"")}
2456
+ `;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(`
2457
+ `)}return[...oxlintImports,...imports,"",...presetRulesSource,`${localRulesSource}const localConfig = ${localConfigSource}`,"","export default defineConfig({",` extends: [${extendsEntries.join(", ")}],`,ignorePatternsSource," ...localConfig,","});",""].join(`
2458
+ `)};var rootPackageJsonRecord=({scanDirectory,outputDirectory})=>{const rootPackageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:"package.json",scanDirectory});return rootPackageJsonPath===null?null:readJsonRecord(rootPackageJsonPath)};var dependencyVersionFor=({rootPackageJson,packageName,isRootWorkspace})=>{const dependencySections=[rootPackageJson?.devDependencies,rootPackageJson?.dependencies,rootPackageJson?.peerDependencies,rootPackageJson?.optionalDependencies];for(const section2 of dependencySections){if(isRecord5(section2)&&typeof section2[packageName]==="string"){return section2[packageName]}}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord5(workspaces)?workspaces.catalog:undefined;if(!isRootWorkspace&&isRecord5(catalog)&&typeof catalog[packageName]==="string"){return"catalog:"}return defaultDevDependencyVersion};var packageHasDependency=(packageJson,packageName)=>[packageJson.dependencies,packageJson.devDependencies,packageJson.peerDependencies,packageJson.optionalDependencies].filter(isRecord5).some((section2)=>typeof section2[packageName]==="string");var patchPackageJsonDependencies=({packageJson,packageNames,rootPackageJson,isRootWorkspace})=>{const nextPackageJson={...packageJson};const devDependencies=isRecord5(nextPackageJson.devDependencies)?{...nextPackageJson.devDependencies}:{};for(const packageName of packageNames){if(packageHasDependency(nextPackageJson,packageName)){continue}devDependencies[packageName]=dependencyVersionFor({isRootWorkspace,packageName,rootPackageJson})}nextPackageJson.devDependencies=Object.fromEntries(Object.entries(devDependencies).toSorted(([left],[right])=>left.localeCompare(right)));return nextPackageJson};var lintTargetManifests=(detection)=>{if(!detection.monorepo){return detection.manifests}return detection.manifests.filter((manifest)=>path22.posix.dirname(toPosixPath(manifest.relativePath))!==".")};var existingJsonOxlintConfigPath=({scanDirectory,outputDirectory,workspacePath})=>{const candidates=[".oxlintrc.json",".oxlintrc.jsonc"].map((fileName)=>workspacePath==="."?fileName:path22.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=path22.join(scanDirectory,"docs");if(!existsSync8(docsDirectory)){return false}return readdirSync3(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 readdirSync3(directory3,{withFileTypes:true})){if(entry.isDirectory()){if(!ignoredPromptTargetDirectories.has(entry.name)){visit2(path22.join(directory3,entry.name))}continue}if(entry.isFile()&&entry.name==="AGENTS.md"){targets.push(relativePosixPath(scanDirectory,path22.join(directory3,entry.name)))}}};if(existsSync8(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 writeAppliedLintConfigs=({scanDirectory,outputDirectory,detection,contextPlan,baseline,planArtifact,generatedFiles,plannedDependencies,planOnly})=>{const rootPackageJson=planOnly?null:rootPackageJsonRecord({outputDirectory,scanDirectory});const applied=[];for(const manifest of lintTargetManifests(detection)){const manifestRelativePath=toPosixPath(manifest.relativePath);const workspacePath=path22.posix.dirname(manifestRelativePath);const normalizedWorkspacePath=workspacePath==="."?".":workspacePath;if(planOnly?detection.detectedLanguages.includes("python")&&!hasJavaScriptWorkspaceDependency(manifest):isPythonUvWorkspace({manifest,outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath})){continue}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){continue}const configFile=normalizedWorkspacePath==="."?oxlintConfigFileName:path22.posix.join(normalizedWorkspacePath,oxlintConfigFileName);const existingConfigPath=planOnly?null:existingJsonOxlintConfigPath({outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath});const existingConfig=planOnly||existingConfigPath===null?{}:readJsonRecord(existingConfigPath);generatedFiles.push(planArtifact({content:isWikiWorkspace?makeWikiOxlintConfig({jsPlugins:assets.flatMap((asset)=>asset.jsPlugins),rules:Object.assign({},...assets.map((asset)=>asset.rules))}):encodeOxlintConfigTs({assets,existingConfig}),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:path22.posix.join(normalizedWorkspacePath,sourceFile.targetPath),source:"lint"}))}const packageJsonFile=manifestRelativePath;const requiredDevDependencies=uniqueSorted2(["oxlint","ultracite",...assets.flatMap((asset)=>asset.requiredDevDependencies)]);if(!planOnly){const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:packageJsonFile,scanDirectory});const packageJson=packageJsonPath===null?{}:readJsonRecord(packageJsonPath);planArtifact({content:encodePrettyJson2(patchPackageJsonDependencies({isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageNames:requiredDevDependencies,rootPackageJson})),kind:"harness",path:packageJsonFile,source:"lint"})}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:dependencyVersionFor({isRootWorkspace:normalizedWorkspacePath===".",packageName:name2,rootPackageJson}),workspace:normalizedWorkspacePath})));applied.push(Object.fromEntries([["workspace",normalizedWorkspacePath],["configFile",configFile],["packageJsonFile",packageJsonFile],["assets",assets.map((asset)=>asset.id)],["requiredDevDependencies",requiredDevDependencies]]))}return applied.toSorted((left,right)=>left.workspace.localeCompare(right.workspace))};var detectedWorkspaces=(scanDirectory,detection)=>detection.manifests.map((manifest)=>path22.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 path22.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=path22.join(scanDirectory,relativePath);const source=!forceGenerated&&existsSync8(sourcePath)?"copied":"generated";const workspacePath=workspacePathForPromptTarget(relativePath);return{opensrcReferences:opensrcReferencesForPacks(packs),packs,primarySkills,scope:promptScope(relativePath),source,specFile:specPathForPromptTarget(relativePath),targetFile:relativePath,workspacePath}};var buildSubagentManifestSpec=({detection,finalPacks,promptSpecs,workspaces=detectedWorkspaces(detection.cwd,detection)})=>{const specialists=promptSpecs.filter((spec)=>spec.scope==="docs"||spec.scope==="workspace").map((spec)=>Object.fromEntries([["id",(spec.workspacePath??spec.targetFile).replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"")],["ownedPaths",ownedPathsForPromptSpec(spec)],["guidanceFiles",[spec.targetFile]],["packs",spec.packs],["skills",spec.primarySkills.length===0?["simplify"]:spec.primarySkills],["notes",subagentSpecialistNote(spec)]]));return sortSubagentSpecialists(Object.fromEntries([["targetFile",".agents/subagents/manifest.mjs"],["specFile",".devpunks/specs/subagents/manifest-spec.json"],["finalPacks",finalPacks],["workspaces",workspaces],["specialists",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,"")}
2459
2459
  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]));let changed=false;const normalize2=(skillIds)=>{const normalized=skillIds.map((skillId)=>aliases.get(skillId)??skillId);if(normalized.every((skillId,index)=>skillId===skillIds[index])){return skillIds}changed=true;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{changed,manifest:{agents,capabilityPacks}}};var renderPreservedSubagentManifestModule=(manifest)=>["const capabilityPacks = ",JSON.stringify(manifest.capabilityPacks,null,2),`;
2460
2460
  `,"const agents = ",JSON.stringify(manifest.agents,null,2),`;
2461
2461
  `,`export { agents, capabilityPacks };