@zaip-ai/cli 1.4.1 → 1.4.3

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 (36) hide show
  1. package/dist/services/install-agents-template.d.ts.map +1 -1
  2. package/dist/services/install-agents-template.js +9 -0
  3. package/dist/services/install-agents-template.js.map +1 -1
  4. package/package.json +1 -1
  5. package/templates/.agents/architecture/software-architecture.md +61 -0
  6. package/templates/.agents/dashboard/.zaip-managed.json +12 -4
  7. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +183 -183
  8. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +2 -2
  9. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +183 -183
  10. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-runtime-selection.mjs +36 -0
  11. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-runtime-selection.test.mjs +63 -0
  12. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard.mjs +31 -28
  13. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  14. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  15. package/templates/.agents/requirements/comparative-audit.md +1 -1
  16. package/templates/.agents/requirements/context-engine.md +1 -1
  17. package/templates/.agents/requirements/cost-observability.md +1 -1
  18. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  19. package/templates/.agents/requirements/data-export.md +1 -1
  20. package/templates/.agents/requirements/design-system.md +1 -1
  21. package/templates/.agents/requirements/execution-engine.md +1 -1
  22. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  23. package/templates/.agents/requirements/model-orchestration.md +1 -1
  24. package/templates/.agents/requirements/public-distribution.md +1 -1
  25. package/templates/.agents/requirements/software-architecture.md +1 -1
  26. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  27. package/templates/.agents/requirements/work-lifecycle.md +1 -1
  28. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  29. package/templates/.agents/runtime/bin/zaip.mjs +42 -35
  30. package/templates/.agents/runtime/checksums.sha256 +2 -2
  31. package/templates/.agents/runtime/provenance.json +2 -2
  32. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +1 -1
  33. package/templates/.agents/skills/zaip-skill-execution/references/candidate-workflow.md +23 -0
  34. package/templates/.agents/skills/zaip-skill-task/SKILL.md +1 -0
  35. package/templates/template-manifest.json +44 -32
  36. package/templates/.agents/architecture/.gitkeep +0 -0
@@ -200,7 +200,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
200
200
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
201
201
  `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Us(r,n.start),r.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",o=[];if(r&&n.sep&&!n.value){let a=[];for(let s=0;s<n.sep.length;++s){let l=n.sep[s];switch(l.type){case"newline":a.push(s);break;case"space":break;case"comment":l.indent>t.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=n.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(yr(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Oy(n.key)&&!yr(n.sep,"newline")){let a=ei(n.start),s=n.key,l=n.sep;l.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:s,sep:l}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(yr(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let a=ei(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?t.items.push({start:o,key:null,sep:[this.sourceToken]}):yr(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);r||n.value?(t.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(a):(Object.assign(n,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(t);if(a){if(a.type==="block-seq"){if(!n.explicitKey&&n.sep&&!yr(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Us(r,n.start),r.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||yr(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Ms(i),o=ei(r);ky(t);let a=t.end.splice(1,t.end.length);a.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:a}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
202
202
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
203
- `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ms(t),i=ei(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ms(t),i=ei(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};wy.Parser=Tu});var Ry=w(Gi=>{"use strict";var Ay=fu(),HU=Fi(),Ki=Vi(),JU=_l(),KU=Re(),GU=Au(),Ty=Nu();function Ny(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GU.LineCounter||null,prettyErrors:t}}function XU(e,t={}){let{lineCounter:n,prettyErrors:i}=Ny(t),r=new Ty.Parser(n?.addNewLine),o=new Ay.Composer(t),a=Array.from(o.compose(r.parse(e)));if(i&&n)for(let s of a)s.errors.forEach(Ki.prettifyError(e,n)),s.warnings.forEach(Ki.prettifyError(e,n));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function Iy(e,t={}){let{lineCounter:n,prettyErrors:i}=Ny(t),r=new Ty.Parser(n?.addNewLine),o=new Ay.Composer(t),a=null;for(let s of o.compose(r.parse(e),!0,e.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new Ki.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(a.errors.forEach(Ki.prettifyError(e,n)),a.warnings.forEach(Ki.prettifyError(e,n))),a}function YU(e,t,n){let i;typeof t=="function"?i=t:n===void 0&&t&&typeof t=="object"&&(n=t);let r=Iy(e,n);if(!r)return null;if(r.warnings.forEach(o=>JU.warn(r.options.logLevel,o)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function QU(e,t,n){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}return KU.isDocument(e)&&!i?e.toString(n):new HU.Document(e,i,n).toString(n)}Gi.parse=YU;Gi.parseAllDocuments=XU;Gi.parseDocument=Iy;Gi.stringify=QU});var Ru=w(xe=>{"use strict";var ex=fu(),tx=Fi(),nx=Jl(),Iu=Vi(),rx=wi(),hr=Re(),ix=pr(),ox=rt(),ax=mr(),sx=gr(),cx=Cs(),lx=Ou(),ux=Au(),dx=Nu(),xs=Ry(),$y=bi();xe.Composer=ex.Composer;xe.Document=tx.Document;xe.Schema=nx.Schema;xe.YAMLError=Iu.YAMLError;xe.YAMLParseError=Iu.YAMLParseError;xe.YAMLWarning=Iu.YAMLWarning;xe.Alias=rx.Alias;xe.isAlias=hr.isAlias;xe.isCollection=hr.isCollection;xe.isDocument=hr.isDocument;xe.isMap=hr.isMap;xe.isNode=hr.isNode;xe.isPair=hr.isPair;xe.isScalar=hr.isScalar;xe.isSeq=hr.isSeq;xe.Pair=ix.Pair;xe.Scalar=ox.Scalar;xe.YAMLMap=ax.YAMLMap;xe.YAMLSeq=sx.YAMLSeq;xe.CST=cx;xe.Lexer=lx.Lexer;xe.LineCounter=ux.LineCounter;xe.Parser=dx.Parser;xe.parse=xs.parse;xe.parseAllDocuments=xs.parseAllDocuments;xe.parseDocument=xs.parseDocument;xe.stringify=xs.stringify;xe.visit=$y.visit;xe.visitAsync=$y.visitAsync});var jP={};Kv(jP,{SqliteReadModelFileSystem:()=>rc,allocateAttributedTokenActiveMs:()=>ec,rebuildSqliteReadModel:()=>xP,sourceFingerprint:()=>no,sqliteReadModelPath:()=>nc,sqliteViewMetadata:()=>sd,validateSqliteReadModelSchema:()=>tc});module.exports=Gv(jP);var oo=require("node:crypto"),bv=require("node:fs"),ic=require("node:fs/promises"),ao=require("node:path"),Lr=require("node:sqlite");var be=ut(pt(),1),gD=be.z.object({provider:be.z.string().min(1),models:be.z.array(be.z.string().min(1)).min(1),reasoning_efforts:be.z.array(be.z.enum(["low","medium","high","xhigh"])).min(1),velocities:be.z.array(be.z.literal("standard")).length(1),streaming:be.z.boolean(),cancellation:be.z.boolean(),checkpointing:be.z.boolean(),resume:be.z.boolean(),tool_calls:be.z.boolean(),structured_output:be.z.boolean(),max_parallel_invocations:be.z.number().int().positive()}).strict().superRefine((e,t)=>{e.resume&&!e.checkpointing&&t.addIssue({code:"custom",message:"Resume requires checkpointing"})}),hC=be.z.object({role:be.z.enum(["system","user","assistant","tool"]),content:be.z.string(),name:be.z.string().min(1).nullable().default(null)}).strict(),yD=be.z.object({schema_version:be.z.literal(1),invocation_id:be.z.string().regex(/^INV-[A-Z0-9-]+$/),agent_id:be.z.string().min(1),model:be.z.string().min(1),reasoning_effort:be.z.enum(["low","medium","high","xhigh"]),velocity:be.z.literal("standard"),input:be.z.object({messages:be.z.array(hC).min(1),context_refs:be.z.array(be.z.string().min(1)),tools:be.z.array(be.z.string().min(1)),response_format:be.z.enum(["text","json"])}).strict(),budget:be.z.object({max_output_tokens:be.z.number().int().positive(),timeout_ms:be.z.number().int().positive().nullable(),max_tool_calls:be.z.number().int().nonnegative()}).strict(),metadata:be.z.record(be.z.string(),be.z.string()),resume_from:be.z.string().min(1).nullable()}).strict(),hD=be.z.object({invocation_id:be.z.string().regex(/^INV-[A-Z0-9-]+$/),reason:be.z.enum(["user","budget","timeout","shutdown","superseded"]),requested_at:be.z.string().datetime()}).strict();var ye=ut(pt(),1),er={schema_version:ye.z.literal(1),invocation_id:ye.z.string().regex(/^INV-[A-Z0-9-]+$/),sequence:ye.z.number().int().nonnegative(),occurred_at:ye.z.string().datetime()},vC=ye.z.object({checkpoint_id:ye.z.string().regex(/^CHK-[A-Z0-9-]+$/),opaque_token:ye.z.string().min(1),resumable_until:ye.z.string().datetime().nullable(),state_hash:ye.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),jf=ye.z.object({input_tokens:ye.z.number().int().nonnegative(),cached_input_tokens:ye.z.number().int().nonnegative(),output_tokens:ye.z.number().int().nonnegative(),reasoning_tokens:ye.z.number().int().nonnegative(),source:ye.z.enum(["provider","estimated","unavailable"])}).strict(),SC=ye.z.object({code:ye.z.enum(["authentication","authorization","invalid_request","rate_limit","provider_unavailable","timeout","budget_exceeded","tool_error","protocol_error","unknown"]),message:ye.z.string().min(1),retryable:ye.z.boolean(),retry_after_ms:ye.z.number().int().nonnegative().nullable(),provider_code:ye.z.string().nullable()}).strict(),bC=ye.z.discriminatedUnion("type",[ye.z.object({...er,type:ye.z.literal("invocation.started")}).strict(),ye.z.object({...er,type:ye.z.literal("output.delta"),delta:ye.z.string().min(1)}).strict(),ye.z.object({...er,type:ye.z.literal("tool.requested"),call_id:ye.z.string().min(1),name:ye.z.string().min(1),arguments:ye.z.unknown()}).strict(),ye.z.object({...er,type:ye.z.literal("tool.completed"),call_id:ye.z.string().min(1),output:ye.z.unknown()}).strict(),ye.z.object({...er,type:ye.z.literal("checkpoint.created"),checkpoint:vC}).strict(),ye.z.object({...er,type:ye.z.literal("usage.updated"),usage:jf}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.completed"),output:ye.z.string(),usage:jf}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.failed"),error:SC}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.cancelled"),reason:ye.z.string().min(1)}).strict()]);var _e=ut(pt(),1),bt=_e.z.array(_e.z.string().min(1)).superRefine((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:"custom",message:"Values must be unique"})}),zf=_e.z.string().regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/),EC=_e.z.object({nome:zf,cargo:zf,foto_url:_e.z.url().refine(e=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Persona photo URL must use http or https").optional()}).strict();function kC(e){return`${e.nome}_${e.cargo}_zaip_agent`}var OC=bt.length(1).superRefine((e,t)=>{for(let[n,i]of e.entries())/^[a-z0-9_]+$/.test(i)||t.addIssue({code:"custom",path:[n],message:"Codex nicknames must be lowercase snake_case"})}),wC=_e.z.string().regex(/^zaip-agent-[a-z0-9-]+$/,'Codex agent name must use the "zaip-agent-NOME" format'),AC=_e.z.string().regex(/^[a-z0-9_]+$/,"Codex task name must use lowercase snake_case"),Ff=_e.z.enum(["orchestrator","analyst","task-executor","execution-finalizer","builder","reviewer","integrator","auditor"]),TC=_e.z.enum(["id","codex_name","codex_task_name"]),NC=_e.z.object({kind:TC,value:_e.z.string().min(1),deprecated_at:_e.z.iso.date(),remove_after:_e.z.iso.date(),replacement:_e.z.string().regex(/^agent-[a-z0-9-]+$/)}).strict().superRefine((e,t)=>{(e.kind==="id"?/^agent-[a-z0-9-]+$/.test(e.value):e.kind==="codex_name"?/^zaip-agent-[a-z0-9-]+$/.test(e.value):/^[a-z0-9_]+$/.test(e.value))||t.addIssue({code:"custom",path:["value"],message:`Alias value does not match identity kind ${e.kind}`}),e.remove_after<=e.deprecated_at&&t.addIssue({code:"custom",path:["remove_after"],message:"Alias removal date must be after its deprecation date"})}),Da=_e.z.object({allow:bt,deny:bt}).strict().superRefine((e,t)=>{let n=e.allow.filter(i=>e.deny.includes(i));n.length>0&&t.addIssue({code:"custom",message:`Permission both allowed and denied: ${n.join(", ")}`})}),IC=_e.z.object({id:_e.z.string().regex(/^agent-[a-z0-9-]+$/),version:_e.z.number().int().positive(),purpose:_e.z.string().min(1),use_when:bt.min(1),do_not_use:bt.min(1),codex_name:wC,codex_task_name:AC,persona:EC,nickname_candidates:OC,compatibility:_e.z.object({aliases:_e.z.array(NC)}).strict().optional(),role:Ff,priority:_e.z.number().int().nonnegative().default(100),inherits:_e.z.string().regex(/^agent-[a-z0-9-]+$/).nullable().default(null),capabilities:bt.min(1),execution_eligibility:_e.z.array(_e.z.enum(["interaction","delivery"])),tools:bt,skills:bt,write_scopes:bt,permissions:_e.z.object({filesystem:Da,network:Da,shell:Da,deployment:Da}).strict(),model:_e.z.object({required_capabilities:bt,preferred:bt,reasoning_effort:_e.z.enum(["low","medium","high","xhigh","ultra"]).optional()}).strict(),budget:_e.z.object({soft_cycles:_e.z.number().int().positive()}).strict(),contract:_e.z.object({inputs:bt.min(1),outputs:bt.min(1),evidence:bt.min(1)}).strict(),review:_e.z.object({can_approve:_e.z.boolean(),cannot_review_roles:_e.z.array(Ff)}).strict(),escalation:bt}).strict().superRefine((e,t)=>{let n=e.nickname_candidates[0];e.codex_task_name!==n&&t.addIssue({code:"custom",path:["codex_task_name"],message:`Codex task name must equal the primary nickname candidate: ${n}`});let i=kC(e.persona);e.nickname_candidates[0]!==i&&t.addIssue({code:"custom",path:["nickname_candidates"],message:`nickname_candidates must contain only the derived persona nickname: ${i}`})}),RC=_e.z.object({id:_e.z.string().regex(/^squad-[a-z0-9-]+$/),version:_e.z.number().int().positive(),purpose:_e.z.string().min(1),members:_e.z.array(_e.z.string().regex(/^agent-[a-z0-9-]+$/)).min(2),max_parallelism:_e.z.number().int().positive(),delegation:_e.z.array(_e.z.object({from:_e.z.string().regex(/^agent-[a-z0-9-]+$/),to:_e.z.string().regex(/^agent-[a-z0-9-]+$/),capability:_e.z.string().min(1)}).strict()),review_policy:_e.z.object({independent:_e.z.literal(!0),executor_roles:_e.z.array(_e.z.enum(["analyst","builder","task-executor"])).min(1),reviewer_roles:_e.z.array(_e.z.enum(["reviewer","auditor"])).min(1)}).strict(),escalation:_e.z.array(_e.z.string().regex(/^agent-[a-z0-9-]+$/)).min(1)}).strict(),ND=_e.z.object({schema_version:_e.z.literal(1),agents:_e.z.array(IC).min(1),squads:_e.z.array(RC).min(1)}).strict();var Z=ut(pt(),1);var pe=ut(pt(),1),$C=["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"],CC=["low","medium","high","xhigh"];var Zf="task-risk-v1",jD=pe.z.enum($C),zD=pe.z.enum(CC),LC=pe.z.literal("standard"),FD=pe.z.object({model:pe.z.string().min(1).optional(),reasoning_effort:pe.z.string().min(1).optional(),velocity:pe.z.string().min(1).optional()}).strict().refine(e=>e.model!==void 0||e.reasoning_effort!==void 0||e.velocity!==void 0,"Model selection override must define at least one field"),MC=pe.z.enum(["discovery","planning","replanning","implementation","testing","integration","review","audit","finalization","rework"]),UC=pe.z.enum(["full_stack_boundary","shared_contracts_3_plus","critical_data_or_security","rollout_and_rollback","repeated_structural_repair","architectural_review_finding","prepared_plan_invalidated","material_architectural_tradeoffs"]),xC=pe.z.object({phase:MC,agent_role:pe.z.string().min(1),complexity:pe.z.enum(["simple","standard","complex"]),risk:pe.z.enum(["lite","standard","critical"]),transversality:pe.z.enum(["local","multi_module","cross_system"]),ambiguity:pe.z.enum(["low","medium","high"]),rework:pe.z.enum(["none","localized","structural"]),rework_cost:pe.z.enum(["low","medium","high"]),bounded:pe.z.boolean(),high_volume:pe.z.boolean().default(!1),xhigh_triggers:pe.z.array(UC).default([])}).strict(),Kc=pe.z.object({production_impact:pe.z.boolean(),external_action:pe.z.boolean(),irreversible_change:pe.z.boolean(),security_or_critical_data:pe.z.boolean(),data_migration:pe.z.boolean(),broad_audit:pe.z.boolean(),rollback:pe.z.enum(["trivial","planned","complex"]),verification_scope:pe.z.enum(["scoped","package","cross_scope","full"])}).strict(),PC=xC.omit({agent_role:!0,risk:!0}).extend({risk_signals:Kc}).strict(),ZD=PC.extend({risk:pe.z.enum(["lite","standard","critical"]),risk_signals:Kc,risk_policy_version:pe.z.literal(Zf),risk_reasons:pe.z.array(pe.z.enum(["CRITICAL_EXPLICIT_IMPACT","CRITICAL_COMPLEX_ROLLBACK","CRITICAL_AMBIGUOUS_CROSS_SYSTEM","CRITICAL_STRUCTURAL_REWORK","LITE_BOUNDED_LOCAL","STANDARD_GOVERNED"])).min(1)}).strict().superRefine((e,t)=>{let n=DC(e);e.risk!==n.risk&&t.addIssue({code:"custom",path:["risk"],message:`Task risk must be ${n.risk} for the persisted signals`}),JSON.stringify(e.risk_reasons)!==JSON.stringify(n.reasons)&&t.addIssue({code:"custom",path:["risk_reasons"],message:`Task risk reasons must be ${n.reasons.join(",")}`})}),qD=pe.z.object({models:pe.z.array(pe.z.string().min(1)).min(1),reasoning_efforts:pe.z.array(pe.z.string().min(1)).min(1),velocities:pe.z.array(pe.z.string().min(1)).min(1)}).strict(),qf=pe.z.object({mode:pe.z.literal("auto"),default_model:pe.z.literal("gpt-5.6-terra"),default_effort:pe.z.literal("medium"),default_velocity:LC,allowed_models:pe.z.tuple([pe.z.literal("gpt-5.6-luna"),pe.z.literal("gpt-5.6-terra"),pe.z.literal("gpt-5.6-sol")]),allowed_efforts:pe.z.tuple([pe.z.literal("low"),pe.z.literal("medium"),pe.z.literal("high"),pe.z.literal("xhigh")]),max_auto_effort:pe.z.literal("xhigh"),automatic_sources:pe.z.tuple([pe.z.literal("spec"),pe.z.literal("prd")]),notice:pe.z.enum(["always","mismatch"])}).strict();function DC(e){let t=Kc.parse(e.risk_signals);return t.production_impact||t.external_action||t.irreversible_change||t.security_or_critical_data||t.data_migration||t.broad_audit?qr("critical","CRITICAL_EXPLICIT_IMPACT"):t.rollback==="complex"?qr("critical","CRITICAL_COMPLEX_ROLLBACK"):e.ambiguity==="high"&&e.transversality==="cross_system"?qr("critical","CRITICAL_AMBIGUOUS_CROSS_SYSTEM"):e.rework==="structural"&&e.rework_cost==="high"?qr("critical","CRITICAL_STRUCTURAL_REWORK"):e.complexity==="simple"&&e.transversality==="local"&&e.ambiguity==="low"&&e.rework==="none"&&e.rework_cost==="low"&&e.bounded&&t.rollback==="trivial"&&t.verification_scope==="scoped"?qr("lite","LITE_BOUNDED_LOCAL"):qr("standard","STANDARD_GOVERNED")}function qr(e,t){return{risk:e,policy_version:Zf,reasons:[t]}}var Cu=ut(Ru(),1),_x=10,$u=class extends Error{name="YamlContractError"};function Xi(e){let t=(0,Cu.parseDocument)(e,{strict:!0,uniqueKeys:!0});if(t.errors.length>0)throw new $u(t.errors.map(n=>n.message).join("; "));return t.toJS({maxAliasCount:_x})}var Ps=Z.z.string().regex(/^[a-f0-9]{64}$/i,"Expected a SHA-256 checksum"),fx=Z.z.string().min(1).superRefine((e,t)=>{try{new Intl.DateTimeFormat("en",{timeZone:e}).format()}catch{t.addIssue({code:"custom",message:"Expected a valid IANA timezone"})}}),mx=Z.z.string().min(1).max(255).refine(e=>e.trim()===e&&!/[\r\n\0]/.test(e),"Expected a non-empty Git branch name");function gx(e){return e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||e.endsWith("/")||/^[A-Za-z]:/.test(e)?!1:e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}var yx=Z.z.object({sha256:Ps}).strict();function Cy(e){return Z.z.record(Z.z.string().min(1),e).superRefine((t,n)=>{for(let i of Object.keys(t))gx(i)||n.addIssue({code:"custom",path:[i],message:"Managed file path must be canonical and workspace-relative"})})}var hx=Cy(yx),vx=Cy(Ps),Sx=Z.z.object({schema_version:Z.z.literal(1),zaip:Z.z.object({enabled:Z.z.boolean()}).strict().optional(),"zaip-aios":Z.z.object({enabled:Z.z.boolean()}).strict().optional(),project:Z.z.object({id:Z.z.string().min(1),name:Z.z.string().min(1),timezone:fx}).strict(),stack:Z.z.object({id:Z.z.string().min(1),language:Z.z.string().min(1).optional(),api:Z.z.string().min(1).optional(),query_builder:Z.z.string().min(1).optional(),extensions:Z.z.array(Z.z.string().min(1)).min(1).optional(),layout:Z.z.object({frontend:Z.z.string().min(1),backend:Z.z.string().min(1),site:Z.z.string().min(1),modules:Z.z.string().min(1),packages:Z.z.string().min(1),e2e:Z.z.string().min(1)}).strict().optional(),source_limits:Z.z.object({warning_lines:Z.z.number().int().positive(),error_lines:Z.z.number().int().positive()}).strict().optional(),invariants:Z.z.array(Z.z.string().min(1)).min(1).optional(),commands:Z.z.object({test:Z.z.string().min(1),typecheck:Z.z.string().min(1)}).strict().optional(),overrides:Z.z.record(Z.z.string(),Z.z.unknown())}).strict(),clients:Z.z.object({codex:Z.z.boolean(),claude:Z.z.boolean()}).strict(),tracking:Z.z.object({enabled:Z.z.boolean(),currency:Z.z.string().regex(/^[A-Z]{3}$/,"Expected an ISO 4217 currency code"),storage_mode:Z.z.enum(["tracked_sanitized","local_only"])}).strict(),deploy:Z.z.object({branch:mx.optional()}).strict().optional(),model_orchestration:Z.z.discriminatedUnion("mode",[Z.z.object({mode:Z.z.literal("manual"),default_model:Z.z.literal("manual"),default_effort:Z.z.literal("manual"),default_velocity:Z.z.literal("manual"),notice:Z.z.enum(["always","mismatch"])}).strict(),Z.z.object({mode:Z.z.literal("off"),default_model:Z.z.string().min(1),default_effort:Z.z.string().min(1),default_velocity:Z.z.string().min(1),notice:Z.z.enum(["always","mismatch"])}).strict(),qf]).optional(),execution:Z.z.discriminatedUnion("runtime",[Z.z.object({runtime:Z.z.literal("manual")}).strict(),Z.z.object({runtime:Z.z.literal("autonomous"),autonomous:Z.z.object({provider:Z.z.enum(["codex","claude"]),model:Z.z.string().min(1),max_parallelism:Z.z.number().int().min(1).max(8),lease_ms:Z.z.number().int().min(5e3).max(36e5),max_phase_attempts:Z.z.number().int().positive().nullable().optional(),max_total_invocations:Z.z.number().int().positive().nullable().optional()}).strict()}).strict()]).optional(),assurance:Z.z.object({version:Z.z.literal(1),standard_depth:Z.z.enum(["auto","base","elevated"]),require_final_commit:Z.z.boolean()}).strict().optional(),context:Z.z.object({canonical_roots:Z.z.array(Z.z.string().min(1)).min(1),projection_roots:Z.z.array(Z.z.string().min(1))}).strict().optional()}).strict().superRefine((e,t)=>{let n=e.zaip?.enabled,i=e["zaip-aios"]?.enabled;n!==void 0&&i!==void 0&&n!==i&&t.addIssue({code:"custom",path:["zaip","enabled"],message:"Conflicting ZAIP activation keys: zaip.enabled and legacy zaip-aios.enabled must agree"})}),Ly={framework:Z.z.object({version:Z.z.string().min(1),distribution_sha256:Ps.nullable()}).strict(),layout:Z.z.object({version:Z.z.union([Z.z.literal(2),Z.z.literal(3)])}).strict(),resolved_profile:Z.z.object({id:Z.z.string().min(1).nullable(),sha256:Ps.nullable()}).strict()},bx=Z.z.object({lock_version:Z.z.literal(1),...Ly,managed_files:hx}).strict(),Ex=Z.z.object({lock_version:Z.z.literal(2),...Ly,managed_files:vx}).strict(),_z=Z.z.toJSONSchema(Sx),pz=Z.z.toJSONSchema(Z.z.union([bx,Ex]));var Oe=require("node:fs/promises"),Fe=require("node:path");var Uy=require("node:crypto");var My="23456789ABCDEFGHJKLMNPQRSTUVWXYZ";function Ds(e=4){if(!Number.isSafeInteger(e)||e<2||e>16)throw new RangeError("collision code length must be between 2 and 16");let t=(0,Uy.randomBytes)(e);return Array.from(t,n=>My[n%My.length]).join("")}var Gn=class extends Error{name="WorkspacePathError"},Qi=class{root;appendQueues=new Map;constructor(t){this.root=(0,Fe.resolve)(t)}resolve(t){if(kx(t)||Ox(t))throw new Gn("Expected a path relative to the workspace root");let n=(0,Fe.resolve)(this.root,t),i=(0,Fe.relative)(this.root,n);if(i===".."||i.startsWith(`..${Fe.sep}`)||(0,Fe.isAbsolute)(i))throw new Gn(`Path escapes workspace root: ${t}`);return n}async exists(t){try{let n=this.resolve(t);return await this.assertPhysicalContainment(n),await(0,Oe.stat)(n),!0}catch(n){if(Yi(n)&&n.code==="ENOENT")return!1;throw n}}async readText(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),(0,Oe.readFile)(n,"utf8")}async readBytes(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),(0,Oe.readFile)(n)}async readTextFrom(t,n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("Expected a non-negative byte offset");let i=this.resolve(t);await this.assertPhysicalContainment(i);let r=await(0,Oe.open)(i,"r");try{let o=await r.stat(),a=Math.min(n,o.size),s=Buffer.allocUnsafe(o.size-a);return s.byteLength>0&&await r.read(s,0,s.byteLength,a),{content:s.toString("utf8"),nextOffset:o.size}}finally{await r.close()}}async listFiles(t,n=""){let i=this.resolve(t);return await this.assertPhysicalContainment(i),await this.exists(t)?(await(0,Oe.readdir)(i,{recursive:!0,withFileTypes:!0})).filter(o=>o.isFile()).map(o=>(0,Fe.relative)(this.root,(0,Fe.resolve)(o.parentPath,o.name)).replace(/\\/g,"/")).filter(o=>o.endsWith(n)).sort():[]}async listDirectories(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),await this.exists(t)?(await(0,Oe.readdir)(n,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>(0,Fe.relative)(this.root,(0,Fe.resolve)(n,r.name)).replace(/\\/g,"/")).sort():[]}async writeTextAtomic(t,n){let i=this.resolve(t),r=`${i}.${Ds(6)}.tmp`;await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i);try{await(0,Oe.writeFile)(r,n,{encoding:"utf8",flag:"wx"}),await wx(r,i)}finally{await(0,Oe.rm)(r,{force:!0})}}async appendText(t,n){let i=this.resolve(t),o=(this.appendQueues.get(i)??Promise.resolve()).catch(()=>{}).then(async()=>{await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i),await(0,Oe.appendFile)(i,n,{encoding:"utf8",flush:!0})});this.appendQueues.set(i,o);try{await o}finally{this.appendQueues.get(i)===o&&this.appendQueues.delete(i)}}async writeTextExclusive(t,n){let i=this.resolve(t);await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i),await(0,Oe.writeFile)(i,n,{encoding:"utf8",flag:"wx",flush:!0})}async writeTextAtomicExclusive(t,n){let i=this.resolve(t),r=`${i}.${Ds(6)}.tmp`;await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i);try{await(0,Oe.writeFile)(r,n,{encoding:"utf8",flag:"wx",flush:!0}),await(0,Oe.link)(r,i)}finally{await(0,Oe.rm)(r,{force:!0})}}async removeFile(t){let n=this.resolve(t);await this.assertPhysicalContainment(n),await(0,Oe.rm)(n,{force:!0})}async removeFileIfContentMatches(t,n){let i=`${t}.${Ds(16)}.compare-delete`;try{await this.moveFileAtomic(t,i)}catch(s){if(Yi(s)&&s.code==="ENOENT")return!1;throw s}if(await this.readText(i)===n)return await this.removeFile(i),!0;let o=this.resolve(i),a=this.resolve(t);try{await(0,Oe.link)(o,a),await this.removeFile(i)}catch(s){throw Yi(s)&&s.code==="EEXIST"?new Gn(`Conditional delete observed a replacement; captured file retained at ${i}`):s}return!1}async collectCompareDeleteTombstones(t){let n=[];for(let i of await this.listFiles(t)){let r=/^(.*)\.[A-Z0-9]{16}\.compare-delete$/.exec(i);if(r===null)continue;let o=r[1];o!==void 0&&await this.exists(o)&&(await this.removeFile(i),n.push(i))}return n}async moveFileAtomic(t,n){let i=this.resolve(t),r=this.resolve(n);await this.assertPhysicalContainment(i),await this.assertPhysicalContainment(r),await(0,Oe.mkdir)((0,Fe.dirname)(r),{recursive:!0}),await this.assertPhysicalContainment(r),await(0,Oe.rename)(i,r)}async assertPhysicalContainment(t){let n=await(0,Oe.realpath)(this.root),i=t,r=null;for(;;)try{let o=await(0,Oe.realpath)(i),a=(0,Fe.relative)(n,o);if(a===".."||a.startsWith(`..${Fe.sep}`)||(0,Fe.isAbsolute)(a))throw await(0,Oe.lstat)(i),new Gn(`Physical path escapes workspace root: ${t}`);return}catch(o){if(!Yi(o)||o.code!=="ENOENT")throw o;if(r=o,i===this.root)throw new Gn(`Cannot resolve workspace root for: ${t}`,{cause:r});let a=(0,Fe.dirname)(i);if(a===i)throw new Gn(`Cannot resolve workspace ancestor for: ${t}`,{cause:r});i=a}}};function kx(e){return Fe.posix.isAbsolute(e)||Fe.win32.isAbsolute(e)||/^[A-Za-z]:/.test(e)}function Ox(e){return e.split(/[\\/]+/).some(t=>t==="..")}function Yi(e){return e instanceof Error&&"code"in e}async function wx(e,t){if(process.platform!=="win32"){await(0,Oe.rename)(e,t);return}for(let n=0;n<5;n+=1)try{await(0,Oe.rm)(t,{force:!0}),await(0,Oe.rename)(e,t);return}catch(i){if(!Ax(i)||n===4)throw i;await Tx(25*(n+1))}}function Ax(e){return Yi(e)&&["EPERM","EBUSY","EACCES"].includes(e.code??"")}async function Tx(e){await new Promise(t=>setTimeout(t,e))}var xy=require("node:child_process");var Py=require("node:util"),vz=(0,Py.promisify)(xy.execFile);var st=ut(pt(),1);var Dy=ut(Ru(),1);var kz=st.z.object({id:st.z.string().regex(/^RULE-[A-Z0-9-]+$/),load:st.z.enum(["always","auto","file_match","manual"]),globs:st.z.array(st.z.string().min(1)).default([]),priority:st.z.enum(["critical","high","medium","low"]),max_context_tokens:st.z.number().int().positive(),requires:st.z.array(st.z.string().regex(/^RULE-[A-Z0-9-]+$/))}).strict().superRefine((e,t)=>{e.load==="file_match"&&e.globs.length===0&&t.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}),Oz=st.z.object({schema_version:st.z.literal(2),id:st.z.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:st.z.string().regex(/^[a-z][a-z0-9-]*$/),title:st.z.string().min(1),status:st.z.enum(["proposed","active","deprecated"]),version:st.z.number().int().positive(),source_change:st.z.string().min(1).nullable(),source_release:st.z.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((e,t)=>{e.source_change===null&&e.source_release===void 0&&t.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"}),e.source_change!==null&&e.source_release!==void 0&&t.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})});var ge=ut(pt(),1);var Nx=["codex_host_native","provider_subprocess"],Ix=["frontier","balanced","fast_scan","review"],Rx=["subagents","worktrees","sandbox","approvals","skills","mcp"];var Tz=ge.z.enum(Nx),Nz=ge.z.enum(Ix),zy=ge.z.enum(Rx),$x=ge.z.array(zy).min(1).refine(e=>new Set(e).size===e.length,{message:"native_surfaces must be unique"}),Cx=ge.z.object({locator:ge.z.string().min(1),candidate_sha256:ge.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),Lx=ge.z.object({capability_id:ge.z.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:ge.z.literal("implemented"),previous_states:ge.z.tuple([ge.z.literal("declared")]),evidence:ge.z.array(Cx).length(0)}).strict(),Mx=ge.z.object({tier:ge.z.literal(1),enabled:ge.z.literal(!0),optional:ge.z.literal(!1),invokes_provider_subprocess:ge.z.literal(!1),authority:ge.z.literal("host"),native_surfaces:$x,capability_bindings:ge.z.record(zy,Lx)}).strict().superRefine((e,t)=>{let n=Object.keys(e.capability_bindings).sort(),i=[...e.native_surfaces].sort();JSON.stringify(n)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}),Ux=ge.z.object({tier:ge.z.union([ge.z.literal(2),ge.z.literal(3)]),enabled:ge.z.boolean(),optional:ge.z.literal(!0),invokes_provider_subprocess:ge.z.literal(!0),authority:ge.z.literal("framework"),native_surfaces:ge.z.array(ge.z.never()).length(0),opt_in:ge.z.object({required:ge.z.literal(!0),allowed_sources:ge.z.array(ge.z.enum(["project_config","human_decision"])).min(1).refine(e=>new Set(e).size===e.length,{message:"opt-in sources must be unique"})}).strict()}).strict(),js=ge.z.object({selection:ge.z.enum(["host_available","inherit_host"]),reasoning:ge.z.enum(["low","medium","high"]),intent:ge.z.string().min(1)}).strict(),Iz=ge.z.object({schema_version:ge.z.literal(1),host_id:ge.z.literal("codex"),candidate_sha256:ge.z.null(),default_mode:ge.z.literal("codex_host_native"),modes:ge.z.object({codex_host_native:Mx,provider_subprocess:Ux}).strict(),model_classes:ge.z.object({frontier:js,balanced:js,fast_scan:js,review:js}).strict()}).strict(),Rz=ge.z.object({enabled:ge.z.literal(!0),source:ge.z.enum(["project_config","human_decision"]),provenance:ge.z.object({reference:ge.z.string().min(1),recorded_at:ge.z.string().datetime({offset:!0})}).strict()}).strict();var We=ut(pt(),1);var xx=We.z.object({schema_version:We.z.literal(1),project:We.z.object({id:We.z.string().min(1),name:We.z.string().min(1),timezone:We.z.string().min(1).default("America/Sao_Paulo")}),framework:We.z.object({version:We.z.string().min(1)}),layout:We.z.object({version:We.z.literal(1),managed_namespace:We.z.string().min(1).default(".agents/managed"),project_namespace:We.z.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:We.z.object({id:We.z.string().min(1).default("zaip-aios-stack")}),paths:We.z.object({specs:We.z.string().min(1).default(".agents/specs"),changes:We.z.string().min(1).default(".agents/changes"),tasks:We.z.string().min(1).default(".agents/tasks"),decisions:We.z.string().min(1).default(".agents/decisions"),runs:We.z.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:We.z.array(We.z.enum(["codex","claude"])).default(["codex","claude"])}).strict(),xz=We.z.toJSONSchema(xx);var Fy="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)",Hz=new RegExp(`^${Fy}$`,"i");var Jz=new RegExp(String.raw`\b${Fy}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi");var Mu=class{#e;constructor(t){let n=new Map;for(let i of t){let r=n.get(i.from)??new Set;r.add(i.to),n.set(i.from,r)}this.#e=n}canTransition(t,n){return this.#e.get(t)?.has(n)??!1}assertTransition(t,n){if(!this.canTransition(t,n))throw new Error(`Invalid state transition: ${t} -> ${n}`)}nextStates(t){return[...this.#e.get(t)??[]]}};var Xz=new Mu([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}]);var Y=ut(pt(),1);var Uu=e=>Math.round(e*1e6)/1e6;function zs(e,t,n){let i=`${e} ${t} ${n}`.toLowerCase();return i.includes("claude")||i.includes("anthropic")?"anthropic":i.includes("gpt")||i.includes("openai")||i.includes("codex")?"openai":null}function Zy(e){let t=Math.max(e.inputTokens-e.cachedInputTokens,0),n=Uu(t/1e6*e.inputRate*e.inputMultiplier),i=Uu(e.cachedInputTokens/1e6*(e.cachedInputRate??0)*e.inputMultiplier),r=Uu(e.outputTokens/1e6*e.outputRate*e.outputMultiplier);return{inputUsd:n,cachedInputUsd:i,outputUsd:r,reasoningUsd:0}}var Pe=ut(pt(),1),ti=Pe.z.number().finite().nonnegative().nullable(),Zx=Pe.z.object({task_id:Pe.z.string().min(1),completed:Pe.z.boolean(),completed_at:Pe.z.string().min(1).nullable(),attempt:Pe.z.number().int().nonnegative().nullable(),attempt_id:Pe.z.string().min(1).nullable().optional(),equivalence_key:Pe.z.string().min(1).nullable().optional(),model:Pe.z.string().min(1).nullable(),reasoning_effort:Pe.z.enum(["low","medium","high","xhigh"]).nullable(),baseline_task_id:Pe.z.string().min(1).nullable(),baseline_attempt_id:Pe.z.string().min(1).nullable().optional(),baseline_equivalence_id:Pe.z.string().min(1).nullable(),observed_cost_usd:ti,baseline_observed_cost_usd:ti,quality_score:ti,quality_floor:ti,rework_count:Pe.z.number().int().nonnegative().nullable(),billed_amount:ti.optional(),billed_currency:Pe.z.string().min(1).nullable().optional(),billed_provenance:Pe.z.enum(["observed","inferred","unavailable"]).nullable().optional(),billed_source_id:Pe.z.string().min(1).nullable().optional(),billed_at:Pe.z.string().min(1).nullable().optional(),baseline_billed_amount:ti.optional(),baseline_billed_currency:Pe.z.string().min(1).nullable().optional(),baseline_billed_provenance:Pe.z.enum(["observed","inferred","unavailable"]).nullable().optional(),baseline_billed_source_id:Pe.z.string().min(1).nullable().optional(),baseline_billed_at:Pe.z.string().min(1).nullable().optional()}).strict(),F1=Pe.z.object({timezone:Pe.z.string().min(1),interval:Pe.z.object({start:Pe.z.string().min(1),end:Pe.z.string().min(1)}).strict(),equivalence_key:Pe.z.string().min(1).nullable().optional(),tasks:Pe.z.array(Zx)}).strict();var qy=require("node:crypto");function xu(e){let t=qx(e.manifest),n=t.source_streams.find(i=>i.run_id===e.run_id);if(n===void 0)return null;if(n.path!==e.path||Vy(e.content)!==n.content_sha256)throw new Error(`Historical developer attribution source mismatch: ${e.run_id}`);return t.assignment}function Vy(e){return(0,qy.createHash)("sha256").update(e).digest("hex")}function qx(e){if(typeof e!="object"||e===null)throw new Error("Invalid historical developer attribution manifest");let t=e,{manifest_hash:n,...i}=t;if(t.schema_version!==1||t.kind!=="historical_developer_attribution"||t.assignment?.attribution_source!=="human_assigned"||!Array.isArray(t.source_streams)||Vy(JSON.stringify(i))!==n)throw new Error("Invalid historical developer attribution manifest");return t}var Tr=Y.z.string().datetime({offset:!0}).or(Y.z.string().datetime()),Bx=Y.z.object({id:Y.z.string().min(1),provider:Y.z.enum(["openai","anthropic"]),aliases:Y.z.array(Y.z.string().min(1)).default([]),input_per_million_usd:Y.z.number().nonnegative(),cached_input_per_million_usd:Y.z.number().nonnegative().nullable().default(null),output_per_million_usd:Y.z.number().nonnegative(),reasoning_per_million_usd:Y.z.number().nonnegative().nullable().default(null),priority_input_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_cached_input_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_output_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_reasoning_per_million_usd:Y.z.number().nonnegative().nullable().optional(),reasoning_billed_separately:Y.z.boolean().default(!1),long_context_threshold_tokens:Y.z.number().int().positive().nullable().default(null),long_context_input_multiplier:Y.z.number().positive().default(1),long_context_output_multiplier:Y.z.number().positive().default(1),source_label:Y.z.string().min(1),source_url:Y.z.string().url(),notes:Y.z.array(Y.z.string()).default([])}).strict(),By=Y.z.object({schema_version:Y.z.literal(1),updated_at:Tr,source:Y.z.string().min(1),disclaimer:Y.z.string().min(1),models:Y.z.array(Bx)}).strict(),Hy=Y.z.object({schema_version:Y.z.literal(1),base:Y.z.literal("USD"),quote:Y.z.literal("BRL"),rate:Y.z.number().positive(),as_of:Tr,source_label:Y.z.string().min(1),source_url:Y.z.string().url()}).strict(),Jy=Y.z.object({input:Y.z.number().int().nonnegative().nullable(),cached_input:Y.z.number().int().nonnegative().nullable().default(null),output:Y.z.number().int().nonnegative().nullable(),reasoning:Y.z.number().int().nonnegative().nullable(),total:Y.z.number().int().nonnegative().nullable().default(null),source:Y.z.preprocess(e=>e==="client"?"provider_reported":e,Y.z.enum(["provider_reported","estimated","unavailable"]))}).strict(),Ky=Y.z.object({estimated_usd:Y.z.number().nonnegative().nullable(),estimated_brl:Y.z.number().nonnegative().nullable(),fx_rate:Y.z.number().positive().nullable(),pricing_model:Y.z.string().nullable(),pricing_source:Y.z.string().nullable(),input_usd:Y.z.number().nonnegative().nullable().default(null),cached_input_usd:Y.z.number().nonnegative().nullable().default(null),output_usd:Y.z.number().nonnegative().nullable().default(null),reasoning_usd:Y.z.number().nonnegative().nullable().default(null)}).strict(),Hx=Y.z.object({cycle_count:Y.z.number().int().nonnegative().nullable(),source:Y.z.enum(["repository","local-codex","manual","unavailable"]),segment_key:Y.z.string().nullable()}).strict(),zx=Y.z.object({schema_version:Y.z.literal(1),recorded_at:Tr,run_id:Y.z.string().startsWith("RUN-"),task_id:Y.z.string().startsWith("TASK-"),spec_id:Y.z.string().nullable(),change_id:Y.z.string().nullable(),task_title:Y.z.string().nullable(),task_status:Y.z.string().nullable(),client:Y.z.string().min(1),agent:Y.z.string().min(1),provider:Y.z.enum(["openai","anthropic"]).nullable(),model:Y.z.string().min(1),status:Y.z.enum(["running","completed","failed"]),started_at:Tr,finished_at:Tr.nullable(),duration_ms:Y.z.number().int().nonnegative().nullable(),token_usage:Jy,estimated_cost:Ky,telemetry:Hx,source_segment_key:Y.z.string().nullable()}).strict(),Fx=Y.z.object({schema_version:Y.z.literal(1),recorded_at:Tr,run_id:Y.z.string().startsWith("RUN-"),task_id:Y.z.string().startsWith("TASK-"),cycle_index:Y.z.number().int().nonnegative(),provider:Y.z.enum(["openai","anthropic"]).nullable(),model:Y.z.string().min(1),timestamp:Tr,source:Y.z.enum(["local-codex","manual"]),source_segment_key:Y.z.string().nullable(),token_usage:Jy,estimated_cost:Ky}).strict();function Wy(e){return Math.round(e*1e6)/1e6}function Fs(e){let t=e.provider??zs(e.model,"",""),n=e.model.toLowerCase(),i=V=>{let ce=V.toLowerCase();if(n===ce)return!0;let Se=n.slice(ce.length);return Se.startsWith("@")||Se.startsWith(":")||Se.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(Se)},r=e.catalog.models.find(V=>i(V.id)||V.aliases.some(ce=>i(ce)));if(!r||t!==null&&r.provider!==t)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:null,pricing_source:null,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let o=e.usage.cached_input,a=e.usage.input,s=e.usage.output;if(a===null||o===null||s===null)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let l=e.usage.reasoning??0,c=r.long_context_threshold_tokens!==null&&(e.usage.input??0)>r.long_context_threshold_tokens,u=c?r.long_context_input_multiplier:1,d=c?r.long_context_output_multiplier:1,p=e.serviceTier==="priority"||e.serviceTier==="fast";if(p&&c)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let f=p?r.priority_input_per_million_usd??null:r.input_per_million_usd,S=p?r.priority_output_per_million_usd??null:r.output_per_million_usd;if(f===null||S===null)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let{inputUsd:h,cachedInputUsd:v,outputUsd:E,reasoningUsd:U}=Zy({inputTokens:a,cachedInputTokens:o,outputTokens:s,reasoningTokens:l,inputRate:f,cachedInputRate:p?r.priority_cached_input_per_million_usd??null:r.cached_input_per_million_usd,outputRate:S,reasoningRate:p?r.priority_reasoning_per_million_usd??null:r.reasoning_per_million_usd,inputMultiplier:u,outputMultiplier:d}),F=Wy(h+v+E+U),q=e.fxRate===null||e.fxRate===void 0?null:Wy(F*e.fxRate.rate);return{estimated_usd:F,estimated_brl:q,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:h,cached_input_usd:v,output_usd:E,reasoning_usd:U}}var $e=ut(pt(),1);function zt(e,t){let n=[...new Set(t)].sort((a,s)=>a.localeCompare(s)),i=new Map;if(n.length===0)return i;if(e===null||!Number.isFinite(e)){for(let a of n)i.set(a,null);return i}if(Number.isInteger(e)){let a=Math.floor(e/n.length),s=e-a*n.length;return n.forEach((l,c)=>{i.set(l,a+(c===n.length-1?s:0))}),i}let r=e/n.length,o=0;return n.forEach((a,s)=>{let l=s===n.length-1?e-o:r;i.set(a,l),o+=l}),i}var Xy=".agents/records/lifecycle/views",MF=`${Xy}/manifest.json`;var Nr=".agents/records/lifecycle",aZ=`${Nr}/manifest.json`,sZ=`${Nr}/entity-snapshot.json`,cZ=`${Nr}/entity-state.json`,lZ=`${Nr}/indexes`;var uZ=`${Nr}/summary.json`,dZ=`${Nr}/overview.json`,_Z=`${Nr}/active-work.json`;var Qy=$e.z.enum(["prd","spec","change","task","execution","run","decision","validation","evidence"]),pZ=Qy.options,Kx=$e.z.enum(["parent","child","references","evidence","requirement"]),Gx=$e.z.enum(["explicit","derived"]),Xx=$e.z.object({target_id:$e.z.string().min(1),type:Kx,direction:$e.z.enum(["outbound","inbound"]),provenance:Gx,source_locator:$e.z.string().min(1).nullable().default(null)}).strict(),Yx=$e.z.object({input_tokens:$e.z.number().int().nonnegative().nullable().default(null),output_tokens:$e.z.number().int().nonnegative().nullable().default(null),cached_input_tokens:$e.z.number().int().nonnegative().nullable().default(null),total_tokens:$e.z.number().int().nonnegative().nullable().default(null),cost:$e.z.number().nonnegative().nullable().default(null),currency:$e.z.string().min(1).nullable().default(null)}).strict(),Qx=$e.z.object({kind:Qy,id:$e.z.string().min(1),title:$e.z.string().min(1).nullable().default(null),status:$e.z.string().min(1).nullable().default(null),risk:$e.z.string().min(1).nullable().default(null),priority:$e.z.string().min(1).nullable().default(null),updated_at:$e.z.string().datetime({offset:!0}),relations:$e.z.array($e.z.string().min(1)).default([]),relation_edges:$e.z.array(Xx).optional(),usage:Yx.nullable().default(null),data:$e.z.record($e.z.string(),$e.z.unknown()).nullable().default(null)}).strict(),fZ=$e.z.object({schema_version:$e.z.literal(1),event_id:$e.z.string().min(1),occurred_at:$e.z.string().datetime({offset:!0}),operation:$e.z.enum(["upsert","remove"]),entity:Qx}).strict();var fe=ut(pt(),1);var $t=ut(pt(),1);var k=ut(pt(),1);var It=ut(pt(),1),eP=It.z.string().datetime({offset:!0}).or(It.z.string().datetime()),eh=It.z.object({schema_version:It.z.literal(2),event_id:It.z.string().min(1).max(200),run_id:It.z.string().startsWith("RUN-"),sequence:It.z.number().int().positive(),occurred_at:eP,type:It.z.literal("run.attribution.recovered"),phase:It.z.literal("execution"),execution_id:It.z.string().startsWith("EXEC-"),task_id:It.z.string().startsWith("TASK-"),change_id:It.z.string().startsWith("CHG-")}).strict();function th(e,t){return e.entrypoint==="task"&&e.execution_id!==null&&e.task_id!==null&&e.change_id===null&&t.execution_id===e.execution_id&&t.task_id===e.task_id}function Pu(e,t){return e.coverage==="partial"&&t.coverage==="complete"&&e.call_id===t.call_id&&e.agent_invocation_id===t.agent_invocation_id&&e.source_call_key===t.source_call_key&&JSON.stringify(e.tokens)===JSON.stringify(t.tokens)}function Du(e,t,n){return e.type==="usage.recorded"&&e.retrospective_correction===!0&&e.activity_kind==="retrospective_observed_timing"&&e.supersedes_event_id===null&&e.phase===t.phase&&e.source_segment_key!==null&&e.source_started_at!==void 0&&e.source_finished_at!==void 0&&Date.parse(e.source_finished_at)>=Date.parse(e.source_started_at)&&e.source_occurred_at===e.source_finished_at&&e.tokens.source==="unavailable"&&[e.tokens.input,e.tokens.cached_input,e.tokens.output,e.tokens.reasoning,e.tokens.total,e.cost.usd,e.cost.brl,e.cost.fx_rate,e.provider,e.model].every(r=>r===null)?!0:e.type==="usage.recorded"&&e.retrospective_correction===!0&&e.activity_kind==="retrospective_local_remeasurement"&&e.supersedes_event_id!==null&&n.has(e.supersedes_event_id)&&e.phase===t.phase}function Zs(e,t){let n={conversation:0,planning:1,execution:2};if(n[t]<n[e])throw new Error(`Run V2 phase cannot move backward from ${e} to ${t}`)}var Xe=ut(pt(),1),nh=Xe.z.string().datetime({offset:!0}).or(Xe.z.string().datetime()),nP=Xe.z.string().regex(/^DEC-(?:HUMAN|AI)-/),rP=Xe.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation","rollback"]),kZ=Xe.z.object({schema_version:Xe.z.literal(2),id:nP,title:Xe.z.string().min(1),scope_type:Xe.z.enum(["change","execution"]),scope_id:Xe.z.string().min(1),origin:Xe.z.enum(["human","agent"]),category:rP,context:Xe.z.string().min(1),decision:Xe.z.string().min(1),reason:Xe.z.string().min(1),alternatives:Xe.z.array(Xe.z.string().min(1)),consequences:Xe.z.array(Xe.z.string().min(1)),reversible:Xe.z.boolean(),rollback:Xe.z.string().min(1),confidence:Xe.z.number().min(0).max(1).nullable(),created_at:nh,confirmed_at:nh.nullable()}).strict().superRefine((e,t)=>{let n=e.scope_type==="change"?"CHG-":"EXEC-";e.scope_id.startsWith(n)||t.addIssue({code:"custom",path:["scope_id"],message:`${e.scope_type} decision requires ${n} scope_id`});let i=e.origin==="human"?"DEC-HUMAN-":"DEC-AI-";e.id.startsWith(i)||t.addIssue({code:"custom",path:["id"],message:`${e.origin} decision requires ${i} id`}),e.origin==="human"&&e.confidence!==null&&t.addIssue({code:"custom",path:["confidence"],message:"Human decisions do not use agent confidence"}),e.origin==="agent"&&e.confidence===null&&t.addIssue({code:"custom",path:["confidence"],message:"Agent decisions require confidence"}),e.origin==="human"&&e.confirmed_at===null&&t.addIssue({code:"custom",path:["confirmed_at"],message:"Human decisions require explicit confirmation provenance"})});var Rt=k.z.string().datetime({offset:!0}).or(k.z.string().datetime()),qs=k.z.enum(["conversation","planning","execution"]),Vs=k.z.string().startsWith("RUN-"),aP=k.z.string().startsWith("CONV-"),rh=k.z.string().startsWith("EXEC-").nullable(),ih=k.z.string().startsWith("TASK-").nullable(),oh=k.z.string().startsWith("SPEC-").nullable(),ah=k.z.string().startsWith("PRD-").nullable(),sh=k.z.string().startsWith("CHG-").nullable(),zu=Vs.nullable(),Ir=k.z.string().regex(/^(?:AINV|INV)-/).max(200),ch=k.z.string().startsWith("MCALL-").max(200),MZ=k.z.enum(["intake","orchestrator","subagent"]),sP=k.z.enum(["intake","orchestrator","subagent","owner","contributor"]),lh=k.z.enum(["intake","orchestration","execution","review","audit","finalization"]),Fu=k.z.enum(["low","medium","high","xhigh"]),eo=k.z.object({schema_version:k.z.literal(1),provider:k.z.literal("github"),account_id:k.z.string().min(1).max(100),login_snapshot:k.z.string().min(1).max(100),attribution_source:k.z.enum(["verified_local_account","last_verified_local_account","cached_fallback","human_assigned"]),verified_at:Rt.nullable(),expires_at:Rt.nullable().optional(),last_verified_at:Rt.nullable().optional()}).strict();var uh=k.z.enum(["orchestrator","delegated"]);var Zu=k.z.object({input:k.z.number().int().nonnegative().nullable(),cached_input:k.z.number().int().nonnegative().nullable(),output:k.z.number().int().nonnegative().nullable(),reasoning:k.z.number().int().nonnegative().nullable(),total:k.z.number().int().nonnegative().nullable(),source:k.z.enum(["provider_reported","estimated","unavailable"])}).strict().superRefine((e,t)=>{e.input!==null&&e.cached_input!==null&&e.cached_input>e.input&&t.addIssue({code:"custom",path:["cached_input"],message:"cached_input cannot exceed input"}),e.total!==null&&e.input!==null&&e.output!==null&&e.total<e.input+e.output&&t.addIssue({code:"custom",path:["total"],message:"total cannot be lower than input + output"})}),dh=k.z.object({usd:k.z.number().nonnegative().nullable(),brl:k.z.number().nonnegative().nullable(),fx_rate:k.z.number().positive().nullable().optional()}).strict(),Rr={schema_version:k.z.literal(2),event_id:k.z.string().min(1).max(200),run_id:Vs,sequence:k.z.number().int().positive(),occurred_at:Rt},cP=k.z.object({intent:k.z.enum(["conversation","continue","refine","rework","new_work"]),classification_source:k.z.enum(["agent","explicit","fallback"]),confidence:k.z.number().min(0).max(1),reason_codes:k.z.array(k.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(12)}).strict(),_h=k.z.object({...Rr,type:k.z.literal("run.started"),attribution_status:k.z.enum(["attributed","legacy_unattributed"]),developer_identity:eo.nullable().optional(),phase:qs,run_role:sP.optional(),run_purpose:lh.optional(),requires_finalizer:k.z.boolean().optional(),execution_kind:k.z.enum(["interaction","delivery"]).optional(),execution_eligibility:k.z.array(k.z.enum(["interaction","delivery"])).optional(),entrypoint:k.z.enum(["conversation","task","spec","prd"]),work_type:k.z.enum(["new","rework"]),storage_mode:k.z.enum(["tracked_sanitized","local_only"]),client:k.z.string().min(1).max(100),agent:k.z.string().min(1).max(100),agent_name:k.z.string().min(1).max(100).nullable().optional(),agent_identity_warning:k.z.object({code:k.z.literal("deprecated-agent-identity"),kind:k.z.enum(["id","codex_name","codex_task_name"]),requested:k.z.string().min(1),canonical_id:k.z.string().min(1),deprecated_at:k.z.iso.date(),remove_after:k.z.iso.date()}).strict().optional(),provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200),reasoning_effort:Fu.nullable().optional(),client_thread_id:k.z.string().min(1).max(200).nullable().optional(),client_turn_id:k.z.string().min(1).max(200).nullable().optional(),conversation_id:aP,execution_id:rh,task_id:ih,spec_id:oh,prd_id:ah,change_id:sh,parent_run_id:zu,continuation_of_run_id:zu,retry_of_run_id:zu,agent_invocation_id:Ir.optional(),root_agent_invocation_id:Ir.optional(),parent_agent_invocation_id:Ir.nullable().optional(),invocation_kind:uh.optional(),delegation_depth:k.z.number().int().nonnegative().optional(),intake:cP.nullable().optional()}).strict().superRefine((e,t)=>{e.phase==="execution"&&e.execution_id===null&&e.attribution_status!=="legacy_unattributed"&&t.addIssue({code:"custom",path:["execution_id"],message:"Execution phase requires execution_id"}),{conversation:e.conversation_id,task:e.task_id,spec:e.spec_id,prd:e.prd_id}[e.entrypoint]===null&&t.addIssue({code:"custom",path:[`${e.entrypoint}_id`],message:`${e.entrypoint} entrypoint requires its scope id`}),e.run_role==="orchestrator"&&e.parent_run_id!==null&&t.addIssue({code:"custom",path:["parent_run_id"],message:"orchestrator Run cannot have parent_run_id"}),e.run_role==="subagent"&&e.parent_run_id===null&&t.addIssue({code:"custom",path:["parent_run_id"],message:"subagent Sub-Run requires parent_run_id"});let i=e.agent_invocation_id!==void 0;i&&(e.root_agent_invocation_id===void 0||e.parent_agent_invocation_id===void 0||e.invocation_kind===void 0||e.delegation_depth===void 0)&&t.addIssue({code:"custom",path:["agent_invocation_id"],message:"Agent Invocation identity must be complete when present"}),i&&e.invocation_kind==="orchestrator"&&(e.parent_agent_invocation_id!==null||e.root_agent_invocation_id!==e.agent_invocation_id||e.delegation_depth!==0)&&t.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator Agent Invocation must be its root at depth zero"}),i&&e.invocation_kind==="delegated"&&(e.parent_agent_invocation_id===null||e.delegation_depth===0)&&t.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated Agent Invocation requires a parent and positive depth"});for(let[r,o]of[["parent_run_id",e.parent_run_id],["continuation_of_run_id",e.continuation_of_run_id],["retry_of_run_id",e.retry_of_run_id]])o===e.run_id&&t.addIssue({code:"custom",path:[r],message:`${r} cannot reference itself`})}),ph=k.z.object({...Rr,type:k.z.literal("usage.recorded"),phase:qs,activity_kind:k.z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),classification_source:k.z.enum(["explicit","current_context","default","legacy_inferred"]),tokens:Zu,cost:dh,provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),source_segment_key:k.z.string().min(1).max(500).nullable(),attributed_spec_id:k.z.string().min(1).max(200).nullable().optional(),model_call_id:ch.nullable().optional(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict().optional(),supersedes_event_id:k.z.string().min(1).max(200).nullable(),retrospective_correction:k.z.literal(!0).optional(),source_occurred_at:Rt.optional(),source_started_at:Rt.optional(),source_finished_at:Rt.optional(),duration_ms:k.z.number().int().nonnegative().nullable().optional(),duration_provenance:k.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().optional(),context_stats:k.z.object({initial_pack_tokens:k.z.number().int().nonnegative().nullable(),tool_output_tokens:k.z.number().int().nonnegative().nullable(),files_opened:k.z.number().int().nonnegative().nullable(),snippets_opened:k.z.number().int().nonnegative().nullable()}).strict().optional()}).strict(),fh=k.z.object({...Rr,type:k.z.literal("model.call.observed"),call_id:ch,agent_invocation_id:Ir,coverage:k.z.enum(["complete","partial","unavailable"]),tokens:Zu,cost:dh,provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),source_call_key:k.z.string().min(1).max(500).nullable(),source_occurred_at:Rt.optional(),source_started_at:Rt.optional(),source_finished_at:Rt.optional(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict().optional()}).strict(),mh=k.z.object({schema_version:k.z.literal(1),run_id:Vs,execution_id:rh.nullable().default(null),task_id:ih.nullable().default(null),spec_id:oh.nullable().default(null),prd_id:ah.nullable().default(null),change_id:sh.nullable().default(null),developer_identity:eo.nullable().optional(),zaip_agent:k.z.string().min(1).max(100).nullable().default(null),phase:qs.nullable().default(null),purpose:lh.nullable().default(null),agent_invocation_id:Ir,root_agent_invocation_id:Ir,parent_agent_invocation_id:Ir.nullable(),invocation_kind:uh,delegation_depth:k.z.number().int().nonnegative(),client:k.z.enum(["codex","codex-desktop","codex-subagent"]),thread_id:k.z.string().min(1).max(200).nullable(),turn_id:k.z.string().min(1).max(200).nullable(),agent_path:k.z.string().min(1).max(500).nullable()}).strict().superRefine((e,t)=>{e.invocation_kind==="orchestrator"&&(e.parent_agent_invocation_id!==null||e.root_agent_invocation_id!==e.agent_invocation_id||e.delegation_depth!==0)&&t.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator telemetry correlation must be its root at depth zero"}),e.invocation_kind==="delegated"&&(e.parent_agent_invocation_id===null||e.delegation_depth===0)&&t.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated telemetry correlation requires a parent and positive depth"}),e.client==="codex-subagent"&&(e.thread_id!==null||e.agent_path===null&&e.turn_id===null)&&t.addIssue({code:"custom",path:["agent_path"],message:"Codex subagent telemetry requires agent_path or turn_id and no root thread_id"}),e.client!=="codex-subagent"&&e.thread_id===null&&e.turn_id===null&&t.addIssue({code:"custom",path:["thread_id"],message:"Codex root telemetry requires thread_id or turn_id"})}),gh=k.z.object({correlation:mh,event_kind:k.z.enum(["response","usage","terminal","error"]),source:k.z.enum(["codex_app_server","codex_session_fallback","unavailable"]),source_event_key:k.z.string().min(1).max(500),source_method:k.z.enum(["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"]).optional(),stream_boundary:k.z.enum(["item_completed","response_completed","usage_updated","error","turn_completed"]).optional(),source_occurred_at:Rt.nullable(),captured_at:Rt,coverage:k.z.enum(["complete","partial","unavailable"]),tokens:Zu.nullable(),provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict(),status:k.z.enum(["completed","failed","cancelled"]).nullable(),will_retry:k.z.boolean().nullable().optional(),latency_ms:k.z.number().int().nonnegative().nullable(),historical_cost:k.z.object({estimated_usd:k.z.number().nonnegative().nullable(),estimated_brl:k.z.number().nonnegative().nullable(),fx_rate:k.z.number().positive().nullable(),pricing_model:k.z.string().nullable(),pricing_source:k.z.string().nullable(),input_usd:k.z.number().nonnegative().nullable(),cached_input_usd:k.z.number().nonnegative().nullable(),output_usd:k.z.number().nonnegative().nullable(),reasoning_usd:k.z.number().nonnegative().nullable()}).strict().nullable().optional(),context_stats:k.z.object({initial_pack_tokens:k.z.number().int().nonnegative().nullable(),tool_output_tokens:k.z.number().int().nonnegative().nullable(),files_opened:k.z.number().int().nonnegative().nullable(),snippets_opened:k.z.number().int().nonnegative().nullable()}).strict().nullable(),discarded_counts:k.z.object({prompt:k.z.number().int().nonnegative(),response_text:k.z.number().int().nonnegative(),reasoning:k.z.number().int().nonnegative(),secrets:k.z.number().int().nonnegative()}).strict()}).strict().superRefine((e,t)=>{e.source==="codex_session_fallback"&&e.coverage==="complete"&&t.addIssue({code:"custom",path:["coverage"],message:"Codex session fallback coverage must be partial or unavailable"}),e.source==="unavailable"&&e.coverage!=="unavailable"&&t.addIssue({code:"custom",path:["coverage"],message:"Unavailable source requires unavailable coverage"}),e.source==="unavailable"&&(e.provider!==null||e.model!==null||e.runtime.reasoning_effort!==null||e.runtime.service_tier!==null||e.latency_ms!==null)&&t.addIssue({code:"custom",path:["source"],message:"Unavailable source cannot contain effective runtime observations"}),e.coverage==="unavailable"&&e.tokens!==null&&e.tokens.source!=="unavailable"&&t.addIssue({code:"custom",path:["tokens","source"],message:"Unavailable coverage cannot contain observed tokens"}),e.event_kind==="terminal"&&e.status===null&&t.addIssue({code:"custom",path:["status"],message:"Terminal telemetry requires status"}),e.event_kind==="error"&&(e.will_retry===!0&&e.status!==null||e.will_retry!==!0&&e.status!=="failed")&&t.addIssue({code:"custom",path:["status"],message:"Retrying errors require null status; terminal errors require failed status"})}),lP=k.z.object({schema_version:k.z.literal(1),event_id:k.z.string().startsWith("CEVT-").max(200),checksum_sha256:k.z.string().regex(/^[a-f0-9]{64}$/),compaction:k.z.object({status:k.z.enum(["pending","compacted"]),compacted_at:Rt.nullable()}).strict(),event:gh}).strict(),yh=k.z.string().startsWith("INV-").max(200),hh=k.z.object({...Rr,type:k.z.literal("model.selection.recorded"),invocation_id:yh,requested:k.z.object({model:k.z.string().min(1).max(200),reasoning_effort:Fu.nullable(),velocity:k.z.literal("standard")}).strict(),selection:k.z.object({source:k.z.enum(["execution-override","task-override","auto-policy","project-default"]),policy_version:k.z.number().int().positive(),reasons:k.z.array(k.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(20)}).strict()}).strict(),vh=k.z.object({...Rr,type:k.z.literal("provider.invocation.finished"),invocation_id:yh,status:k.z.enum(["completed","failed","cancelled"]),effective:k.z.object({provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),reasoning_effort:Fu.nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict(),latency_ms:k.z.number().int().nonnegative().nullable()}).strict(),Sh=k.z.object({...Rr,type:k.z.literal("run.finished"),phase:qs,status:k.z.enum(["completed","failed","cancelled"]),duration_ms:k.z.number().int().nonnegative().nullable().default(null),duration_provenance:k.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().default(null)}).strict(),uP=k.z.object({...Rr,type:k.z.literal("run.finalization.decided"),finalizer_run_id:Vs,outcome:k.z.enum(["completed","blocked","failed","cancelled"]),summary:k.z.string().min(1).max(4e3),evidence_ids:k.z.array(k.z.string().min(1).max(200)).max(100),changed_files:k.z.array(k.z.string().min(1).max(500)).max(1e4).default([])}).strict(),to=k.z.discriminatedUnion("type",[_h,ph,fh,hh,vh,eh,uP,Sh]);var dP=$t.z.object({run_id:$t.z.string().startsWith("RUN-"),path:$t.z.string().startsWith(".agents/records/runs/"),content_sha256:$t.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),_P=$t.z.object({schema_version:$t.z.literal(1),manifest_id:$t.z.string().min(1),created_at:$t.z.string().datetime({offset:!0}),kind:$t.z.literal("historical_developer_attribution"),assignment:eo.extend({attribution_source:$t.z.literal("human_assigned")}),source_streams:$t.z.array(dP).min(1)}).strict().superRefine((e,t)=>{let n=new Set,i=new Set;for(let[r,o]of e.source_streams.entries())n.has(o.run_id)&&t.addIssue({code:"custom",path:["source_streams",r,"run_id"],message:"Duplicate historical Run"}),i.has(o.path)&&t.addIssue({code:"custom",path:["source_streams",r,"path"],message:"Duplicate historical Run path"}),n.add(o.run_id),i.add(o.path)}),FZ=_P.extend({manifest_hash:$t.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var VZ=1440*60*1e3;var HZ=64*1024;function Ah(e){let t=new Map,n=[];for(let i of e){if(i.source_segment_key===null){n.push(i);continue}let r=t.get(i.source_segment_key);if(r===void 0){t.set(i.source_segment_key,i),n.push(i);continue}if(!Th(i,r))throw new Error(`Divergent duplicate source segment: ${i.source_segment_key}`)}return n}function Th(e,t){return JSON.stringify(wh(e))===JSON.stringify(wh(t))}function wh(e){return{phase:e.phase,activity_kind:e.activity_kind,classification_source:e.classification_source,tokens:e.tokens,cost:e.cost,provider:e.provider,model:e.model,source_segment_key:e.source_segment_key,model_call_id:e.model_call_id??null}}function Nh(e,t){let n=[],i=null;for(let r of e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)){let o=JSON.parse(r),a=to.parse(Array.isArray(o)?t(o,i):o);i??=a.run_id,n.push(a)}return n}function Ih(e,t,n){if(e.model!=="unknown"&&n.requested.model!==e.model)throw new Error(`Agent Run model is immutable: expected ${e.model}, received ${n.requested.model}`);if(e.reasoning_effort!=null&&n.requested.reasoning_effort!==e.reasoning_effort)throw new Error(`Agent Run reasoning effort is immutable: expected ${e.reasoning_effort}, received ${n.requested.reasoning_effort}`);let i=t.find(r=>r.type==="model.selection.recorded");if(i!==void 0){if(JSON.stringify(i.requested)!==JSON.stringify(n.requested))throw new Error(`Agent Run calls must inherit one model configuration: ${e.run_id}`);if(JSON.stringify(i.selection)!==JSON.stringify(n.selection))throw new Error(`Agent Run calls must inherit one selection decision: ${e.run_id}`)}}function qu(e){return Nh(e,vP)}function Vu(e){let t=new Map;for(let v of e){let E=to.parse(v),U=t.get(E.event_id);if(U!==void 0){if(JSON.stringify(U)!==JSON.stringify(E))throw new Error(`Divergent duplicate Run V2 event: ${E.event_id}`);continue}t.set(E.event_id,E)}let n=[...t.values()].sort((v,E)=>v.sequence-E.sequence);if(n.length===0||n[0]?.type!=="run.started")throw new Error("Run V2 stream must start with run.started");let i=n[0],r=i.phase,o=null,a=null,s=null,l=new Map,c=new Map,u=new Map,d=new Map,p=new Map;for(let[v,E]of n.entries()){if(E.run_id!==i.run_id)throw new Error("Run V2 stream mixes run ids");if(E.sequence!==v+1)throw new Error("Run V2 sequence must be contiguous");let U=l.get(E.sequence);if(U!==void 0&&U!==E.event_id)throw new Error(`Run V2 sequence is duplicated: ${E.sequence}`);if(l.set(E.sequence,E.event_id),v>0&&E.type==="run.started")throw new Error("Run V2 has multiple starts");if(o!==null&&E.type!=="run.finalization.decided"&&!Du(E,o,c))throw new Error("Run V2 contains a non-retrospective record after run.finished");if(E.type==="usage.recorded"){if(Zs(r,E.phase),E.phase==="execution"&&i.execution_id===null&&i.attribution_status!=="legacy_unattributed")throw new Error("Execution phase requires execution_id");if(E.supersedes_event_id!==null&&!c.has(E.supersedes_event_id))throw new Error(`Superseded usage event must occur earlier: ${E.supersedes_event_id}`);c.set(E.event_id,E),r=E.phase}if(E.type==="run.attribution.recovered"){if(!th(i,E))throw new Error("Run attribution recovery does not match its immutable start header");if(s!==null)throw new Error("Run V2 has multiple attribution recoveries");Zs(r,E.phase),r=E.phase,s=E}if(E.type==="model.selection.recorded"){if(Ih(i,n.slice(0,v),{invocationId:E.invocation_id,requested:E.requested,selection:E.selection}),u.has(E.invocation_id))throw new Error(`Duplicate model selection for invocation: ${E.invocation_id}`);u.set(E.invocation_id,E)}if(E.type==="provider.invocation.finished"){if(!u.has(E.invocation_id))throw new Error(`Provider invocation requires earlier model selection: ${E.invocation_id}`);if(d.has(E.invocation_id))throw new Error(`Duplicate provider terminal for invocation: ${E.invocation_id}`);d.set(E.invocation_id,E)}if(E.type==="model.call.observed"){let F=p.get(E.call_id);if(F!==void 0&&JSON.stringify(F)!==JSON.stringify(E)&&!Pu(F,E))throw new Error(`Divergent duplicate Model Call: ${E.call_id}`);p.set(E.call_id,E)}if(E.type==="run.finalization.decided"){if(a!==null)throw new Error("Run V2 has multiple finalization decisions");a=E}if(E.type==="run.finished"){if(E.phase!==r)throw new Error("run.finished phase must match the latest phase");o=E}}let f=n.filter(v=>v.type==="usage.recorded"),S=new Set(f.map(v=>v.supersedes_event_id).filter(v=>v!==null)),h=Ah(f.filter(v=>!S.has(v.event_id)));return{run:s===null?i:{...i,phase:s.phase,execution_id:s.execution_id,task_id:s.task_id,change_id:s.change_id},status:o?.status??"running",finished:o,finalization_decision:a,attribution_recovery:s,records:n,usage_records:f,effective_usage_records:h,model_selection_records:[...u.values()],provider_invocation_records:[...d.values()],model_call_records:[...p.values()]}}function vP(e,t){if(e[0]!==3||t===null)throw new Error("Run delta requires transport version 3 and a preceding run.started header");if(e[1]==="f")return{schema_version:2,type:"run.finished",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],status:e[6]};if(e[1]==="a")return{schema_version:2,type:"run.attribution.recovered",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],execution_id:e[6],task_id:e[7],change_id:e[8]};if(e[1]==="d"&&Array.isArray(e[8]))return{schema_version:2,type:"run.finalization.decided",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],finalizer_run_id:e[5],outcome:e[6],summary:e[7],evidence_ids:e[8],changed_files:Array.isArray(e[9])?e[9]:[]};if(e[1]==="m"&&Array.isArray(e[6])&&Array.isArray(e[7])){let d=e[6],p=e[7];return{schema_version:2,type:"model.selection.recorded",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],invocation_id:e[5],requested:{model:d[0],reasoning_effort:d[1],velocity:d[2]},selection:{source:p[0],policy_version:p[1],reasons:p[2]}}}if(e[1]==="p"&&Array.isArray(e[7])){let d=e[7];return{schema_version:2,type:"provider.invocation.finished",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],invocation_id:e[5],status:e[6],effective:{provider:d[0],model:d[1],reasoning_effort:d[2],service_tier:d[3]},latency_ms:e[8]}}if(e[1]==="c"&&Array.isArray(e[8])&&Array.isArray(e[9])){let d=e[8],p=e[9],f=e[16];return{schema_version:2,type:"model.call.observed",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],call_id:e[5],agent_invocation_id:e[6],coverage:e[7],tokens:{input:d[0],cached_input:d[1],output:d[2],reasoning:d[3],total:d[4],source:d[5]},cost:{usd:p[0],brl:p[1],fx_rate:p[2]??null},provider:e[10],model:e[11],source_call_key:e[12],...e[13]===null?{}:{source_occurred_at:e[13]},...e[14]===null||e[14]===void 0?{}:{source_started_at:e[14]},...e[15]===null||e[15]===void 0?{}:{source_finished_at:e[15]},...f===null||!Array.isArray(f)?{}:{runtime:{reasoning_effort:f[0],service_tier:f[1]}}}}if(e[1]!=="u"||!Array.isArray(e[8])||!Array.isArray(e[9]))throw new Error("Invalid Run transport v3 delta");let n=e[8],i=e[9],r=e[15],o=e[16],a=e[17],s=e[18],l=e[19],c=e[20],u=typeof e[21]=="string"?e[21]:null;return{schema_version:2,type:"usage.recorded",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],activity_kind:e[6],classification_source:e[7],tokens:{input:n[0],cached_input:n[1],output:n[2],reasoning:n[3],total:n[4],source:n[5]},cost:{usd:i[0],brl:i[1],fx_rate:i[2]??null},provider:e[10],model:e[11],source_segment_key:e[12],...u==null?{}:{attributed_spec_id:u},...c==null?{}:{model_call_id:c},supersedes_event_id:e[13],...e[14]===null?{}:{source_occurred_at:e[14]},...a==null?{}:{source_started_at:a},...s==null?{}:{source_finished_at:s},...l===!0?{retrospective_correction:!0}:{},...r===null||!Array.isArray(r)?{}:{context_stats:{initial_pack_tokens:r[0],tool_output_tokens:r[1],files_opened:r[2],snippets_opened:r[3]}},...o===null||!Array.isArray(o)?{}:{runtime:{reasoning_effort:o[0],service_tier:o[1]}}}}var Ws=fe.z.string().datetime({offset:!0}),SP=fe.z.preprocess(e=>e==="client"?"provider_reported":e,fe.z.enum(["provider_reported","estimated","unavailable"])),Uq=fe.z.object({id:fe.z.string().regex(/^DEC-(?:HUMAN|AI)-/),title:fe.z.string().min(1),origin:fe.z.enum(["human","agent"]),category:fe.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation"]),status:fe.z.enum(["active","superseded","rejected"]),task:fe.z.string().startsWith("TASK-").nullable(),change:fe.z.string().startsWith("CHG-").nullable(),context:fe.z.string().min(1),decision:fe.z.string().min(1),reason:fe.z.string().min(1),alternatives:fe.z.array(fe.z.string()),consequences:fe.z.array(fe.z.string()),reversible:fe.z.boolean(),rollback:fe.z.string(),confidence:fe.z.number().min(0).max(1).nullable(),created_at:Ws,confirmed_at:Ws.nullable()}).strict();var xq=fe.z.object({id:fe.z.string().startsWith("RUN-"),task:fe.z.string().startsWith("TASK-"),status:fe.z.enum(["running","completed","failed"]),client:fe.z.string().min(1),agent:fe.z.string().min(1),model:fe.z.string().min(1),started_at:Ws,finished_at:Ws.nullable(),duration_ms:fe.z.number().int().nonnegative().nullable(),provider:fe.z.string().min(1).nullable().default(null),token_usage:fe.z.object({input:fe.z.number().int().nonnegative().nullable(),cached_input:fe.z.number().int().nonnegative().nullable().default(null),output:fe.z.number().int().nonnegative().nullable(),reasoning:fe.z.number().int().nonnegative().nullable(),total:fe.z.number().int().nonnegative().nullable().default(null),source:SP}),cost:fe.z.object({estimated_usd:fe.z.number().nonnegative().nullable(),estimated_brl:fe.z.number().nonnegative().nullable(),fx_rate:fe.z.number().positive().nullable(),pricing_model:fe.z.string().nullable(),pricing_source:fe.z.string().nullable(),input_usd:fe.z.number().nonnegative().nullable().default(null),cached_input_usd:fe.z.number().nonnegative().nullable().default(null),output_usd:fe.z.number().nonnegative().nullable().default(null),reasoning_usd:fe.z.number().nonnegative().nullable().default(null)}).default({estimated_usd:null,estimated_brl:null,fx_rate:null,pricing_model:null,pricing_source:null,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null}),telemetry:fe.z.object({cycle_count:fe.z.number().int().nonnegative().nullable(),source:fe.z.enum(["repository","local-codex","manual","unavailable"]),segment_key:fe.z.string().nullable()}).default({cycle_count:null,source:"unavailable",segment_key:null}),commands:fe.z.array(fe.z.string()),gates:fe.z.array(fe.z.string()),decisions:fe.z.array(fe.z.string()),evidence:fe.z.array(fe.z.string())}).strict();var bP=["prd_count","spec_count","task_count","test_count","evidence_count"],Bs=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function EP(e,t){let n=["a.payload_type IS NULL","a.run_id IS NOT NULL","a.zaip_agent IS NOT NULL"],i=[];for(let f of["from","to"])t[f]&&(n.push(`a.occurred_day_sp ${f==="from"?">=":"<="} ?`),i.push(t[f].slice(0,10)));for(let f of["agent","phase","status"])t[f]&&(n.push(`a.${f==="agent"?"zaip_agent":f}=?`),i.push(t[f]));t.risk&&(n.push("EXISTS (SELECT 1 FROM zaip_aios_activities t WHERE t.payload_type='work_item' AND json_extract(t.payload_json,'$.entity_kind')='task' AND json_extract(t.payload_json,'$.id')=a.task_id AND json_extract(t.payload_json,'$.risk')=?)"),i.push(t.risk)),(t.priority||t.workType)&&n.push("0"),t.origin&&n.push(t.origin==="prd"?"a.prd_id IS NOT NULL":t.origin==="spec"?"a.prd_id IS NULL AND a.spec_id IS NOT NULL":t.origin==="task"?"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NOT NULL":"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NULL");let r=[];for(let f of["provider","model"])t[f]&&(r.push(`COALESCE(u.${f},'unavailable')=?`),i.push(t[f]));r.length&&n.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=a.agent_invocation_id AND ${r.join(" AND ")})`),t.query&&(n.push("(a.zaip_agent LIKE ? OR a.zaip_agent_persona LIKE ? OR a.zaip_agent_job LIKE ?)"),i.push(...Array(3).fill(`%${t.query}%`)));let o=e.prepare(`SELECT a.run_id, MIN(a.zaip_agent) AS agent FROM zaip_aios_activities a WHERE ${n.join(" AND ")} GROUP BY a.run_id HAVING COUNT(DISTINCT a.zaip_agent)=1`).all(...i),a=new Map(o.map(f=>[f.run_id,f.agent])),s=new Map,l=new Set,c=t.from?.slice(0,10)??"0000-01-01",u=t.to?.slice(0,10)??"9999-12-31",d=e.prepare(`WITH files AS (
203
+ `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ms(t),i=ei(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ms(t),i=ei(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};wy.Parser=Tu});var Ry=w(Gi=>{"use strict";var Ay=fu(),HU=Fi(),Ki=Vi(),JU=_l(),KU=Re(),GU=Au(),Ty=Nu();function Ny(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GU.LineCounter||null,prettyErrors:t}}function XU(e,t={}){let{lineCounter:n,prettyErrors:i}=Ny(t),r=new Ty.Parser(n?.addNewLine),o=new Ay.Composer(t),a=Array.from(o.compose(r.parse(e)));if(i&&n)for(let s of a)s.errors.forEach(Ki.prettifyError(e,n)),s.warnings.forEach(Ki.prettifyError(e,n));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function Iy(e,t={}){let{lineCounter:n,prettyErrors:i}=Ny(t),r=new Ty.Parser(n?.addNewLine),o=new Ay.Composer(t),a=null;for(let s of o.compose(r.parse(e),!0,e.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new Ki.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(a.errors.forEach(Ki.prettifyError(e,n)),a.warnings.forEach(Ki.prettifyError(e,n))),a}function YU(e,t,n){let i;typeof t=="function"?i=t:n===void 0&&t&&typeof t=="object"&&(n=t);let r=Iy(e,n);if(!r)return null;if(r.warnings.forEach(o=>JU.warn(r.options.logLevel,o)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function QU(e,t,n){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}return KU.isDocument(e)&&!i?e.toString(n):new HU.Document(e,i,n).toString(n)}Gi.parse=YU;Gi.parseAllDocuments=XU;Gi.parseDocument=Iy;Gi.stringify=QU});var Ru=w(xe=>{"use strict";var ex=fu(),tx=Fi(),nx=Jl(),Iu=Vi(),rx=wi(),hr=Re(),ix=pr(),ox=rt(),ax=mr(),sx=gr(),cx=Cs(),lx=Ou(),ux=Au(),dx=Nu(),xs=Ry(),$y=bi();xe.Composer=ex.Composer;xe.Document=tx.Document;xe.Schema=nx.Schema;xe.YAMLError=Iu.YAMLError;xe.YAMLParseError=Iu.YAMLParseError;xe.YAMLWarning=Iu.YAMLWarning;xe.Alias=rx.Alias;xe.isAlias=hr.isAlias;xe.isCollection=hr.isCollection;xe.isDocument=hr.isDocument;xe.isMap=hr.isMap;xe.isNode=hr.isNode;xe.isPair=hr.isPair;xe.isScalar=hr.isScalar;xe.isSeq=hr.isSeq;xe.Pair=ix.Pair;xe.Scalar=ox.Scalar;xe.YAMLMap=ax.YAMLMap;xe.YAMLSeq=sx.YAMLSeq;xe.CST=cx;xe.Lexer=lx.Lexer;xe.LineCounter=ux.LineCounter;xe.Parser=dx.Parser;xe.parse=xs.parse;xe.parseAllDocuments=xs.parseAllDocuments;xe.parseDocument=xs.parseDocument;xe.stringify=xs.stringify;xe.visit=$y.visit;xe.visitAsync=$y.visitAsync});var jP={};Kv(jP,{SqliteReadModelFileSystem:()=>rc,allocateAttributedTokenActiveMs:()=>ec,rebuildSqliteReadModel:()=>xP,sourceFingerprint:()=>no,sqliteReadModelPath:()=>nc,sqliteViewMetadata:()=>sd,validateSqliteReadModelSchema:()=>tc});module.exports=Gv(jP);var oo=require("node:crypto"),bv=require("node:fs"),ic=require("node:fs/promises"),ao=require("node:path"),Lr=require("node:sqlite");var be=ut(pt(),1),gD=be.z.object({provider:be.z.string().min(1),models:be.z.array(be.z.string().min(1)).min(1),reasoning_efforts:be.z.array(be.z.enum(["low","medium","high","xhigh"])).min(1),velocities:be.z.array(be.z.literal("standard")).length(1),streaming:be.z.boolean(),cancellation:be.z.boolean(),checkpointing:be.z.boolean(),resume:be.z.boolean(),tool_calls:be.z.boolean(),structured_output:be.z.boolean(),max_parallel_invocations:be.z.number().int().positive()}).strict().superRefine((e,t)=>{e.resume&&!e.checkpointing&&t.addIssue({code:"custom",message:"Resume requires checkpointing"})}),hC=be.z.object({role:be.z.enum(["system","user","assistant","tool"]),content:be.z.string(),name:be.z.string().min(1).nullable().default(null)}).strict(),yD=be.z.object({schema_version:be.z.literal(1),invocation_id:be.z.string().regex(/^INV-[A-Z0-9-]+$/),agent_id:be.z.string().min(1),model:be.z.string().min(1),reasoning_effort:be.z.enum(["low","medium","high","xhigh"]),velocity:be.z.literal("standard"),input:be.z.object({messages:be.z.array(hC).min(1),context_refs:be.z.array(be.z.string().min(1)),tools:be.z.array(be.z.string().min(1)),response_format:be.z.enum(["text","json"])}).strict(),budget:be.z.object({max_output_tokens:be.z.number().int().positive(),timeout_ms:be.z.number().int().positive().nullable(),max_tool_calls:be.z.number().int().nonnegative()}).strict(),metadata:be.z.record(be.z.string(),be.z.string()),resume_from:be.z.string().min(1).nullable()}).strict(),hD=be.z.object({invocation_id:be.z.string().regex(/^INV-[A-Z0-9-]+$/),reason:be.z.enum(["user","budget","timeout","shutdown","superseded"]),requested_at:be.z.string().datetime()}).strict();var ye=ut(pt(),1),er={schema_version:ye.z.literal(1),invocation_id:ye.z.string().regex(/^INV-[A-Z0-9-]+$/),sequence:ye.z.number().int().nonnegative(),occurred_at:ye.z.string().datetime()},vC=ye.z.object({checkpoint_id:ye.z.string().regex(/^CHK-[A-Z0-9-]+$/),opaque_token:ye.z.string().min(1),resumable_until:ye.z.string().datetime().nullable(),state_hash:ye.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),jf=ye.z.object({input_tokens:ye.z.number().int().nonnegative(),cached_input_tokens:ye.z.number().int().nonnegative(),output_tokens:ye.z.number().int().nonnegative(),reasoning_tokens:ye.z.number().int().nonnegative(),source:ye.z.enum(["provider","estimated","unavailable"])}).strict(),SC=ye.z.object({code:ye.z.enum(["authentication","authorization","invalid_request","rate_limit","provider_unavailable","timeout","budget_exceeded","tool_error","protocol_error","unknown"]),message:ye.z.string().min(1),retryable:ye.z.boolean(),retry_after_ms:ye.z.number().int().nonnegative().nullable(),provider_code:ye.z.string().nullable()}).strict(),bC=ye.z.discriminatedUnion("type",[ye.z.object({...er,type:ye.z.literal("invocation.started")}).strict(),ye.z.object({...er,type:ye.z.literal("output.delta"),delta:ye.z.string().min(1)}).strict(),ye.z.object({...er,type:ye.z.literal("tool.requested"),call_id:ye.z.string().min(1),name:ye.z.string().min(1),arguments:ye.z.unknown()}).strict(),ye.z.object({...er,type:ye.z.literal("tool.completed"),call_id:ye.z.string().min(1),output:ye.z.unknown()}).strict(),ye.z.object({...er,type:ye.z.literal("checkpoint.created"),checkpoint:vC}).strict(),ye.z.object({...er,type:ye.z.literal("usage.updated"),usage:jf}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.completed"),output:ye.z.string(),usage:jf}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.failed"),error:SC}).strict(),ye.z.object({...er,type:ye.z.literal("invocation.cancelled"),reason:ye.z.string().min(1)}).strict()]);var _e=ut(pt(),1),bt=_e.z.array(_e.z.string().min(1)).superRefine((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:"custom",message:"Values must be unique"})}),zf=_e.z.string().regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/),EC=_e.z.object({nome:zf,cargo:zf,foto_url:_e.z.url().refine(e=>{let t=new URL(e).protocol;return t==="http:"||t==="https:"},"Persona photo URL must use http or https").optional()}).strict();function kC(e){return`${e.nome}_${e.cargo}_zaip_agent`}var OC=bt.length(1).superRefine((e,t)=>{for(let[n,i]of e.entries())/^[a-z0-9_]+$/.test(i)||t.addIssue({code:"custom",path:[n],message:"Codex nicknames must be lowercase snake_case"})}),wC=_e.z.string().regex(/^zaip-agent-[a-z0-9-]+$/,'Codex agent name must use the "zaip-agent-NOME" format'),AC=_e.z.string().regex(/^[a-z0-9_]+$/,"Codex task name must use lowercase snake_case"),Ff=_e.z.enum(["orchestrator","analyst","task-executor","execution-finalizer","builder","reviewer","integrator","auditor"]),TC=_e.z.enum(["id","codex_name","codex_task_name"]),NC=_e.z.object({kind:TC,value:_e.z.string().min(1),deprecated_at:_e.z.iso.date(),remove_after:_e.z.iso.date(),replacement:_e.z.string().regex(/^agent-[a-z0-9-]+$/)}).strict().superRefine((e,t)=>{(e.kind==="id"?/^agent-[a-z0-9-]+$/.test(e.value):e.kind==="codex_name"?/^zaip-agent-[a-z0-9-]+$/.test(e.value):/^[a-z0-9_]+$/.test(e.value))||t.addIssue({code:"custom",path:["value"],message:`Alias value does not match identity kind ${e.kind}`}),e.remove_after<=e.deprecated_at&&t.addIssue({code:"custom",path:["remove_after"],message:"Alias removal date must be after its deprecation date"})}),Da=_e.z.object({allow:bt,deny:bt}).strict().superRefine((e,t)=>{let n=e.allow.filter(i=>e.deny.includes(i));n.length>0&&t.addIssue({code:"custom",message:`Permission both allowed and denied: ${n.join(", ")}`})}),IC=_e.z.object({id:_e.z.string().regex(/^agent-[a-z0-9-]+$/),version:_e.z.number().int().positive(),purpose:_e.z.string().min(1),use_when:bt.min(1),do_not_use:bt.min(1),codex_name:wC,codex_task_name:AC,persona:EC,nickname_candidates:OC,compatibility:_e.z.object({aliases:_e.z.array(NC)}).strict().optional(),role:Ff,priority:_e.z.number().int().nonnegative().default(100),inherits:_e.z.string().regex(/^agent-[a-z0-9-]+$/).nullable().default(null),capabilities:bt.min(1),execution_eligibility:_e.z.array(_e.z.enum(["interaction","delivery"])),tools:bt,skills:bt,write_scopes:bt,permissions:_e.z.object({filesystem:Da,network:Da,shell:Da,deployment:Da}).strict(),model:_e.z.object({required_capabilities:bt,preferred:bt,reasoning_effort:_e.z.enum(["low","medium","high","xhigh","ultra"]).optional()}).strict(),budget:_e.z.object({soft_cycles:_e.z.number().int().positive()}).strict(),contract:_e.z.object({inputs:bt.min(1),outputs:bt.min(1),evidence:bt.min(1)}).strict(),review:_e.z.object({can_approve:_e.z.boolean(),cannot_review_roles:_e.z.array(Ff)}).strict(),escalation:bt}).strict().superRefine((e,t)=>{let n=e.nickname_candidates[0];e.codex_task_name!==n&&t.addIssue({code:"custom",path:["codex_task_name"],message:`Codex task name must equal the primary nickname candidate: ${n}`});let i=kC(e.persona);e.nickname_candidates[0]!==i&&t.addIssue({code:"custom",path:["nickname_candidates"],message:`nickname_candidates must contain only the derived persona nickname: ${i}`})}),RC=_e.z.object({id:_e.z.string().regex(/^squad-[a-z0-9-]+$/),version:_e.z.number().int().positive(),purpose:_e.z.string().min(1),members:_e.z.array(_e.z.string().regex(/^agent-[a-z0-9-]+$/)).min(2),max_parallelism:_e.z.number().int().positive(),delegation:_e.z.array(_e.z.object({from:_e.z.string().regex(/^agent-[a-z0-9-]+$/),to:_e.z.string().regex(/^agent-[a-z0-9-]+$/),capability:_e.z.string().min(1)}).strict()),review_policy:_e.z.object({independent:_e.z.literal(!0),executor_roles:_e.z.array(_e.z.enum(["analyst","builder","task-executor"])).min(1),reviewer_roles:_e.z.array(_e.z.enum(["reviewer","auditor"])).min(1)}).strict(),escalation:_e.z.array(_e.z.string().regex(/^agent-[a-z0-9-]+$/)).min(1)}).strict(),ND=_e.z.object({schema_version:_e.z.literal(1),agents:_e.z.array(IC).min(1),squads:_e.z.array(RC).min(1)}).strict();var Z=ut(pt(),1);var pe=ut(pt(),1),$C=["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"],CC=["low","medium","high","xhigh"];var Zf="task-risk-v1",jD=pe.z.enum($C),zD=pe.z.enum(CC),LC=pe.z.literal("standard"),FD=pe.z.object({model:pe.z.string().min(1).optional(),reasoning_effort:pe.z.string().min(1).optional(),velocity:pe.z.string().min(1).optional()}).strict().refine(e=>e.model!==void 0||e.reasoning_effort!==void 0||e.velocity!==void 0,"Model selection override must define at least one field"),MC=pe.z.enum(["discovery","planning","replanning","implementation","testing","integration","review","audit","finalization","rework"]),UC=pe.z.enum(["full_stack_boundary","shared_contracts_3_plus","critical_data_or_security","rollout_and_rollback","repeated_structural_repair","architectural_review_finding","prepared_plan_invalidated","material_architectural_tradeoffs"]),xC=pe.z.object({phase:MC,agent_role:pe.z.string().min(1),complexity:pe.z.enum(["simple","standard","complex"]),risk:pe.z.enum(["lite","standard","critical"]),transversality:pe.z.enum(["local","multi_module","cross_system"]),ambiguity:pe.z.enum(["low","medium","high"]),rework:pe.z.enum(["none","localized","structural"]),rework_cost:pe.z.enum(["low","medium","high"]),bounded:pe.z.boolean(),high_volume:pe.z.boolean().default(!1),xhigh_triggers:pe.z.array(UC).default([])}).strict(),Kc=pe.z.object({production_impact:pe.z.boolean(),external_action:pe.z.boolean(),irreversible_change:pe.z.boolean(),security_or_critical_data:pe.z.boolean(),data_migration:pe.z.boolean(),broad_audit:pe.z.boolean(),rollback:pe.z.enum(["trivial","planned","complex"]),verification_scope:pe.z.enum(["scoped","package","cross_scope","full"])}).strict(),PC=xC.omit({agent_role:!0,risk:!0}).extend({risk_signals:Kc}).strict(),ZD=PC.extend({risk:pe.z.enum(["lite","standard","critical"]),risk_signals:Kc,risk_policy_version:pe.z.literal(Zf),risk_reasons:pe.z.array(pe.z.enum(["CRITICAL_EXPLICIT_IMPACT","CRITICAL_COMPLEX_ROLLBACK","CRITICAL_AMBIGUOUS_CROSS_SYSTEM","CRITICAL_STRUCTURAL_REWORK","LITE_BOUNDED_LOCAL","STANDARD_GOVERNED"])).min(1)}).strict().superRefine((e,t)=>{let n=DC(e);e.risk!==n.risk&&t.addIssue({code:"custom",path:["risk"],message:`Task risk must be ${n.risk} for the persisted signals`}),JSON.stringify(e.risk_reasons)!==JSON.stringify(n.reasons)&&t.addIssue({code:"custom",path:["risk_reasons"],message:`Task risk reasons must be ${n.reasons.join(",")}`})}),qD=pe.z.object({models:pe.z.array(pe.z.string().min(1)).min(1),reasoning_efforts:pe.z.array(pe.z.string().min(1)).min(1),velocities:pe.z.array(pe.z.string().min(1)).min(1)}).strict(),qf=pe.z.object({mode:pe.z.literal("auto"),default_model:pe.z.literal("gpt-5.6-terra"),default_effort:pe.z.literal("medium"),default_velocity:LC,allowed_models:pe.z.tuple([pe.z.literal("gpt-5.6-luna"),pe.z.literal("gpt-5.6-terra"),pe.z.literal("gpt-5.6-sol")]),allowed_efforts:pe.z.tuple([pe.z.literal("low"),pe.z.literal("medium"),pe.z.literal("high"),pe.z.literal("xhigh")]),max_auto_effort:pe.z.literal("xhigh"),automatic_sources:pe.z.tuple([pe.z.literal("spec"),pe.z.literal("prd")]),notice:pe.z.enum(["always","mismatch"])}).strict();function DC(e){let t=Kc.parse(e.risk_signals);return t.production_impact||t.external_action||t.irreversible_change||t.security_or_critical_data||t.data_migration||t.broad_audit?qr("critical","CRITICAL_EXPLICIT_IMPACT"):t.rollback==="complex"?qr("critical","CRITICAL_COMPLEX_ROLLBACK"):e.ambiguity==="high"&&e.transversality==="cross_system"?qr("critical","CRITICAL_AMBIGUOUS_CROSS_SYSTEM"):e.rework==="structural"&&e.rework_cost==="high"?qr("critical","CRITICAL_STRUCTURAL_REWORK"):e.complexity==="simple"&&e.transversality==="local"&&e.ambiguity==="low"&&e.rework==="none"&&e.rework_cost==="low"&&e.bounded&&t.rollback==="trivial"&&t.verification_scope==="scoped"?qr("lite","LITE_BOUNDED_LOCAL"):qr("standard","STANDARD_GOVERNED")}function qr(e,t){return{risk:e,policy_version:Zf,reasons:[t]}}var Cu=ut(Ru(),1),_x=10,$u=class extends Error{name="YamlContractError"};function Xi(e){let t=(0,Cu.parseDocument)(e,{strict:!0,uniqueKeys:!0});if(t.errors.length>0)throw new $u(t.errors.map(n=>n.message).join("; "));return t.toJS({maxAliasCount:_x})}var Ps=Z.z.string().regex(/^[a-f0-9]{64}$/i,"Expected a SHA-256 checksum"),fx=Z.z.string().min(1).superRefine((e,t)=>{try{new Intl.DateTimeFormat("en",{timeZone:e}).format()}catch{t.addIssue({code:"custom",message:"Expected a valid IANA timezone"})}}),mx=Z.z.string().min(1).max(255).refine(e=>e.trim()===e&&!/[\r\n\0]/.test(e),"Expected a non-empty Git branch name");function gx(e){return e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||e.endsWith("/")||/^[A-Za-z]:/.test(e)?!1:e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}var yx=Z.z.object({sha256:Ps}).strict();function Cy(e){return Z.z.record(Z.z.string().min(1),e).superRefine((t,n)=>{for(let i of Object.keys(t))gx(i)||n.addIssue({code:"custom",path:[i],message:"Managed file path must be canonical and workspace-relative"})})}var hx=Cy(yx),vx=Cy(Ps),Sx=Z.z.object({schema_version:Z.z.literal(1),zaip:Z.z.object({enabled:Z.z.boolean()}).strict().optional(),"zaip-aios":Z.z.object({enabled:Z.z.boolean()}).strict().optional(),project:Z.z.object({id:Z.z.string().min(1),name:Z.z.string().min(1),timezone:fx}).strict(),stack:Z.z.object({id:Z.z.string().min(1),language:Z.z.string().min(1).optional(),api:Z.z.string().min(1).optional(),query_builder:Z.z.string().min(1).optional(),extensions:Z.z.array(Z.z.string().min(1)).min(1).optional(),layout:Z.z.object({frontend:Z.z.string().min(1),backend:Z.z.string().min(1),site:Z.z.string().min(1),modules:Z.z.string().min(1),packages:Z.z.string().min(1),e2e:Z.z.string().min(1)}).strict().optional(),source_limits:Z.z.object({warning_lines:Z.z.number().int().positive(),error_lines:Z.z.number().int().positive()}).strict().optional(),invariants:Z.z.array(Z.z.string().min(1)).min(1).optional(),commands:Z.z.object({test:Z.z.string().min(1),typecheck:Z.z.string().min(1)}).strict().optional(),overrides:Z.z.record(Z.z.string(),Z.z.unknown())}).strict(),clients:Z.z.object({codex:Z.z.boolean(),claude:Z.z.boolean()}).strict(),tracking:Z.z.object({enabled:Z.z.boolean(),currency:Z.z.string().regex(/^[A-Z]{3}$/,"Expected an ISO 4217 currency code"),storage_mode:Z.z.enum(["tracked_sanitized","local_only"])}).strict(),deploy:Z.z.object({branch:mx.optional()}).strict().optional(),model_orchestration:Z.z.discriminatedUnion("mode",[Z.z.object({mode:Z.z.literal("manual"),default_model:Z.z.literal("manual"),default_effort:Z.z.literal("manual"),default_velocity:Z.z.literal("manual"),notice:Z.z.enum(["always","mismatch"])}).strict(),Z.z.object({mode:Z.z.literal("off"),default_model:Z.z.string().min(1),default_effort:Z.z.string().min(1),default_velocity:Z.z.string().min(1),notice:Z.z.enum(["always","mismatch"])}).strict(),qf]).optional(),execution:Z.z.discriminatedUnion("runtime",[Z.z.object({runtime:Z.z.literal("manual")}).strict(),Z.z.object({runtime:Z.z.literal("autonomous"),autonomous:Z.z.object({provider:Z.z.enum(["codex","claude"]),model:Z.z.string().min(1),max_parallelism:Z.z.number().int().min(1).max(8),lease_ms:Z.z.number().int().min(5e3).max(36e5),max_phase_attempts:Z.z.number().int().positive().nullable().optional(),max_total_invocations:Z.z.number().int().positive().nullable().optional()}).strict()}).strict()]).optional(),assurance:Z.z.object({version:Z.z.literal(1),standard_depth:Z.z.enum(["auto","base","elevated"]),require_final_commit:Z.z.boolean()}).strict().optional(),context:Z.z.object({canonical_roots:Z.z.array(Z.z.string().min(1)).min(1),projection_roots:Z.z.array(Z.z.string().min(1))}).strict().optional()}).strict().superRefine((e,t)=>{let n=e.zaip?.enabled,i=e["zaip-aios"]?.enabled;n!==void 0&&i!==void 0&&n!==i&&t.addIssue({code:"custom",path:["zaip","enabled"],message:"Conflicting ZAIP activation keys: zaip.enabled and legacy zaip-aios.enabled must agree"})}),Ly={framework:Z.z.object({version:Z.z.string().min(1),distribution_sha256:Ps.nullable()}).strict(),layout:Z.z.object({version:Z.z.union([Z.z.literal(2),Z.z.literal(3)])}).strict(),resolved_profile:Z.z.object({id:Z.z.string().min(1).nullable(),sha256:Ps.nullable()}).strict()},bx=Z.z.object({lock_version:Z.z.literal(1),...Ly,managed_files:hx}).strict(),Ex=Z.z.object({lock_version:Z.z.literal(2),...Ly,managed_files:vx}).strict(),_z=Z.z.toJSONSchema(Sx),pz=Z.z.toJSONSchema(Z.z.union([bx,Ex]));var Oe=require("node:fs/promises"),Fe=require("node:path");var Uy=require("node:crypto");var My="23456789ABCDEFGHJKLMNPQRSTUVWXYZ";function Ds(e=4){if(!Number.isSafeInteger(e)||e<2||e>16)throw new RangeError("collision code length must be between 2 and 16");let t=(0,Uy.randomBytes)(e);return Array.from(t,n=>My[n%My.length]).join("")}var Gn=class extends Error{name="WorkspacePathError"},Qi=class{root;appendQueues=new Map;constructor(t){this.root=(0,Fe.resolve)(t)}resolve(t){if(kx(t)||Ox(t))throw new Gn("Expected a path relative to the workspace root");let n=(0,Fe.resolve)(this.root,t),i=(0,Fe.relative)(this.root,n);if(i===".."||i.startsWith(`..${Fe.sep}`)||(0,Fe.isAbsolute)(i))throw new Gn(`Path escapes workspace root: ${t}`);return n}async exists(t){try{let n=this.resolve(t);return await this.assertPhysicalContainment(n),await(0,Oe.stat)(n),!0}catch(n){if(Yi(n)&&n.code==="ENOENT")return!1;throw n}}async readText(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),(0,Oe.readFile)(n,"utf8")}async readBytes(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),(0,Oe.readFile)(n)}async readTextFrom(t,n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("Expected a non-negative byte offset");let i=this.resolve(t);await this.assertPhysicalContainment(i);let r=await(0,Oe.open)(i,"r");try{let o=await r.stat(),a=Math.min(n,o.size),s=Buffer.allocUnsafe(o.size-a);return s.byteLength>0&&await r.read(s,0,s.byteLength,a),{content:s.toString("utf8"),nextOffset:o.size}}finally{await r.close()}}async listFiles(t,n=""){let i=this.resolve(t);return await this.assertPhysicalContainment(i),await this.exists(t)?(await(0,Oe.readdir)(i,{recursive:!0,withFileTypes:!0})).filter(o=>o.isFile()).map(o=>(0,Fe.relative)(this.root,(0,Fe.resolve)(o.parentPath,o.name)).replace(/\\/g,"/")).filter(o=>o.endsWith(n)).sort():[]}async listDirectories(t){let n=this.resolve(t);return await this.assertPhysicalContainment(n),await this.exists(t)?(await(0,Oe.readdir)(n,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>(0,Fe.relative)(this.root,(0,Fe.resolve)(n,r.name)).replace(/\\/g,"/")).sort():[]}async writeTextAtomic(t,n){let i=this.resolve(t),r=`${i}.${Ds(6)}.tmp`;await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i);try{await(0,Oe.writeFile)(r,n,{encoding:"utf8",flag:"wx"}),await wx(r,i)}finally{await(0,Oe.rm)(r,{force:!0})}}async appendText(t,n){let i=this.resolve(t),o=(this.appendQueues.get(i)??Promise.resolve()).catch(()=>{}).then(async()=>{await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i),await(0,Oe.appendFile)(i,n,{encoding:"utf8",flush:!0})});this.appendQueues.set(i,o);try{await o}finally{this.appendQueues.get(i)===o&&this.appendQueues.delete(i)}}async writeTextExclusive(t,n){let i=this.resolve(t);await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i),await(0,Oe.writeFile)(i,n,{encoding:"utf8",flag:"wx",flush:!0})}async writeTextAtomicExclusive(t,n){let i=this.resolve(t),r=`${i}.${Ds(6)}.tmp`;await this.assertPhysicalContainment(i),await(0,Oe.mkdir)((0,Fe.dirname)(i),{recursive:!0}),await this.assertPhysicalContainment(i);try{await(0,Oe.writeFile)(r,n,{encoding:"utf8",flag:"wx",flush:!0}),await(0,Oe.link)(r,i)}finally{await(0,Oe.rm)(r,{force:!0})}}async removeFile(t){let n=this.resolve(t);await this.assertPhysicalContainment(n),await(0,Oe.rm)(n,{force:!0})}async removeFileIfContentMatches(t,n){let i=`${t}.${Ds(16)}.compare-delete`;try{await this.moveFileAtomic(t,i)}catch(s){if(Yi(s)&&s.code==="ENOENT")return!1;throw s}if(await this.readText(i)===n)return await this.removeFile(i),!0;let o=this.resolve(i),a=this.resolve(t);try{await(0,Oe.link)(o,a),await this.removeFile(i)}catch(s){throw Yi(s)&&s.code==="EEXIST"?new Gn(`Conditional delete observed a replacement; captured file retained at ${i}`):s}return!1}async collectCompareDeleteTombstones(t){let n=[];for(let i of await this.listFiles(t)){let r=/^(.*)\.[A-Z0-9]{16}\.compare-delete$/.exec(i);if(r===null)continue;let o=r[1];o!==void 0&&await this.exists(o)&&(await this.removeFile(i),n.push(i))}return n}async moveFileAtomic(t,n){let i=this.resolve(t),r=this.resolve(n);await this.assertPhysicalContainment(i),await this.assertPhysicalContainment(r),await(0,Oe.mkdir)((0,Fe.dirname)(r),{recursive:!0}),await this.assertPhysicalContainment(r),await(0,Oe.rename)(i,r)}async assertPhysicalContainment(t){let n=await(0,Oe.realpath)(this.root),i=t,r=null;for(;;)try{let o=await(0,Oe.realpath)(i),a=(0,Fe.relative)(n,o);if(a===".."||a.startsWith(`..${Fe.sep}`)||(0,Fe.isAbsolute)(a))throw await(0,Oe.lstat)(i),new Gn(`Physical path escapes workspace root: ${t}`);return}catch(o){if(!Yi(o)||o.code!=="ENOENT")throw o;if(r=o,i===this.root)throw new Gn(`Cannot resolve workspace root for: ${t}`,{cause:r});let a=(0,Fe.dirname)(i);if(a===i)throw new Gn(`Cannot resolve workspace ancestor for: ${t}`,{cause:r});i=a}}};function kx(e){return Fe.posix.isAbsolute(e)||Fe.win32.isAbsolute(e)||/^[A-Za-z]:/.test(e)}function Ox(e){return e.split(/[\\/]+/).some(t=>t==="..")}function Yi(e){return e instanceof Error&&"code"in e}async function wx(e,t){if(process.platform!=="win32"){await(0,Oe.rename)(e,t);return}for(let n=0;n<5;n+=1)try{await(0,Oe.rm)(t,{force:!0}),await(0,Oe.rename)(e,t);return}catch(i){if(!Ax(i)||n===4)throw i;await Tx(25*(n+1))}}function Ax(e){return Yi(e)&&["EPERM","EBUSY","EACCES"].includes(e.code??"")}async function Tx(e){await new Promise(t=>setTimeout(t,e))}var xy=require("node:child_process");var Py=require("node:util"),vz=(0,Py.promisify)(xy.execFile);var st=ut(pt(),1);var Dy=ut(Ru(),1);var kz=st.z.object({id:st.z.string().regex(/^RULE-[A-Z0-9-]+$/),load:st.z.enum(["always","auto","file_match","manual"]),globs:st.z.array(st.z.string().min(1)).default([]),priority:st.z.enum(["critical","high","medium","low"]),max_context_tokens:st.z.number().int().positive(),requires:st.z.array(st.z.string().regex(/^RULE-[A-Z0-9-]+$/))}).strict().superRefine((e,t)=>{e.load==="file_match"&&e.globs.length===0&&t.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}),Oz=st.z.object({schema_version:st.z.literal(2),id:st.z.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:st.z.string().regex(/^[a-z][a-z0-9-]*$/),title:st.z.string().min(1),status:st.z.enum(["proposed","active","deprecated"]),version:st.z.number().int().positive(),source_change:st.z.string().min(1).nullable(),source_release:st.z.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((e,t)=>{e.source_change===null&&e.source_release===void 0&&t.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"}),e.source_change!==null&&e.source_release!==void 0&&t.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})});var ge=ut(pt(),1);var Nx=["codex_host_native","provider_subprocess"],Ix=["frontier","balanced","fast_scan","review"],Rx=["subagents","worktrees","sandbox","approvals","skills","mcp"];var Tz=ge.z.enum(Nx),Nz=ge.z.enum(Ix),zy=ge.z.enum(Rx),$x=ge.z.array(zy).min(1).refine(e=>new Set(e).size===e.length,{message:"native_surfaces must be unique"}),Cx=ge.z.object({locator:ge.z.string().min(1),candidate_sha256:ge.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),Lx=ge.z.object({capability_id:ge.z.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:ge.z.literal("implemented"),previous_states:ge.z.tuple([ge.z.literal("declared")]),evidence:ge.z.array(Cx).length(0)}).strict(),Mx=ge.z.object({tier:ge.z.literal(1),enabled:ge.z.literal(!0),optional:ge.z.literal(!1),invokes_provider_subprocess:ge.z.literal(!1),authority:ge.z.literal("host"),native_surfaces:$x,capability_bindings:ge.z.record(zy,Lx)}).strict().superRefine((e,t)=>{let n=Object.keys(e.capability_bindings).sort(),i=[...e.native_surfaces].sort();JSON.stringify(n)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}),Ux=ge.z.object({tier:ge.z.union([ge.z.literal(2),ge.z.literal(3)]),enabled:ge.z.boolean(),optional:ge.z.literal(!0),invokes_provider_subprocess:ge.z.literal(!0),authority:ge.z.literal("framework"),native_surfaces:ge.z.array(ge.z.never()).length(0),opt_in:ge.z.object({required:ge.z.literal(!0),allowed_sources:ge.z.array(ge.z.enum(["project_config","human_decision"])).min(1).refine(e=>new Set(e).size===e.length,{message:"opt-in sources must be unique"})}).strict()}).strict(),js=ge.z.object({selection:ge.z.enum(["host_available","inherit_host"]),reasoning:ge.z.enum(["low","medium","high"]),intent:ge.z.string().min(1)}).strict(),Iz=ge.z.object({schema_version:ge.z.literal(1),host_id:ge.z.literal("codex"),candidate_sha256:ge.z.null(),default_mode:ge.z.literal("codex_host_native"),modes:ge.z.object({codex_host_native:Mx,provider_subprocess:Ux}).strict(),model_classes:ge.z.object({frontier:js,balanced:js,fast_scan:js,review:js}).strict()}).strict(),Rz=ge.z.object({enabled:ge.z.literal(!0),source:ge.z.enum(["project_config","human_decision"]),provenance:ge.z.object({reference:ge.z.string().min(1),recorded_at:ge.z.string().datetime({offset:!0})}).strict()}).strict();var We=ut(pt(),1);var xx=We.z.object({schema_version:We.z.literal(1),project:We.z.object({id:We.z.string().min(1),name:We.z.string().min(1),timezone:We.z.string().min(1).default("America/Sao_Paulo")}),framework:We.z.object({version:We.z.string().min(1)}),layout:We.z.object({version:We.z.literal(1),managed_namespace:We.z.string().min(1).default(".agents/managed"),project_namespace:We.z.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:We.z.object({id:We.z.string().min(1).default("zaip-aios-stack")}),paths:We.z.object({specs:We.z.string().min(1).default(".agents/specs"),changes:We.z.string().min(1).default(".agents/changes"),tasks:We.z.string().min(1).default(".agents/tasks"),decisions:We.z.string().min(1).default(".agents/decisions"),runs:We.z.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:We.z.array(We.z.enum(["codex","claude"])).default(["codex","claude"])}).strict(),xz=We.z.toJSONSchema(xx);var Fy="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)",Hz=new RegExp(`^${Fy}$`,"i");var Jz=new RegExp(String.raw`\b${Fy}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi");var Mu=class{#e;constructor(t){let n=new Map;for(let i of t){let r=n.get(i.from)??new Set;r.add(i.to),n.set(i.from,r)}this.#e=n}canTransition(t,n){return this.#e.get(t)?.has(n)??!1}assertTransition(t,n){if(!this.canTransition(t,n))throw new Error(`Invalid state transition: ${t} -> ${n}`)}nextStates(t){return[...this.#e.get(t)??[]]}};var Xz=new Mu([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}]);var Y=ut(pt(),1);var Uu=e=>Math.round(e*1e6)/1e6;function zs(e,t,n){let i=`${e} ${t} ${n}`.toLowerCase();return i.includes("claude")||i.includes("anthropic")?"anthropic":i.includes("gpt")||i.includes("openai")||i.includes("codex")?"openai":null}function Zy(e){let t=Math.max(e.inputTokens-e.cachedInputTokens,0),n=Uu(t/1e6*e.inputRate*e.inputMultiplier),i=Uu(e.cachedInputTokens/1e6*(e.cachedInputRate??0)*e.inputMultiplier),r=Uu(e.outputTokens/1e6*e.outputRate*e.outputMultiplier);return{inputUsd:n,cachedInputUsd:i,outputUsd:r,reasoningUsd:0}}var Pe=ut(pt(),1),ti=Pe.z.number().finite().nonnegative().nullable(),Zx=Pe.z.object({task_id:Pe.z.string().min(1),completed:Pe.z.boolean(),completed_at:Pe.z.string().min(1).nullable(),attempt:Pe.z.number().int().nonnegative().nullable(),attempt_id:Pe.z.string().min(1).nullable().optional(),equivalence_key:Pe.z.string().min(1).nullable().optional(),model:Pe.z.string().min(1).nullable(),reasoning_effort:Pe.z.enum(["low","medium","high","xhigh"]).nullable(),baseline_task_id:Pe.z.string().min(1).nullable(),baseline_attempt_id:Pe.z.string().min(1).nullable().optional(),baseline_equivalence_id:Pe.z.string().min(1).nullable(),observed_cost_usd:ti,baseline_observed_cost_usd:ti,quality_score:ti,quality_floor:ti,rework_count:Pe.z.number().int().nonnegative().nullable(),billed_amount:ti.optional(),billed_currency:Pe.z.string().min(1).nullable().optional(),billed_provenance:Pe.z.enum(["observed","inferred","unavailable"]).nullable().optional(),billed_source_id:Pe.z.string().min(1).nullable().optional(),billed_at:Pe.z.string().min(1).nullable().optional(),baseline_billed_amount:ti.optional(),baseline_billed_currency:Pe.z.string().min(1).nullable().optional(),baseline_billed_provenance:Pe.z.enum(["observed","inferred","unavailable"]).nullable().optional(),baseline_billed_source_id:Pe.z.string().min(1).nullable().optional(),baseline_billed_at:Pe.z.string().min(1).nullable().optional()}).strict(),F1=Pe.z.object({timezone:Pe.z.string().min(1),interval:Pe.z.object({start:Pe.z.string().min(1),end:Pe.z.string().min(1)}).strict(),equivalence_key:Pe.z.string().min(1).nullable().optional(),tasks:Pe.z.array(Zx)}).strict();var qy=require("node:crypto");function xu(e){let t=qx(e.manifest),n=t.source_streams.find(i=>i.run_id===e.run_id);if(n===void 0)return null;if(n.path!==e.path||Vy(e.content)!==n.content_sha256)throw new Error(`Historical developer attribution source mismatch: ${e.run_id}`);return t.assignment}function Vy(e){return(0,qy.createHash)("sha256").update(e).digest("hex")}function qx(e){if(typeof e!="object"||e===null)throw new Error("Invalid historical developer attribution manifest");let t=e,{manifest_hash:n,...i}=t;if(t.schema_version!==1||t.kind!=="historical_developer_attribution"||t.assignment?.attribution_source!=="human_assigned"||!Array.isArray(t.source_streams)||Vy(JSON.stringify(i))!==n)throw new Error("Invalid historical developer attribution manifest");return t}var Tr=Y.z.string().datetime({offset:!0}).or(Y.z.string().datetime()),Bx=Y.z.object({id:Y.z.string().min(1),provider:Y.z.enum(["openai","anthropic"]),aliases:Y.z.array(Y.z.string().min(1)).default([]),input_per_million_usd:Y.z.number().nonnegative(),cached_input_per_million_usd:Y.z.number().nonnegative().nullable().default(null),output_per_million_usd:Y.z.number().nonnegative(),reasoning_per_million_usd:Y.z.number().nonnegative().nullable().default(null),priority_input_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_cached_input_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_output_per_million_usd:Y.z.number().nonnegative().nullable().optional(),priority_reasoning_per_million_usd:Y.z.number().nonnegative().nullable().optional(),reasoning_billed_separately:Y.z.boolean().default(!1),long_context_threshold_tokens:Y.z.number().int().positive().nullable().default(null),long_context_input_multiplier:Y.z.number().positive().default(1),long_context_output_multiplier:Y.z.number().positive().default(1),source_label:Y.z.string().min(1),source_url:Y.z.string().url(),notes:Y.z.array(Y.z.string()).default([])}).strict(),By=Y.z.object({schema_version:Y.z.literal(1),updated_at:Tr,source:Y.z.string().min(1),disclaimer:Y.z.string().min(1),models:Y.z.array(Bx)}).strict(),Hy=Y.z.object({schema_version:Y.z.literal(1),base:Y.z.literal("USD"),quote:Y.z.literal("BRL"),rate:Y.z.number().positive(),as_of:Tr,source_label:Y.z.string().min(1),source_url:Y.z.string().url()}).strict(),Jy=Y.z.object({input:Y.z.number().int().nonnegative().nullable(),cached_input:Y.z.number().int().nonnegative().nullable().default(null),output:Y.z.number().int().nonnegative().nullable(),reasoning:Y.z.number().int().nonnegative().nullable(),total:Y.z.number().int().nonnegative().nullable().default(null),source:Y.z.preprocess(e=>e==="client"?"provider_reported":e,Y.z.enum(["provider_reported","estimated","unavailable"]))}).strict(),Ky=Y.z.object({estimated_usd:Y.z.number().nonnegative().nullable(),estimated_brl:Y.z.number().nonnegative().nullable(),fx_rate:Y.z.number().positive().nullable(),pricing_model:Y.z.string().nullable(),pricing_source:Y.z.string().nullable(),input_usd:Y.z.number().nonnegative().nullable().default(null),cached_input_usd:Y.z.number().nonnegative().nullable().default(null),output_usd:Y.z.number().nonnegative().nullable().default(null),reasoning_usd:Y.z.number().nonnegative().nullable().default(null)}).strict(),Hx=Y.z.object({cycle_count:Y.z.number().int().nonnegative().nullable(),source:Y.z.enum(["repository","local-codex","manual","unavailable"]),segment_key:Y.z.string().nullable()}).strict(),zx=Y.z.object({schema_version:Y.z.literal(1),recorded_at:Tr,run_id:Y.z.string().startsWith("RUN-"),task_id:Y.z.string().startsWith("TASK-"),spec_id:Y.z.string().nullable(),change_id:Y.z.string().nullable(),task_title:Y.z.string().nullable(),task_status:Y.z.string().nullable(),client:Y.z.string().min(1),agent:Y.z.string().min(1),provider:Y.z.enum(["openai","anthropic"]).nullable(),model:Y.z.string().min(1),status:Y.z.enum(["running","completed","failed"]),started_at:Tr,finished_at:Tr.nullable(),duration_ms:Y.z.number().int().nonnegative().nullable(),token_usage:Jy,estimated_cost:Ky,telemetry:Hx,source_segment_key:Y.z.string().nullable()}).strict(),Fx=Y.z.object({schema_version:Y.z.literal(1),recorded_at:Tr,run_id:Y.z.string().startsWith("RUN-"),task_id:Y.z.string().startsWith("TASK-"),cycle_index:Y.z.number().int().nonnegative(),provider:Y.z.enum(["openai","anthropic"]).nullable(),model:Y.z.string().min(1),timestamp:Tr,source:Y.z.enum(["local-codex","manual"]),source_segment_key:Y.z.string().nullable(),token_usage:Jy,estimated_cost:Ky}).strict();function Wy(e){return Math.round(e*1e6)/1e6}function Fs(e){let t=e.provider??zs(e.model,"",""),n=e.model.toLowerCase(),i=V=>{let ce=V.toLowerCase();if(n===ce)return!0;let Se=n.slice(ce.length);return Se.startsWith("@")||Se.startsWith(":")||Se.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(Se)},r=e.catalog.models.find(V=>i(V.id)||V.aliases.some(ce=>i(ce)));if(!r||t!==null&&r.provider!==t)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:null,pricing_source:null,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let o=e.usage.cached_input,a=e.usage.input,s=e.usage.output;if(a===null||o===null||s===null)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let l=e.usage.reasoning??0,c=r.long_context_threshold_tokens!==null&&(e.usage.input??0)>r.long_context_threshold_tokens,u=c?r.long_context_input_multiplier:1,d=c?r.long_context_output_multiplier:1,p=e.serviceTier==="priority"||e.serviceTier==="fast";if(p&&c)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let f=p?r.priority_input_per_million_usd??null:r.input_per_million_usd,S=p?r.priority_output_per_million_usd??null:r.output_per_million_usd;if(f===null||S===null)return{estimated_usd:null,estimated_brl:null,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null};let{inputUsd:h,cachedInputUsd:v,outputUsd:E,reasoningUsd:U}=Zy({inputTokens:a,cachedInputTokens:o,outputTokens:s,reasoningTokens:l,inputRate:f,cachedInputRate:p?r.priority_cached_input_per_million_usd??null:r.cached_input_per_million_usd,outputRate:S,reasoningRate:p?r.priority_reasoning_per_million_usd??null:r.reasoning_per_million_usd,inputMultiplier:u,outputMultiplier:d}),F=Wy(h+v+E+U),q=e.fxRate===null||e.fxRate===void 0?null:Wy(F*e.fxRate.rate);return{estimated_usd:F,estimated_brl:q,fx_rate:e.fxRate?.rate??null,pricing_model:r.id,pricing_source:r.source_label,input_usd:h,cached_input_usd:v,output_usd:E,reasoning_usd:U}}var $e=ut(pt(),1);function zt(e,t){let n=[...new Set(t)].sort((a,s)=>a.localeCompare(s)),i=new Map;if(n.length===0)return i;if(e===null||!Number.isFinite(e)){for(let a of n)i.set(a,null);return i}if(Number.isInteger(e)){let a=Math.floor(e/n.length),s=e-a*n.length;return n.forEach((l,c)=>{i.set(l,a+(c===n.length-1?s:0))}),i}let r=e/n.length,o=0;return n.forEach((a,s)=>{let l=s===n.length-1?e-o:r;i.set(a,l),o+=l}),i}var Xy=".agents/records/lifecycle/views",xF=`${Xy}/manifest.json`;var Nr=".agents/records/lifecycle",cZ=`${Nr}/manifest.json`,lZ=`${Nr}/entity-snapshot.json`,uZ=`${Nr}/entity-state.json`,dZ=`${Nr}/indexes`;var _Z=`${Nr}/summary.json`,pZ=`${Nr}/overview.json`,fZ=`${Nr}/active-work.json`;var Qy=$e.z.enum(["prd","spec","change","task","execution","run","decision","validation","evidence"]),mZ=Qy.options,Kx=$e.z.enum(["parent","child","references","evidence","requirement"]),Gx=$e.z.enum(["explicit","derived"]),Xx=$e.z.object({target_id:$e.z.string().min(1),type:Kx,direction:$e.z.enum(["outbound","inbound"]),provenance:Gx,source_locator:$e.z.string().min(1).nullable().default(null)}).strict(),Yx=$e.z.object({input_tokens:$e.z.number().int().nonnegative().nullable().default(null),output_tokens:$e.z.number().int().nonnegative().nullable().default(null),cached_input_tokens:$e.z.number().int().nonnegative().nullable().default(null),total_tokens:$e.z.number().int().nonnegative().nullable().default(null),cost:$e.z.number().nonnegative().nullable().default(null),currency:$e.z.string().min(1).nullable().default(null)}).strict(),Qx=$e.z.object({kind:Qy,id:$e.z.string().min(1),title:$e.z.string().min(1).nullable().default(null),status:$e.z.string().min(1).nullable().default(null),risk:$e.z.string().min(1).nullable().default(null),priority:$e.z.string().min(1).nullable().default(null),updated_at:$e.z.string().datetime({offset:!0}),relations:$e.z.array($e.z.string().min(1)).default([]),relation_edges:$e.z.array(Xx).optional(),usage:Yx.nullable().default(null),data:$e.z.record($e.z.string(),$e.z.unknown()).nullable().default(null)}).strict(),gZ=$e.z.object({schema_version:$e.z.literal(1),event_id:$e.z.string().min(1),occurred_at:$e.z.string().datetime({offset:!0}),operation:$e.z.enum(["upsert","remove"]),entity:Qx}).strict();var fe=ut(pt(),1);var $t=ut(pt(),1);var k=ut(pt(),1);var It=ut(pt(),1),eP=It.z.string().datetime({offset:!0}).or(It.z.string().datetime()),eh=It.z.object({schema_version:It.z.literal(2),event_id:It.z.string().min(1).max(200),run_id:It.z.string().startsWith("RUN-"),sequence:It.z.number().int().positive(),occurred_at:eP,type:It.z.literal("run.attribution.recovered"),phase:It.z.literal("execution"),execution_id:It.z.string().startsWith("EXEC-"),task_id:It.z.string().startsWith("TASK-"),change_id:It.z.string().startsWith("CHG-")}).strict();function th(e,t){return e.entrypoint==="task"&&e.execution_id!==null&&e.task_id!==null&&e.change_id===null&&t.execution_id===e.execution_id&&t.task_id===e.task_id}function Pu(e,t){return e.coverage==="partial"&&t.coverage==="complete"&&e.call_id===t.call_id&&e.agent_invocation_id===t.agent_invocation_id&&e.source_call_key===t.source_call_key&&JSON.stringify(e.tokens)===JSON.stringify(t.tokens)}function Du(e,t,n){return e.type==="usage.recorded"&&e.retrospective_correction===!0&&e.activity_kind==="retrospective_observed_timing"&&e.supersedes_event_id===null&&e.phase===t.phase&&e.source_segment_key!==null&&e.source_started_at!==void 0&&e.source_finished_at!==void 0&&Date.parse(e.source_finished_at)>=Date.parse(e.source_started_at)&&e.source_occurred_at===e.source_finished_at&&e.tokens.source==="unavailable"&&[e.tokens.input,e.tokens.cached_input,e.tokens.output,e.tokens.reasoning,e.tokens.total,e.cost.usd,e.cost.brl,e.cost.fx_rate,e.provider,e.model].every(r=>r===null)?!0:e.type==="usage.recorded"&&e.retrospective_correction===!0&&e.activity_kind==="retrospective_local_remeasurement"&&e.supersedes_event_id!==null&&n.has(e.supersedes_event_id)&&e.phase===t.phase}function Zs(e,t){let n={conversation:0,planning:1,execution:2};if(n[t]<n[e])throw new Error(`Run V2 phase cannot move backward from ${e} to ${t}`)}var Xe=ut(pt(),1),nh=Xe.z.string().datetime({offset:!0}).or(Xe.z.string().datetime()),nP=Xe.z.string().regex(/^DEC-(?:HUMAN|AI)-/),rP=Xe.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation","rollback"]),wZ=Xe.z.object({schema_version:Xe.z.literal(2),id:nP,title:Xe.z.string().min(1),scope_type:Xe.z.enum(["change","execution"]),scope_id:Xe.z.string().min(1),origin:Xe.z.enum(["human","agent"]),category:rP,context:Xe.z.string().min(1),decision:Xe.z.string().min(1),reason:Xe.z.string().min(1),alternatives:Xe.z.array(Xe.z.string().min(1)),consequences:Xe.z.array(Xe.z.string().min(1)),reversible:Xe.z.boolean(),rollback:Xe.z.string().min(1),confidence:Xe.z.number().min(0).max(1).nullable(),created_at:nh,confirmed_at:nh.nullable()}).strict().superRefine((e,t)=>{let n=e.scope_type==="change"?"CHG-":"EXEC-";e.scope_id.startsWith(n)||t.addIssue({code:"custom",path:["scope_id"],message:`${e.scope_type} decision requires ${n} scope_id`});let i=e.origin==="human"?"DEC-HUMAN-":"DEC-AI-";e.id.startsWith(i)||t.addIssue({code:"custom",path:["id"],message:`${e.origin} decision requires ${i} id`}),e.origin==="human"&&e.confidence!==null&&t.addIssue({code:"custom",path:["confidence"],message:"Human decisions do not use agent confidence"}),e.origin==="agent"&&e.confidence===null&&t.addIssue({code:"custom",path:["confidence"],message:"Agent decisions require confidence"}),e.origin==="human"&&e.confirmed_at===null&&t.addIssue({code:"custom",path:["confirmed_at"],message:"Human decisions require explicit confirmation provenance"})});var Rt=k.z.string().datetime({offset:!0}).or(k.z.string().datetime()),qs=k.z.enum(["conversation","planning","execution"]),Vs=k.z.string().startsWith("RUN-"),aP=k.z.string().startsWith("CONV-"),rh=k.z.string().startsWith("EXEC-").nullable(),ih=k.z.string().startsWith("TASK-").nullable(),oh=k.z.string().startsWith("SPEC-").nullable(),ah=k.z.string().startsWith("PRD-").nullable(),sh=k.z.string().startsWith("CHG-").nullable(),zu=Vs.nullable(),Ir=k.z.string().regex(/^(?:AINV|INV)-/).max(200),ch=k.z.string().startsWith("MCALL-").max(200),xZ=k.z.enum(["intake","orchestrator","subagent"]),sP=k.z.enum(["intake","orchestrator","subagent","owner","contributor"]),lh=k.z.enum(["intake","orchestration","execution","review","audit","finalization"]),Fu=k.z.enum(["low","medium","high","xhigh"]),eo=k.z.object({schema_version:k.z.literal(1),provider:k.z.literal("github"),account_id:k.z.string().min(1).max(100),login_snapshot:k.z.string().min(1).max(100),attribution_source:k.z.enum(["verified_local_account","last_verified_local_account","cached_fallback","human_assigned"]),verified_at:Rt.nullable(),expires_at:Rt.nullable().optional(),last_verified_at:Rt.nullable().optional()}).strict();var uh=k.z.enum(["orchestrator","delegated"]);var Zu=k.z.object({input:k.z.number().int().nonnegative().nullable(),cached_input:k.z.number().int().nonnegative().nullable(),output:k.z.number().int().nonnegative().nullable(),reasoning:k.z.number().int().nonnegative().nullable(),total:k.z.number().int().nonnegative().nullable(),source:k.z.enum(["provider_reported","estimated","unavailable"])}).strict().superRefine((e,t)=>{e.input!==null&&e.cached_input!==null&&e.cached_input>e.input&&t.addIssue({code:"custom",path:["cached_input"],message:"cached_input cannot exceed input"}),e.total!==null&&e.input!==null&&e.output!==null&&e.total<e.input+e.output&&t.addIssue({code:"custom",path:["total"],message:"total cannot be lower than input + output"})}),dh=k.z.object({usd:k.z.number().nonnegative().nullable(),brl:k.z.number().nonnegative().nullable(),fx_rate:k.z.number().positive().nullable().optional()}).strict(),Rr={schema_version:k.z.literal(2),event_id:k.z.string().min(1).max(200),run_id:Vs,sequence:k.z.number().int().positive(),occurred_at:Rt},cP=k.z.object({intent:k.z.enum(["conversation","continue","refine","rework","new_work"]),classification_source:k.z.enum(["agent","explicit","fallback"]),confidence:k.z.number().min(0).max(1),reason_codes:k.z.array(k.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(12)}).strict(),_h=k.z.object({...Rr,type:k.z.literal("run.started"),attribution_status:k.z.enum(["attributed","legacy_unattributed"]),developer_identity:eo.nullable().optional(),phase:qs,run_role:sP.optional(),run_purpose:lh.optional(),requires_finalizer:k.z.boolean().optional(),execution_kind:k.z.enum(["interaction","delivery"]).optional(),execution_eligibility:k.z.array(k.z.enum(["interaction","delivery"])).optional(),entrypoint:k.z.enum(["conversation","task","spec","prd"]),work_type:k.z.enum(["new","rework"]),storage_mode:k.z.enum(["tracked_sanitized","local_only"]),client:k.z.string().min(1).max(100),agent:k.z.string().min(1).max(100),agent_name:k.z.string().min(1).max(100).nullable().optional(),agent_identity_warning:k.z.object({code:k.z.literal("deprecated-agent-identity"),kind:k.z.enum(["id","codex_name","codex_task_name"]),requested:k.z.string().min(1),canonical_id:k.z.string().min(1),deprecated_at:k.z.iso.date(),remove_after:k.z.iso.date()}).strict().optional(),provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200),reasoning_effort:Fu.nullable().optional(),client_thread_id:k.z.string().min(1).max(200).nullable().optional(),client_turn_id:k.z.string().min(1).max(200).nullable().optional(),conversation_id:aP,execution_id:rh,task_id:ih,spec_id:oh,prd_id:ah,change_id:sh,parent_run_id:zu,continuation_of_run_id:zu,retry_of_run_id:zu,agent_invocation_id:Ir.optional(),root_agent_invocation_id:Ir.optional(),parent_agent_invocation_id:Ir.nullable().optional(),invocation_kind:uh.optional(),delegation_depth:k.z.number().int().nonnegative().optional(),intake:cP.nullable().optional()}).strict().superRefine((e,t)=>{e.phase==="execution"&&e.execution_id===null&&e.attribution_status!=="legacy_unattributed"&&t.addIssue({code:"custom",path:["execution_id"],message:"Execution phase requires execution_id"}),{conversation:e.conversation_id,task:e.task_id,spec:e.spec_id,prd:e.prd_id}[e.entrypoint]===null&&t.addIssue({code:"custom",path:[`${e.entrypoint}_id`],message:`${e.entrypoint} entrypoint requires its scope id`}),e.run_role==="orchestrator"&&e.parent_run_id!==null&&t.addIssue({code:"custom",path:["parent_run_id"],message:"orchestrator Run cannot have parent_run_id"}),e.run_role==="subagent"&&e.parent_run_id===null&&t.addIssue({code:"custom",path:["parent_run_id"],message:"subagent Sub-Run requires parent_run_id"});let i=e.agent_invocation_id!==void 0;i&&(e.root_agent_invocation_id===void 0||e.parent_agent_invocation_id===void 0||e.invocation_kind===void 0||e.delegation_depth===void 0)&&t.addIssue({code:"custom",path:["agent_invocation_id"],message:"Agent Invocation identity must be complete when present"}),i&&e.invocation_kind==="orchestrator"&&(e.parent_agent_invocation_id!==null||e.root_agent_invocation_id!==e.agent_invocation_id||e.delegation_depth!==0)&&t.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator Agent Invocation must be its root at depth zero"}),i&&e.invocation_kind==="delegated"&&(e.parent_agent_invocation_id===null||e.delegation_depth===0)&&t.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated Agent Invocation requires a parent and positive depth"});for(let[r,o]of[["parent_run_id",e.parent_run_id],["continuation_of_run_id",e.continuation_of_run_id],["retry_of_run_id",e.retry_of_run_id]])o===e.run_id&&t.addIssue({code:"custom",path:[r],message:`${r} cannot reference itself`})}),ph=k.z.object({...Rr,type:k.z.literal("usage.recorded"),phase:qs,activity_kind:k.z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),classification_source:k.z.enum(["explicit","current_context","default","legacy_inferred"]),tokens:Zu,cost:dh,provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),source_segment_key:k.z.string().min(1).max(500).nullable(),attributed_spec_id:k.z.string().min(1).max(200).nullable().optional(),model_call_id:ch.nullable().optional(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict().optional(),supersedes_event_id:k.z.string().min(1).max(200).nullable(),retrospective_correction:k.z.literal(!0).optional(),source_occurred_at:Rt.optional(),source_started_at:Rt.optional(),source_finished_at:Rt.optional(),duration_ms:k.z.number().int().nonnegative().nullable().optional(),duration_provenance:k.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().optional(),context_stats:k.z.object({initial_pack_tokens:k.z.number().int().nonnegative().nullable(),tool_output_tokens:k.z.number().int().nonnegative().nullable(),files_opened:k.z.number().int().nonnegative().nullable(),snippets_opened:k.z.number().int().nonnegative().nullable()}).strict().optional()}).strict(),fh=k.z.object({...Rr,type:k.z.literal("model.call.observed"),call_id:ch,agent_invocation_id:Ir,coverage:k.z.enum(["complete","partial","unavailable"]),tokens:Zu,cost:dh,provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),source_call_key:k.z.string().min(1).max(500).nullable(),source_occurred_at:Rt.optional(),source_started_at:Rt.optional(),source_finished_at:Rt.optional(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict().optional()}).strict(),mh=k.z.object({schema_version:k.z.literal(1),run_id:Vs,execution_id:rh.nullable().default(null),task_id:ih.nullable().default(null),spec_id:oh.nullable().default(null),prd_id:ah.nullable().default(null),change_id:sh.nullable().default(null),developer_identity:eo.nullable().optional(),zaip_agent:k.z.string().min(1).max(100).nullable().default(null),phase:qs.nullable().default(null),purpose:lh.nullable().default(null),agent_invocation_id:Ir,root_agent_invocation_id:Ir,parent_agent_invocation_id:Ir.nullable(),invocation_kind:uh,delegation_depth:k.z.number().int().nonnegative(),client:k.z.enum(["codex","codex-desktop","codex-subagent"]),thread_id:k.z.string().min(1).max(200).nullable(),turn_id:k.z.string().min(1).max(200).nullable(),agent_path:k.z.string().min(1).max(500).nullable()}).strict().superRefine((e,t)=>{e.invocation_kind==="orchestrator"&&(e.parent_agent_invocation_id!==null||e.root_agent_invocation_id!==e.agent_invocation_id||e.delegation_depth!==0)&&t.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator telemetry correlation must be its root at depth zero"}),e.invocation_kind==="delegated"&&(e.parent_agent_invocation_id===null||e.delegation_depth===0)&&t.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated telemetry correlation requires a parent and positive depth"}),e.client==="codex-subagent"&&(e.thread_id!==null||e.agent_path===null&&e.turn_id===null)&&t.addIssue({code:"custom",path:["agent_path"],message:"Codex subagent telemetry requires agent_path or turn_id and no root thread_id"}),e.client!=="codex-subagent"&&e.thread_id===null&&e.turn_id===null&&t.addIssue({code:"custom",path:["thread_id"],message:"Codex root telemetry requires thread_id or turn_id"})}),gh=k.z.object({correlation:mh,event_kind:k.z.enum(["response","usage","terminal","error"]),source:k.z.enum(["codex_app_server","codex_session_fallback","unavailable"]),source_event_key:k.z.string().min(1).max(500),source_method:k.z.enum(["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"]).optional(),stream_boundary:k.z.enum(["item_completed","response_completed","usage_updated","error","turn_completed"]).optional(),source_occurred_at:Rt.nullable(),captured_at:Rt,coverage:k.z.enum(["complete","partial","unavailable"]),tokens:Zu.nullable(),provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),runtime:k.z.object({reasoning_effort:k.z.string().min(1).max(40).nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict(),status:k.z.enum(["completed","failed","cancelled"]).nullable(),will_retry:k.z.boolean().nullable().optional(),latency_ms:k.z.number().int().nonnegative().nullable(),historical_cost:k.z.object({estimated_usd:k.z.number().nonnegative().nullable(),estimated_brl:k.z.number().nonnegative().nullable(),fx_rate:k.z.number().positive().nullable(),pricing_model:k.z.string().nullable(),pricing_source:k.z.string().nullable(),input_usd:k.z.number().nonnegative().nullable(),cached_input_usd:k.z.number().nonnegative().nullable(),output_usd:k.z.number().nonnegative().nullable(),reasoning_usd:k.z.number().nonnegative().nullable()}).strict().nullable().optional(),context_stats:k.z.object({initial_pack_tokens:k.z.number().int().nonnegative().nullable(),tool_output_tokens:k.z.number().int().nonnegative().nullable(),files_opened:k.z.number().int().nonnegative().nullable(),snippets_opened:k.z.number().int().nonnegative().nullable()}).strict().nullable(),discarded_counts:k.z.object({prompt:k.z.number().int().nonnegative(),response_text:k.z.number().int().nonnegative(),reasoning:k.z.number().int().nonnegative(),secrets:k.z.number().int().nonnegative()}).strict()}).strict().superRefine((e,t)=>{e.source==="codex_session_fallback"&&e.coverage==="complete"&&t.addIssue({code:"custom",path:["coverage"],message:"Codex session fallback coverage must be partial or unavailable"}),e.source==="unavailable"&&e.coverage!=="unavailable"&&t.addIssue({code:"custom",path:["coverage"],message:"Unavailable source requires unavailable coverage"}),e.source==="unavailable"&&(e.provider!==null||e.model!==null||e.runtime.reasoning_effort!==null||e.runtime.service_tier!==null||e.latency_ms!==null)&&t.addIssue({code:"custom",path:["source"],message:"Unavailable source cannot contain effective runtime observations"}),e.coverage==="unavailable"&&e.tokens!==null&&e.tokens.source!=="unavailable"&&t.addIssue({code:"custom",path:["tokens","source"],message:"Unavailable coverage cannot contain observed tokens"}),e.event_kind==="terminal"&&e.status===null&&t.addIssue({code:"custom",path:["status"],message:"Terminal telemetry requires status"}),e.event_kind==="error"&&(e.will_retry===!0&&e.status!==null||e.will_retry!==!0&&e.status!=="failed")&&t.addIssue({code:"custom",path:["status"],message:"Retrying errors require null status; terminal errors require failed status"})}),lP=k.z.object({schema_version:k.z.literal(1),event_id:k.z.string().startsWith("CEVT-").max(200),checksum_sha256:k.z.string().regex(/^[a-f0-9]{64}$/),compaction:k.z.object({status:k.z.enum(["pending","compacted"]),compacted_at:Rt.nullable()}).strict(),event:gh}).strict(),yh=k.z.string().startsWith("INV-").max(200),hh=k.z.object({...Rr,type:k.z.literal("model.selection.recorded"),invocation_id:yh,requested:k.z.object({model:k.z.string().min(1).max(200),reasoning_effort:Fu.nullable(),velocity:k.z.literal("standard")}).strict(),selection:k.z.object({source:k.z.enum(["execution-override","task-override","auto-policy","project-default"]),policy_version:k.z.number().int().positive(),reasons:k.z.array(k.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(20)}).strict()}).strict(),vh=k.z.object({...Rr,type:k.z.literal("provider.invocation.finished"),invocation_id:yh,status:k.z.enum(["completed","failed","cancelled"]),effective:k.z.object({provider:k.z.string().min(1).max(100).nullable(),model:k.z.string().min(1).max(200).nullable(),reasoning_effort:Fu.nullable(),service_tier:k.z.string().min(1).max(40).nullable()}).strict(),latency_ms:k.z.number().int().nonnegative().nullable()}).strict(),Sh=k.z.object({...Rr,type:k.z.literal("run.finished"),phase:qs,status:k.z.enum(["completed","failed","cancelled"]),duration_ms:k.z.number().int().nonnegative().nullable().default(null),duration_provenance:k.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().default(null)}).strict(),uP=k.z.object({...Rr,type:k.z.literal("run.finalization.decided"),finalizer_run_id:Vs,outcome:k.z.enum(["completed","blocked","failed","cancelled"]),summary:k.z.string().min(1).max(4e3),evidence_ids:k.z.array(k.z.string().min(1).max(200)).max(100),changed_files:k.z.array(k.z.string().min(1).max(500)).max(1e4).default([])}).strict(),to=k.z.discriminatedUnion("type",[_h,ph,fh,hh,vh,eh,uP,Sh]);var dP=$t.z.object({run_id:$t.z.string().startsWith("RUN-"),path:$t.z.string().startsWith(".agents/records/runs/"),content_sha256:$t.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),_P=$t.z.object({schema_version:$t.z.literal(1),manifest_id:$t.z.string().min(1),created_at:$t.z.string().datetime({offset:!0}),kind:$t.z.literal("historical_developer_attribution"),assignment:eo.extend({attribution_source:$t.z.literal("human_assigned")}),source_streams:$t.z.array(dP).min(1)}).strict().superRefine((e,t)=>{let n=new Set,i=new Set;for(let[r,o]of e.source_streams.entries())n.has(o.run_id)&&t.addIssue({code:"custom",path:["source_streams",r,"run_id"],message:"Duplicate historical Run"}),i.has(o.path)&&t.addIssue({code:"custom",path:["source_streams",r,"path"],message:"Duplicate historical Run path"}),n.add(o.run_id),i.add(o.path)}),qZ=_P.extend({manifest_hash:$t.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var BZ=1440*60*1e3;var KZ=64*1024;function Ah(e){let t=new Map,n=[];for(let i of e){if(i.source_segment_key===null){n.push(i);continue}let r=t.get(i.source_segment_key);if(r===void 0){t.set(i.source_segment_key,i),n.push(i);continue}if(!Th(i,r))throw new Error(`Divergent duplicate source segment: ${i.source_segment_key}`)}return n}function Th(e,t){return JSON.stringify(wh(e))===JSON.stringify(wh(t))}function wh(e){return{phase:e.phase,activity_kind:e.activity_kind,classification_source:e.classification_source,tokens:e.tokens,cost:e.cost,provider:e.provider,model:e.model,source_segment_key:e.source_segment_key,model_call_id:e.model_call_id??null}}function Nh(e,t){let n=[],i=null;for(let r of e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)){let o=JSON.parse(r),a=to.parse(Array.isArray(o)?t(o,i):o);i??=a.run_id,n.push(a)}return n}function Ih(e,t,n){if(e.model!=="unknown"&&n.requested.model!==e.model)throw new Error(`Agent Run model is immutable: expected ${e.model}, received ${n.requested.model}`);if(e.reasoning_effort!=null&&n.requested.reasoning_effort!==e.reasoning_effort)throw new Error(`Agent Run reasoning effort is immutable: expected ${e.reasoning_effort}, received ${n.requested.reasoning_effort}`);let i=t.find(r=>r.type==="model.selection.recorded");if(i!==void 0){if(JSON.stringify(i.requested)!==JSON.stringify(n.requested))throw new Error(`Agent Run calls must inherit one model configuration: ${e.run_id}`);if(JSON.stringify(i.selection)!==JSON.stringify(n.selection))throw new Error(`Agent Run calls must inherit one selection decision: ${e.run_id}`)}}function qu(e){return Nh(e,vP)}function Vu(e){let t=new Map;for(let v of e){let E=to.parse(v),U=t.get(E.event_id);if(U!==void 0){if(JSON.stringify(U)!==JSON.stringify(E))throw new Error(`Divergent duplicate Run V2 event: ${E.event_id}`);continue}t.set(E.event_id,E)}let n=[...t.values()].sort((v,E)=>v.sequence-E.sequence);if(n.length===0||n[0]?.type!=="run.started")throw new Error("Run V2 stream must start with run.started");let i=n[0],r=i.phase,o=null,a=null,s=null,l=new Map,c=new Map,u=new Map,d=new Map,p=new Map;for(let[v,E]of n.entries()){if(E.run_id!==i.run_id)throw new Error("Run V2 stream mixes run ids");if(E.sequence!==v+1)throw new Error("Run V2 sequence must be contiguous");let U=l.get(E.sequence);if(U!==void 0&&U!==E.event_id)throw new Error(`Run V2 sequence is duplicated: ${E.sequence}`);if(l.set(E.sequence,E.event_id),v>0&&E.type==="run.started")throw new Error("Run V2 has multiple starts");if(o!==null&&E.type!=="run.finalization.decided"&&!Du(E,o,c))throw new Error("Run V2 contains a non-retrospective record after run.finished");if(E.type==="usage.recorded"){if(Zs(r,E.phase),E.phase==="execution"&&i.execution_id===null&&i.attribution_status!=="legacy_unattributed")throw new Error("Execution phase requires execution_id");if(E.supersedes_event_id!==null&&!c.has(E.supersedes_event_id))throw new Error(`Superseded usage event must occur earlier: ${E.supersedes_event_id}`);c.set(E.event_id,E),r=E.phase}if(E.type==="run.attribution.recovered"){if(!th(i,E))throw new Error("Run attribution recovery does not match its immutable start header");if(s!==null)throw new Error("Run V2 has multiple attribution recoveries");Zs(r,E.phase),r=E.phase,s=E}if(E.type==="model.selection.recorded"){if(Ih(i,n.slice(0,v),{invocationId:E.invocation_id,requested:E.requested,selection:E.selection}),u.has(E.invocation_id))throw new Error(`Duplicate model selection for invocation: ${E.invocation_id}`);u.set(E.invocation_id,E)}if(E.type==="provider.invocation.finished"){if(!u.has(E.invocation_id))throw new Error(`Provider invocation requires earlier model selection: ${E.invocation_id}`);if(d.has(E.invocation_id))throw new Error(`Duplicate provider terminal for invocation: ${E.invocation_id}`);d.set(E.invocation_id,E)}if(E.type==="model.call.observed"){let F=p.get(E.call_id);if(F!==void 0&&JSON.stringify(F)!==JSON.stringify(E)&&!Pu(F,E))throw new Error(`Divergent duplicate Model Call: ${E.call_id}`);p.set(E.call_id,E)}if(E.type==="run.finalization.decided"){if(a!==null)throw new Error("Run V2 has multiple finalization decisions");a=E}if(E.type==="run.finished"){if(E.phase!==r)throw new Error("run.finished phase must match the latest phase");o=E}}let f=n.filter(v=>v.type==="usage.recorded"),S=new Set(f.map(v=>v.supersedes_event_id).filter(v=>v!==null)),h=Ah(f.filter(v=>!S.has(v.event_id)));return{run:s===null?i:{...i,phase:s.phase,execution_id:s.execution_id,task_id:s.task_id,change_id:s.change_id},status:o?.status??"running",finished:o,finalization_decision:a,attribution_recovery:s,records:n,usage_records:f,effective_usage_records:h,model_selection_records:[...u.values()],provider_invocation_records:[...d.values()],model_call_records:[...p.values()]}}function vP(e,t){if(e[0]!==3||t===null)throw new Error("Run delta requires transport version 3 and a preceding run.started header");if(e[1]==="f")return{schema_version:2,type:"run.finished",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],status:e[6]};if(e[1]==="a")return{schema_version:2,type:"run.attribution.recovered",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],execution_id:e[6],task_id:e[7],change_id:e[8]};if(e[1]==="d"&&Array.isArray(e[8]))return{schema_version:2,type:"run.finalization.decided",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],finalizer_run_id:e[5],outcome:e[6],summary:e[7],evidence_ids:e[8],changed_files:Array.isArray(e[9])?e[9]:[]};if(e[1]==="m"&&Array.isArray(e[6])&&Array.isArray(e[7])){let d=e[6],p=e[7];return{schema_version:2,type:"model.selection.recorded",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],invocation_id:e[5],requested:{model:d[0],reasoning_effort:d[1],velocity:d[2]},selection:{source:p[0],policy_version:p[1],reasons:p[2]}}}if(e[1]==="p"&&Array.isArray(e[7])){let d=e[7];return{schema_version:2,type:"provider.invocation.finished",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],invocation_id:e[5],status:e[6],effective:{provider:d[0],model:d[1],reasoning_effort:d[2],service_tier:d[3]},latency_ms:e[8]}}if(e[1]==="c"&&Array.isArray(e[8])&&Array.isArray(e[9])){let d=e[8],p=e[9],f=e[16];return{schema_version:2,type:"model.call.observed",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],call_id:e[5],agent_invocation_id:e[6],coverage:e[7],tokens:{input:d[0],cached_input:d[1],output:d[2],reasoning:d[3],total:d[4],source:d[5]},cost:{usd:p[0],brl:p[1],fx_rate:p[2]??null},provider:e[10],model:e[11],source_call_key:e[12],...e[13]===null?{}:{source_occurred_at:e[13]},...e[14]===null||e[14]===void 0?{}:{source_started_at:e[14]},...e[15]===null||e[15]===void 0?{}:{source_finished_at:e[15]},...f===null||!Array.isArray(f)?{}:{runtime:{reasoning_effort:f[0],service_tier:f[1]}}}}if(e[1]!=="u"||!Array.isArray(e[8])||!Array.isArray(e[9]))throw new Error("Invalid Run transport v3 delta");let n=e[8],i=e[9],r=e[15],o=e[16],a=e[17],s=e[18],l=e[19],c=e[20],u=typeof e[21]=="string"?e[21]:null;return{schema_version:2,type:"usage.recorded",run_id:t,event_id:e[2],sequence:e[3],occurred_at:e[4],phase:e[5],activity_kind:e[6],classification_source:e[7],tokens:{input:n[0],cached_input:n[1],output:n[2],reasoning:n[3],total:n[4],source:n[5]},cost:{usd:i[0],brl:i[1],fx_rate:i[2]??null},provider:e[10],model:e[11],source_segment_key:e[12],...u==null?{}:{attributed_spec_id:u},...c==null?{}:{model_call_id:c},supersedes_event_id:e[13],...e[14]===null?{}:{source_occurred_at:e[14]},...a==null?{}:{source_started_at:a},...s==null?{}:{source_finished_at:s},...l===!0?{retrospective_correction:!0}:{},...r===null||!Array.isArray(r)?{}:{context_stats:{initial_pack_tokens:r[0],tool_output_tokens:r[1],files_opened:r[2],snippets_opened:r[3]}},...o===null||!Array.isArray(o)?{}:{runtime:{reasoning_effort:o[0],service_tier:o[1]}}}}var Ws=fe.z.string().datetime({offset:!0}),SP=fe.z.preprocess(e=>e==="client"?"provider_reported":e,fe.z.enum(["provider_reported","estimated","unavailable"])),Pq=fe.z.object({id:fe.z.string().regex(/^DEC-(?:HUMAN|AI)-/),title:fe.z.string().min(1),origin:fe.z.enum(["human","agent"]),category:fe.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation"]),status:fe.z.enum(["active","superseded","rejected"]),task:fe.z.string().startsWith("TASK-").nullable(),change:fe.z.string().startsWith("CHG-").nullable(),context:fe.z.string().min(1),decision:fe.z.string().min(1),reason:fe.z.string().min(1),alternatives:fe.z.array(fe.z.string()),consequences:fe.z.array(fe.z.string()),reversible:fe.z.boolean(),rollback:fe.z.string(),confidence:fe.z.number().min(0).max(1).nullable(),created_at:Ws,confirmed_at:Ws.nullable()}).strict();var Dq=fe.z.object({id:fe.z.string().startsWith("RUN-"),task:fe.z.string().startsWith("TASK-"),status:fe.z.enum(["running","completed","failed"]),client:fe.z.string().min(1),agent:fe.z.string().min(1),model:fe.z.string().min(1),started_at:Ws,finished_at:Ws.nullable(),duration_ms:fe.z.number().int().nonnegative().nullable(),provider:fe.z.string().min(1).nullable().default(null),token_usage:fe.z.object({input:fe.z.number().int().nonnegative().nullable(),cached_input:fe.z.number().int().nonnegative().nullable().default(null),output:fe.z.number().int().nonnegative().nullable(),reasoning:fe.z.number().int().nonnegative().nullable(),total:fe.z.number().int().nonnegative().nullable().default(null),source:SP}),cost:fe.z.object({estimated_usd:fe.z.number().nonnegative().nullable(),estimated_brl:fe.z.number().nonnegative().nullable(),fx_rate:fe.z.number().positive().nullable(),pricing_model:fe.z.string().nullable(),pricing_source:fe.z.string().nullable(),input_usd:fe.z.number().nonnegative().nullable().default(null),cached_input_usd:fe.z.number().nonnegative().nullable().default(null),output_usd:fe.z.number().nonnegative().nullable().default(null),reasoning_usd:fe.z.number().nonnegative().nullable().default(null)}).default({estimated_usd:null,estimated_brl:null,fx_rate:null,pricing_model:null,pricing_source:null,input_usd:null,cached_input_usd:null,output_usd:null,reasoning_usd:null}),telemetry:fe.z.object({cycle_count:fe.z.number().int().nonnegative().nullable(),source:fe.z.enum(["repository","local-codex","manual","unavailable"]),segment_key:fe.z.string().nullable()}).default({cycle_count:null,source:"unavailable",segment_key:null}),commands:fe.z.array(fe.z.string()),gates:fe.z.array(fe.z.string()),decisions:fe.z.array(fe.z.string()),evidence:fe.z.array(fe.z.string())}).strict();var bP=["prd_count","spec_count","task_count","test_count","evidence_count"],Bs=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function EP(e,t){let n=["a.payload_type IS NULL","a.run_id IS NOT NULL","a.zaip_agent IS NOT NULL"],i=[];for(let f of["from","to"])t[f]&&(n.push(`a.occurred_day_sp ${f==="from"?">=":"<="} ?`),i.push(t[f].slice(0,10)));for(let f of["agent","phase","status"])t[f]&&(n.push(`a.${f==="agent"?"zaip_agent":f}=?`),i.push(t[f]));t.risk&&(n.push("EXISTS (SELECT 1 FROM zaip_aios_activities t WHERE t.payload_type='work_item' AND json_extract(t.payload_json,'$.entity_kind')='task' AND json_extract(t.payload_json,'$.id')=a.task_id AND json_extract(t.payload_json,'$.risk')=?)"),i.push(t.risk)),(t.priority||t.workType)&&n.push("0"),t.origin&&n.push(t.origin==="prd"?"a.prd_id IS NOT NULL":t.origin==="spec"?"a.prd_id IS NULL AND a.spec_id IS NOT NULL":t.origin==="task"?"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NOT NULL":"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NULL");let r=[];for(let f of["provider","model"])t[f]&&(r.push(`COALESCE(u.${f},'unavailable')=?`),i.push(t[f]));r.length&&n.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=a.agent_invocation_id AND ${r.join(" AND ")})`),t.query&&(n.push("(a.zaip_agent LIKE ? OR a.zaip_agent_persona LIKE ? OR a.zaip_agent_job LIKE ?)"),i.push(...Array(3).fill(`%${t.query}%`)));let o=e.prepare(`SELECT a.run_id, MIN(a.zaip_agent) AS agent FROM zaip_aios_activities a WHERE ${n.join(" AND ")} GROUP BY a.run_id HAVING COUNT(DISTINCT a.zaip_agent)=1`).all(...i),a=new Map(o.map(f=>[f.run_id,f.agent])),s=new Map,l=new Set,c=t.from?.slice(0,10)??"0000-01-01",u=t.to?.slice(0,10)??"9999-12-31",d=e.prepare(`WITH files AS (
204
204
  SELECT json_extract(payload_json,'$.path') path,
205
205
  json_extract(payload_json,'$.artifact_kind') artifact_kind,
206
206
  json_extract(payload_json,'$.artifact_id') artifact_id,
@@ -589,7 +589,7 @@ SELECT i.*,
589
589
  FROM identified_developers
590
590
  ORDER BY entity_kind, id, account_id COLLATE BINARY`).all(...r,o,o,a,a),l=new Map;for(let c of s){let u=`${c.entity_kind}:${c.id}`,d=l.get(u)??[];d.push({account_id:c.account_id,login_snapshot:c.login_snapshot}),l.set(u,d)}return t.map(c=>{let u=Qh(c),d=typeof c.id=="string"?c.id:"";return{...c,developers:u?l.get(`${u}:${d}`)??[]:[]}})}function av(e){if(rv(e))return e.prepare("SELECT * FROM operations_work_projection ORDER BY occurred_at DESC, id DESC").all();let t=nv({kind:"all"});return e.prepare(`${t.select} FROM ${t.source}${t.where} ORDER BY work.occurred_at DESC, work.id DESC`).all(...t.values)}function Qs(e,t,n){return e.filter(i=>{let r=typeof i.occurred_day_sp=="string"?i.occurred_day_sp:"";return r>=t&&r<=n})}var sv=require("node:sqlite");function cv(e,t,n,i){let r;try{r=new sv.DatabaseSync(e,{readOnly:!0});let o=r,a=c=>o.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = ?").get(c)?.value,s=Number(a("source_file_count")??0);return a("source_fingerprint")===t&&a("schema_version")===n&&i(r)?s:null}catch{return null}finally{r?.close()}}function Qu(e){let t=e.prepare("SELECT name FROM sqlite_master WHERE type = 'view' AND name LIKE 'zaip_vw_%'").all();for(let{name:n}of t){let i=n.slice(8),r=a=>`"${a.replaceAll('"','""')}"`;e.prepare("SELECT 1 FROM sqlite_temp_master WHERE name=? LIMIT 1").get(i)===void 0&&e.exec(`CREATE TEMP VIEW ${r(i)} AS SELECT * FROM main.${r(n)}`)}}var lv=require("node:crypto"),$r=require("node:fs/promises"),Cr=require("node:path"),RP=new Set([".json",".jsonl",".md",".yaml",".yml",".txt"]);function $P(e){return[".agents/config/project.yaml",".agents/config/framework.lock.yaml",".agents/config/agents/catalog.yaml",".agents/config/clients.yaml"].includes(e)||e.startsWith(".agents/config/pricing/")||e.startsWith(".agents/records/runs/")&&e.endsWith(".jsonl")||/^\.agents\/records\/(tasks|specs|prds)\/.*\.md$/.test(e)||/^\.agents\/records\/executions\/.*\/execution\.md$/.test(e)||e.startsWith(".agents/records/lifecycle/historical-developer-attribution/")&&e.endsWith(".json")?!0:/^\.agents\/records\/changes\/.*\/(change\.md|decisions\/.*\.md|artifacts\/(evidence|tests|validations)\/.*\.md)$/.test(e)}async function no(e,t={}){let n=(await Promise.all([".agents/config",...["tasks","specs","prds","runs","executions","changes","lifecycle/historical-developer-attribution"].map(a=>`.agents/records/${a}`)].map(a=>uv((0,Cr.resolve)(e,a))))).flat().filter(a=>RP.has(a.slice(a.lastIndexOf(".")).toLowerCase())&&$P((0,Cr.relative)(e,a).replaceAll("\\","/"))).sort(),i=[],r=0,o=0;for(let a=0;a<n.length;a+=32)i.push(...(await Promise.all(n.slice(a,a+32).map(async s=>{let l=(0,Cr.relative)(e,s).replaceAll("\\","/");try{for(let c=0;c<3;c+=1){let u=await(0,$r.stat)(s),d={path:s,source:l,mtimeMs:u.mtimeMs,ctimeMs:u.ctimeMs,size:u.size,fileIdentity:`${u.dev}:${u.ino}:${u.birthtimeMs}`},p=t.previous?.get(l);if(!t.verifyContent&&p!==void 0&&p.mtimeMs===d.mtimeMs&&p.ctimeMs===d.ctimeMs&&p.size===d.size&&p.fileIdentity===d.fileIdentity)return o+=1,{...d,contentHash:p.contentHash};let f=(0,lv.createHash)("sha256").update(await(0,$r.readFile)(s)).digest("hex"),S=await(0,$r.stat)(s);if(!(u.mtimeMs!==S.mtimeMs||u.ctimeMs!==S.ctimeMs||u.size!==S.size||u.ino!==S.ino||u.dev!==S.dev||u.birthtimeMs!==S.birthtimeMs))return r+=1,{...d,contentHash:f}}throw new Error(`Canonical source changed repeatedly during refresh: ${l}`)}catch(c){if(c.code==="ENOENT")return null;throw c}}))).filter(s=>s!==null));return{fingerprint:i.map(a=>`${a.source}:${a.mtimeMs}:${a.size}:${a.contentHash}`).join("|"),candidates:i,hashedFiles:r,reusedFiles:o}}async function uv(e){let t=await(0,$r.readdir)(e,{withFileTypes:!0}).catch(n=>{if(n.code==="ENOENT")return[];throw n});return(await Promise.all(t.map(async n=>{let i=(0,Cr.join)(e,n.name);return n.isDirectory()?uv(i):n.isFile()?[i]:[]}))).flat()}var CP=performance.now();function ed(e,t,n){process.env.ZAIP_DASHBOARD_LAUNCH_PROGRESS==="1"&&process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_rebuild_progress",phase:e,percent:t,detail:n,elapsed_ms:Math.round(performance.now()-CP)})}
591
591
  `)}function td(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];if(t===void 0)return null;try{let n=Xi(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function ni(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Be(e){return typeof e=="string"&&e.length>0?e:null}function ro(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ft(e){let t=[...new Set(e.filter(n=>typeof n=="string"&&n.length>0&&n!=="unavailable"))];return t.length===0?null:t.length===1?t[0]:"mixed"}var nd=2*36e5;function dv(){let e=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),t=Object.fromEntries(e.map(i=>[i.type,i.value])),n=`${t.year}-${t.month}-${t.day}`;return{from:`${t.year}-${t.month}-01`,to:n}}function _v(e){let t=[],n=[],i=[];for(let r of e){let o=td(r.content);if(o===null)continue;let a=Be(o.id),s=Be(o.created_at);if(!(a===null||s===null||Number.isNaN(Date.parse(s)))){if(/^\.agents\/records\/executions\/.*\/execution\.md$/.test(r.path)){let l=ni(o.origin),c=Be(l?.type),u=c==="interaction"?Be(l?.conversation_id):c==="task"?Be(l?.task_id):c==="spec"?Be(l?.spec_id):c==="prd"?Be(l?.prd_id):null;t.push({id:a,status:Be(o.status),kind:Be(o.kind),originType:c,originId:u,createdAt:s,finishedAt:Be(o.finished_at),sourcePath:r.path});continue}if(/^\.agents\/records\/changes\/.*\/change\.md$/.test(r.path)){let l=ni(o.source),c=Be(l?.type),u=c==="task"?Be(l?.task_id):c==="spec"?Be(l?.spec_id):c==="prd"?Be(l?.prd_id):null;if(c===null||u===null)continue;n.push({id:a,title:Be(o.title)??a,status:Be(o.status)??"unclassified",risk:Be(o.risk)??"unclassified",sourceType:c,sourceId:u,sourceSpecId:Be(l?.spec_id),sourcePrdId:Be(l?.prd_id),requirementIds:ro(o.requirement_ids),acceptanceIds:ro(o.acceptance_ids),taskIds:ro(o.task_ids),result:Be(o.result),createdAt:s,sourcePath:r.path});continue}if(/^\.agents\/records\/(changes|executions)\/.*\/decisions\/.*\.md$/.test(r.path)){let l=o.origin,c=o.scope_type,u=Be(o.scope_id);if(l!=="human"&&l!=="agent"||c!=="change"&&c!=="execution"||u===null)continue;i.push({id:a,title:Be(o.title)??a,origin:l,scopeType:c,scopeId:u,createdAt:s,sourcePath:r.path})}}}return{executions:t,changes:n,decisions:i}}function rd(e){let t=new Map;for(let n of e){let i=/^\.agents\/records\/(tasks|specs|prds|changes|executions|conversations)\//.exec(n.path);if(i===null)continue;let r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(n.content)?.[1];if(r===void 0)continue;let o=l=>{let c=new RegExp(`^${l}:\\s*(.+?)\\s*$`,"m").exec(r)?.[1]?.trim();return c===void 0||c==="null"?null:c.replace(/^['"]|['"]$/g,"")},a=o("id");if(a===null)continue;let s=i[1]?.slice(0,-1);s!==void 0&&t.set(`${s}:${a}`,{kind:s,id:a,title:o("title"),status:o("status"),stage:o("stage"),risk:o("risk"),specId:o("spec_id"),changeId:o("change_id"),occurredAt:o("created_at")??o("started_at")??o("recorded_at"),creationRunId:o("creation_run_id"),completedRunId:o("completed_run_id")})}return t}function pv(e,t){let n=new Map;for(let i of(e??"").split(/^ {2}- id: /m).slice(1)){let r=i.slice(0,i.indexOf(`
592
- `)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function fv(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function Zt(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function io(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:zs(t,n,"")}function LP(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function MP(e){let t=e.flatMap(r=>{let o=r.source_started_at,a=r.source_finished_at,s=typeof o=="string"?Date.parse(o):Number.NaN,l=typeof a=="string"?Date.parse(a):Number.NaN;return typeof o=="string"&&typeof a=="string"&&Number.isFinite(s)&&Number.isFinite(l)&&l>s&&l-s<=nd?[{start:o,end:a,startMs:s,endMs:l}]:[]});if(t.length===0)return null;let n=t.reduce((r,o)=>o.startMs<r.startMs?o:r),i=t.reduce((r,o)=>o.endMs>r.endMs?o:r);return i.endMs-n.startMs<=nd?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function mv(e,t){let n=MP(e);if(n!==null)return{source:n.duration,effective:n.duration,provenance:"reconciled",sourceStartedAt:n.start,sourceFinishedAt:n.end};if(typeof t.finished?.duration_ms=="number"&&t.finished.duration_provenance!=="estimated"&&t.finished.duration_provenance!=="unavailable")return{source:t.finished.duration_ms,effective:t.finished.duration_ms,provenance:t.finished.duration_provenance??"observed",sourceStartedAt:null,sourceFinishedAt:null};let i=e.filter(LP);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=Ft(i.map(l=>l.duration_provenance))??"observed";return{source:a,effective:a,provenance:s,sourceStartedAt:null,sourceFinishedAt:null}}let r=Date.parse(t.run.occurred_at),o=typeof t.finished?.occurred_at=="string"?Date.parse(t.finished.occurred_at):Number.NaN;return Number.isFinite(r)&&Number.isFinite(o)&&o>r&&o-r<=nd?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function gv(e){return e.flatMap(t=>{try{return[Hy.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function id(e,t,n,i){let r=0,o=0,a=!1,s=!1,l=!1,c=[],u=[];for(let p of e){if(typeof p.cost.usd=="number"&&(r+=p.cost.usd,a=!0),typeof p.cost.brl=="number"&&(o+=p.cost.brl,s=!0),typeof p.cost.usd=="number"&&typeof p.cost.brl=="number"||p.tokens.total===null)continue;if(p.tokens.total===0){a=!0,s=!0;continue}let f=p.model??t.run.model;if(f===null||f==="unavailable")continue;let S=Fs({provider:io(p.provider,f,t.run.client),model:f,usage:p.tokens,catalog:n,fxRate:i,serviceTier:p.runtime?.service_tier??null});typeof p.cost.usd!="number"&&S.estimated_usd!==null&&(r+=S.estimated_usd,a=!0,l=!0),typeof p.cost.brl!="number"&&S.estimated_brl!==null&&(o+=S.estimated_brl,s=!0,l=!0),S.pricing_model!==null&&c.push(S.pricing_model),S.pricing_source!==null&&u.push(S.pricing_source)}let d=Zt(e,"total");return{usd:a?Math.round(r*1e6)/1e6:null,brl:s?Math.round(o*1e6)/1e6:null,method:d===0?"zero_no_llm_usage":l?"token_pricing_estimate":a||s?"canonical_recorded":null,pricingModel:Ft(c),pricingSource:Ft(u),fxRate:s?i?.rate??null:null}}function UP(e,t){if(t===null)return null;let n=t.toLowerCase(),i=r=>{let o=r.toLowerCase();if(n===o)return!0;let a=n.slice(o.length);return a.startsWith("@")||a.startsWith(":")||a.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(a)};return e.models.find(r=>i(r.id)||r.aliases.some(o=>i(o)))??null}function yv(e,t,n,i){let r=e.model??t.run.model,o=io(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=UP(n,r),l=r===null?null:Fs({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:Fs({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:"default"}),u=s?.long_context_threshold_tokens!==null&&s?.long_context_threshold_tokens!==void 0&&(e.tokens.input??0)>s.long_context_threshold_tokens,d=a==="priority"||a==="fast",p=d&&!u,f=s?p?s.priority_input_per_million_usd??null:s.input_per_million_usd:null,S=s?p?s.priority_cached_input_per_million_usd??null:s.cached_input_per_million_usd:null,h=s?p?s.priority_output_per_million_usd??null:s.output_per_million_usd:null,v=s?p?s.priority_reasoning_per_million_usd??s.priority_output_per_million_usd??null:s.reasoning_per_million_usd??s.output_per_million_usd:null,E=l?.estimated_usd!==null&&l!==null?l:c,U=E?.estimated_usd??null,F=c?.estimated_usd??null,q=e.cost.usd,V=q??U,ce=e.cost.brl??l?.estimated_brl??(V!==null&&i!==null?Math.round(V*i.rate*1e6)/1e6:null);return{provider:o,model:r,serviceTier:a,uncachedInputTokens:e.tokens.input===null?null:Math.max(e.tokens.input-(e.tokens.cached_input??0),0),visibleOutputTokens:e.tokens.output===null?null:Math.max(e.tokens.output-(e.tokens.reasoning??0),0),inputRate:f,cachedRate:S,outputRate:h,reasoningRate:v,contextInputMultiplier:s?u?s.long_context_input_multiplier:1:null,contextOutputMultiplier:s?u?s.long_context_output_multiplier:1:null,speedCostMultiplier:U!==null&&F!==null&&F>0?Math.round(U/F*1e3)/1e3:null,pricingScenario:d&&u?"standard_long_context_fallback":d?"priority":"standard",standardUsd:F,speedUpliftUsd:U!==null&&F!==null?Math.round((U-F)*1e6)/1e6:null,inputUsd:E?.input_usd??null,cachedInputUsd:E?.cached_input_usd??null,outputUsd:E?.output_usd??null,reasoningUsd:E?.reasoning_usd??null,calculatedUsd:U,recordedUsd:q,effectiveUsd:V,effectiveBrl:ce,varianceUsd:q!==null&&U!==null?Math.round((q-U)*1e6)/1e6:null,pricingModel:E?.pricing_model??null,pricingSource:E?.pricing_source??null,fxRate:e.cost.fx_rate??i?.rate??null}}function yt(e){let t=Object.fromEntries(new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}function ec(e){let t=new Set;for(let r of e){t.add(r.startMs),t.add(r.endMs);for(let o=r.startMs;o<r.endMs;){let a=Date.parse(`${yt(new Date(o).toISOString())}T03:00:00.000Z`)+864e5;if(a>=r.endMs)break;t.add(a),o=a}}let n=[...t].sort((r,o)=>r-o),i=new Map;for(let r=0;r<n.length-1;r+=1){let o=n[r],a=n[r+1],s=e.filter(u=>u.startMs<a&&u.endMs>o);if(s.length===0||a<=o)continue;let l=(a-o)/s.length,c=yt(new Date(o).toISOString());for(let u of s){let d=`${u.activityRowId}:${c}`,p=i.get(d);i.set(d,{activityRowId:u.activityRowId,day:c,value:(p?.value??0)+l})}}return[...i.values()]}function Qe(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:yt(e)}function od(e,t){let n=e.map(i=>i[t]).filter(i=>typeof i=="number"&&Number.isFinite(i));return n.length===0?null:n.reduce((i,r)=>i+r,0)}function hv(e,t){let n=e.includes("/artifacts/evidence/")?"evidence":e.includes("/artifacts/validations/")||e.includes("/artifacts/tests/")?"validation":null;if(n===null)return null;let i=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t)?.[1]??"",r=a=>{let s=new RegExp(`^${a}:\\s*['"]?(.+?)['"]?\\s*$`,"m").exec(i)?.[1]?.trim();return s===void 0||s==="null"?null:s},o=r("observed_at")??r("executed_at")??r("created_at")??r("recorded_at");return o===null||Number.isNaN(Date.parse(o))?null:{kind:n,id:r("id")??e.slice(e.lastIndexOf("/")+1,-3),occurredAt:o,occurredDaySp:yt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}var Ev=".local/sqlite/zaip-aios-dashboard.sqlite",ri="73",kv=["zaip_aios_activities","zaip_dim_llm_model","zaip_dim_provider","zaip_dim_zaip_agent","cost_invocation_dimension_facts","cost_group_daily_projection","cost_group_entity_projection","developer_cost_projection","operations_work_projection"],cd=["zaip_activities_agent_run","zaip_activities_relationships","zaip_activities_task_day","zaip_activities_spec_day","zaip_activities_prd_day","zaip_activities_agent","zaip_activities_run_id","zaip_activities_run_hierarchy","zaip_activities_period","zaip_activities_period_invocation","zaip_activities_status","zaip_activities_payload","zaip_activities_work_item_identity","cost_dimension_facts_day_model","cost_dimension_facts_day_provider","cost_dimension_facts_invocation","cost_group_daily_projection_lookup","cost_group_entity_projection_lookup","developer_cost_projection_lookup"],Ov=["zaip_vw_read_model_metadata","zaip_vw_operations_overview","zaip_vw_cost_overview","zaip_vw_cost_models","zaip_vw_cost_providers","zaip_vw_operations_agent_invocations"],jV=2*36e5;function nc(e){return(0,ao.resolve)(process.env.ZAIP_SQLITE_DB_PATH??(0,ao.resolve)(e,Ev))}function ad(e){if(!(0,bv.existsSync)(e))return new Map;let t;try{t=new Lr.DatabaseSync(e,{readOnly:!0});let n=t.prepare("SELECT source_path, source_hash, mtime_ms, ctime_ms, size_bytes, file_identity FROM zaip_vw_read_model_source_state").all();return new Map(n.flatMap(i=>{let r=typeof i.source_path=="string"?i.source_path:null,o=typeof i.source_hash=="string"?i.source_hash:null,a=typeof i.file_identity=="string"?i.file_identity:null,s=typeof i.mtime_ms=="number"?i.mtime_ms:typeof i.mtime_ms=="string"?Number(i.mtime_ms):Number.NaN,l=typeof i.ctime_ms=="number"?i.ctime_ms:typeof i.ctime_ms=="string"?Number(i.ctime_ms):Number.NaN;return r===null||o===null||a===null||!Number.isFinite(s)||!Number.isFinite(l)||typeof i.size_bytes!="number"?[]:[[r,{source:r,mtimeMs:s,ctimeMs:l,size:i.size_bytes,contentHash:o,fileIdentity:a}]]}))}catch{return new Map}finally{t?.close()}}function tc(e){let t=new Lr.DatabaseSync(e,{readOnly:!0});try{let n=t.prepare("PRAGMA integrity_check").get();if(n.integrity_check!=="ok")throw new Error(`SQLite integrity check failed for ${e}: ${n.integrity_check??"unknown"}`);let i=t.prepare("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view', 'index')").all(),r=i.filter(d=>d.type==="table").map(d=>d.name).sort(),o=[...kv].sort();if(r.length!==o.length||r.some((d,p)=>d!==o[p]))throw new Error(`SQLite schema ${ri} requires the complete persisted table contract; found ${r.join(", ")||"none"}`);let a=new Set(i.map(d=>d.name)),s=Ov.filter(d=>!a.has(d));if(s.length>0)throw new Error(`SQLite schema is missing required views: ${s.join(", ")}`);let l=i.filter(d=>d.type==="view").map(d=>d.name);if(l.some(d=>!d.startsWith("zaip_vw_")))throw new Error("SQLite persisted views must use the zaip_vw_ namespace");let c=cd.filter(d=>!a.has(d));if(c.length>0)throw new Error(`SQLite schema is missing required indexes: ${c.join(", ")}`);let u=t.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = ?").get("schema_version")?.value;if(u!==ri)throw new Error(`SQLite schema version must be ${ri}; found ${u??"missing"}`);return{schemaVersion:u,tableCount:r.length,viewCount:l.length,indexCount:i.filter(d=>d.type==="index"&&!d.name.startsWith("sqlite_")).length}}finally{t.close()}}function vv(e){let t=e.prepare("SELECT name FROM sqlite_master WHERE type='index'").all(),n=new Set(t.map(i=>i.name));return cd.every(i=>n.has(i))&&Kh(e)}async function xP(e,t={}){let n=nc(e);if(t.preferExisting&&!t.forceCanonical)try{tc(n);let f=new Lr.DatabaseSync(n,{readOnly:!0});try{if(vv(f)){let S=f.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = 'source_file_count'").get();return{files:Number(S.value),path:n,cache:"stale_seed",fingerprint_ms:0,materialize_ms:0,refresh:{reused_sources:0,processed_sources:0,added_sources:0,changed_sources:0,removed_sources:0,canonical_runs_refolded:0}}}}finally{f.close()}}catch{}let i=ed,r=performance.now();i("source_fingerprint_started",8,"Inventariando fontes can\xF4nicas.");let o=await no(e,t.forceCanonical?{verifyContent:!0}:{previous:ad(n)}),a={reused_sources:o.reusedFiles,processed_sources:o.hashedFiles,added_sources:0,changed_sources:0,removed_sources:0,canonical_runs_refolded:0};i("source_fingerprint_ready",20,"Invent\xE1rio can\xF4nico conclu\xEDdo.");let s=`${o.fingerprint}
592
+ `)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function fv(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function Zt(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function io(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:zs(t,n,"")}function LP(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function MP(e){let t=e.flatMap(r=>{let o=r.source_started_at,a=r.source_finished_at,s=typeof o=="string"?Date.parse(o):Number.NaN,l=typeof a=="string"?Date.parse(a):Number.NaN;return typeof o=="string"&&typeof a=="string"&&Number.isFinite(s)&&Number.isFinite(l)&&l>s&&l-s<=nd?[{start:o,end:a,startMs:s,endMs:l}]:[]});if(t.length===0)return null;let n=t.reduce((r,o)=>o.startMs<r.startMs?o:r),i=t.reduce((r,o)=>o.endMs>r.endMs?o:r);return i.endMs-n.startMs<=nd?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function mv(e,t){let n=MP(e);if(n!==null)return{source:n.duration,effective:n.duration,provenance:"reconciled",sourceStartedAt:n.start,sourceFinishedAt:n.end};if(typeof t.finished?.duration_ms=="number"&&t.finished.duration_provenance!=="estimated"&&t.finished.duration_provenance!=="unavailable")return{source:t.finished.duration_ms,effective:t.finished.duration_ms,provenance:t.finished.duration_provenance??"observed",sourceStartedAt:null,sourceFinishedAt:null};let i=e.filter(LP);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=Ft(i.map(l=>l.duration_provenance))??"observed";return{source:a,effective:a,provenance:s,sourceStartedAt:null,sourceFinishedAt:null}}let r=Date.parse(t.run.occurred_at),o=typeof t.finished?.occurred_at=="string"?Date.parse(t.finished.occurred_at):Number.NaN;return Number.isFinite(r)&&Number.isFinite(o)&&o>r&&o-r<=nd?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function gv(e){return e.flatMap(t=>{try{return[Hy.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function id(e,t,n,i){let r=0,o=0,a=!1,s=!1,l=!1,c=[],u=[];for(let p of e){if(typeof p.cost.usd=="number"&&(r+=p.cost.usd,a=!0),typeof p.cost.brl=="number"&&(o+=p.cost.brl,s=!0),typeof p.cost.usd=="number"&&typeof p.cost.brl=="number"||p.tokens.total===null)continue;if(p.tokens.total===0){a=!0,s=!0;continue}let f=p.model??t.run.model;if(f===null||f==="unavailable")continue;let S=Fs({provider:io(p.provider,f,t.run.client),model:f,usage:p.tokens,catalog:n,fxRate:i,serviceTier:p.runtime?.service_tier??null});typeof p.cost.usd!="number"&&S.estimated_usd!==null&&(r+=S.estimated_usd,a=!0,l=!0),typeof p.cost.brl!="number"&&S.estimated_brl!==null&&(o+=S.estimated_brl,s=!0,l=!0),S.pricing_model!==null&&c.push(S.pricing_model),S.pricing_source!==null&&u.push(S.pricing_source)}let d=Zt(e,"total");return{usd:a?Math.round(r*1e6)/1e6:null,brl:s?Math.round(o*1e6)/1e6:null,method:d===0?"zero_no_llm_usage":l?"token_pricing_estimate":a||s?"canonical_recorded":null,pricingModel:Ft(c),pricingSource:Ft(u),fxRate:s?i?.rate??null:null}}function UP(e,t){if(t===null)return null;let n=t.toLowerCase(),i=r=>{let o=r.toLowerCase();if(n===o)return!0;let a=n.slice(o.length);return a.startsWith("@")||a.startsWith(":")||a.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(a)};return e.models.find(r=>i(r.id)||r.aliases.some(o=>i(o)))??null}function yv(e,t,n,i){let r=e.model??t.run.model,o=io(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=UP(n,r),l=r===null?null:Fs({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:Fs({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:"default"}),u=s?.long_context_threshold_tokens!==null&&s?.long_context_threshold_tokens!==void 0&&(e.tokens.input??0)>s.long_context_threshold_tokens,d=a==="priority"||a==="fast",p=d&&!u,f=s?p?s.priority_input_per_million_usd??null:s.input_per_million_usd:null,S=s?p?s.priority_cached_input_per_million_usd??null:s.cached_input_per_million_usd:null,h=s?p?s.priority_output_per_million_usd??null:s.output_per_million_usd:null,v=s?p?s.priority_reasoning_per_million_usd??s.priority_output_per_million_usd??null:s.reasoning_per_million_usd??s.output_per_million_usd:null,E=l?.estimated_usd!==null&&l!==null?l:c,U=E?.estimated_usd??null,F=c?.estimated_usd??null,q=e.cost.usd,V=q??U,ce=e.cost.brl??l?.estimated_brl??(V!==null&&i!==null?Math.round(V*i.rate*1e6)/1e6:null);return{provider:o,model:r,serviceTier:a,uncachedInputTokens:e.tokens.input===null?null:Math.max(e.tokens.input-(e.tokens.cached_input??0),0),visibleOutputTokens:e.tokens.output===null?null:Math.max(e.tokens.output-(e.tokens.reasoning??0),0),inputRate:f,cachedRate:S,outputRate:h,reasoningRate:v,contextInputMultiplier:s?u?s.long_context_input_multiplier:1:null,contextOutputMultiplier:s?u?s.long_context_output_multiplier:1:null,speedCostMultiplier:U!==null&&F!==null&&F>0?Math.round(U/F*1e3)/1e3:null,pricingScenario:d&&u?"standard_long_context_fallback":d?"priority":"standard",standardUsd:F,speedUpliftUsd:U!==null&&F!==null?Math.round((U-F)*1e6)/1e6:null,inputUsd:E?.input_usd??null,cachedInputUsd:E?.cached_input_usd??null,outputUsd:E?.output_usd??null,reasoningUsd:E?.reasoning_usd??null,calculatedUsd:U,recordedUsd:q,effectiveUsd:V,effectiveBrl:ce,varianceUsd:q!==null&&U!==null?Math.round((q-U)*1e6)/1e6:null,pricingModel:E?.pricing_model??null,pricingSource:E?.pricing_source??null,fxRate:e.cost.fx_rate??i?.rate??null}}function yt(e){let t=Object.fromEntries(new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}function ec(e){let t=new Set;for(let r of e){t.add(r.startMs),t.add(r.endMs);for(let o=r.startMs;o<r.endMs;){let a=Date.parse(`${yt(new Date(o).toISOString())}T03:00:00.000Z`)+864e5;if(a>=r.endMs)break;t.add(a),o=a}}let n=[...t].sort((r,o)=>r-o),i=new Map;for(let r=0;r<n.length-1;r+=1){let o=n[r],a=n[r+1],s=e.filter(u=>u.startMs<a&&u.endMs>o);if(s.length===0||a<=o)continue;let l=(a-o)/s.length,c=yt(new Date(o).toISOString());for(let u of s){let d=`${u.activityRowId}:${c}`,p=i.get(d);i.set(d,{activityRowId:u.activityRowId,day:c,value:(p?.value??0)+l})}}return[...i.values()]}function Qe(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:yt(e)}function od(e,t){let n=e.map(i=>i[t]).filter(i=>typeof i=="number"&&Number.isFinite(i));return n.length===0?null:n.reduce((i,r)=>i+r,0)}function hv(e,t){let n=e.includes("/artifacts/evidence/")?"evidence":e.includes("/artifacts/validations/")||e.includes("/artifacts/tests/")?"validation":null;if(n===null)return null;let i=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t)?.[1]??"",r=a=>{let s=new RegExp(`^${a}:\\s*['"]?(.+?)['"]?\\s*$`,"m").exec(i)?.[1]?.trim();return s===void 0||s==="null"?null:s},o=r("observed_at")??r("executed_at")??r("created_at")??r("recorded_at");return o===null||Number.isNaN(Date.parse(o))?null:{kind:n,id:r("id")??e.slice(e.lastIndexOf("/")+1,-3),occurredAt:o,occurredDaySp:yt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}var Ev=".local/sqlite/zaip-aios-dashboard.sqlite",ri="73",kv=["zaip_aios_activities","zaip_dim_llm_model","zaip_dim_provider","zaip_dim_zaip_agent","cost_invocation_dimension_facts","cost_group_daily_projection","cost_group_entity_projection","developer_cost_projection","operations_work_projection"],cd=["zaip_activities_agent_run","zaip_activities_relationships","zaip_activities_task_day","zaip_activities_spec_day","zaip_activities_prd_day","zaip_activities_agent","zaip_activities_run_id","zaip_activities_run_hierarchy","zaip_activities_period","zaip_activities_period_invocation","zaip_activities_status","zaip_activities_payload","zaip_activities_work_item_identity","cost_dimension_facts_day_model","cost_dimension_facts_day_provider","cost_dimension_facts_invocation","cost_group_daily_projection_lookup","cost_group_entity_projection_lookup","developer_cost_projection_lookup"],Ov=["zaip_vw_read_model_metadata","zaip_vw_operations_overview","zaip_vw_cost_overview","zaip_vw_cost_models","zaip_vw_cost_providers","zaip_vw_operations_agent_invocations"],FV=2*36e5;function nc(e){return(0,ao.resolve)(process.env.ZAIP_SQLITE_DB_PATH??(0,ao.resolve)(e,Ev))}function ad(e){if(!(0,bv.existsSync)(e))return new Map;let t;try{t=new Lr.DatabaseSync(e,{readOnly:!0});let n=t.prepare("SELECT source_path, source_hash, mtime_ms, ctime_ms, size_bytes, file_identity FROM zaip_vw_read_model_source_state").all();return new Map(n.flatMap(i=>{let r=typeof i.source_path=="string"?i.source_path:null,o=typeof i.source_hash=="string"?i.source_hash:null,a=typeof i.file_identity=="string"?i.file_identity:null,s=typeof i.mtime_ms=="number"?i.mtime_ms:typeof i.mtime_ms=="string"?Number(i.mtime_ms):Number.NaN,l=typeof i.ctime_ms=="number"?i.ctime_ms:typeof i.ctime_ms=="string"?Number(i.ctime_ms):Number.NaN;return r===null||o===null||a===null||!Number.isFinite(s)||!Number.isFinite(l)||typeof i.size_bytes!="number"?[]:[[r,{source:r,mtimeMs:s,ctimeMs:l,size:i.size_bytes,contentHash:o,fileIdentity:a}]]}))}catch{return new Map}finally{t?.close()}}function tc(e){let t=new Lr.DatabaseSync(e,{readOnly:!0});try{let n=t.prepare("PRAGMA integrity_check").get();if(n.integrity_check!=="ok")throw new Error(`SQLite integrity check failed for ${e}: ${n.integrity_check??"unknown"}`);let i=t.prepare("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view', 'index')").all(),r=i.filter(d=>d.type==="table").map(d=>d.name).sort(),o=[...kv].sort();if(r.length!==o.length||r.some((d,p)=>d!==o[p]))throw new Error(`SQLite schema ${ri} requires the complete persisted table contract; found ${r.join(", ")||"none"}`);let a=new Set(i.map(d=>d.name)),s=Ov.filter(d=>!a.has(d));if(s.length>0)throw new Error(`SQLite schema is missing required views: ${s.join(", ")}`);let l=i.filter(d=>d.type==="view").map(d=>d.name);if(l.some(d=>!d.startsWith("zaip_vw_")))throw new Error("SQLite persisted views must use the zaip_vw_ namespace");let c=cd.filter(d=>!a.has(d));if(c.length>0)throw new Error(`SQLite schema is missing required indexes: ${c.join(", ")}`);let u=t.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = ?").get("schema_version")?.value;if(u!==ri)throw new Error(`SQLite schema version must be ${ri}; found ${u??"missing"}`);return{schemaVersion:u,tableCount:r.length,viewCount:l.length,indexCount:i.filter(d=>d.type==="index"&&!d.name.startsWith("sqlite_")).length}}finally{t.close()}}function vv(e){let t=e.prepare("SELECT name FROM sqlite_master WHERE type='index'").all(),n=new Set(t.map(i=>i.name));return cd.every(i=>n.has(i))&&Kh(e)}async function xP(e,t={}){let n=nc(e);if(t.preferExisting&&!t.forceCanonical)try{tc(n);let f=new Lr.DatabaseSync(n,{readOnly:!0});try{if(vv(f)){let S=f.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = 'source_file_count'").get();return{files:Number(S.value),path:n,cache:"stale_seed",fingerprint_ms:0,materialize_ms:0,refresh:{reused_sources:0,processed_sources:0,added_sources:0,changed_sources:0,removed_sources:0,canonical_runs_refolded:0}}}}finally{f.close()}}catch{}let i=ed,r=performance.now();i("source_fingerprint_started",8,"Inventariando fontes can\xF4nicas.");let o=await no(e,t.forceCanonical?{verifyContent:!0}:{previous:ad(n)}),a={reused_sources:o.reusedFiles,processed_sources:o.hashedFiles,added_sources:0,changed_sources:0,removed_sources:0,canonical_runs_refolded:0};i("source_fingerprint_ready",20,"Invent\xE1rio can\xF4nico conclu\xEDdo.");let s=`${o.fingerprint}
593
593
  current_day=${yt(new Date().toISOString())}`,l=Math.round(performance.now()-r),c=cv(n,s,ri,vv);if(c!==null&&!t.forceCanonical&&o.hashedFiles===0)return tc(n),{files:c,path:n,cache:"generation",fingerprint_ms:l,materialize_ms:0,refresh:a};i("source_inventory",52,`Encontradas ${o.candidates.length} fontes can\xF4nicas.`),await(0,ic.mkdir)((0,ao.dirname)(n),{recursive:!0});let u=new Lr.DatabaseSync(n),d=0;try{u.exec("PRAGMA busy_timeout=180000; PRAGMA journal_mode=WAL; BEGIN IMMEDIATE;");try{o=await no(e,t.forceCanonical?{verifyContent:!0}:{previous:ad(n)}),a={reused_sources:o.reusedFiles,processed_sources:o.hashedFiles,added_sources:0,changed_sources:0,removed_sources:0,canonical_runs_refolded:0},s=`${o.fingerprint}
594
594
  current_day=${yt(new Date().toISOString())}`;let f=new Map((()=>{try{return u.prepare("SELECT path, content, content_sha256 FROM zaip_vw_files").all()}catch{return[]}})().map(m=>[m.path,m])),S=u.prepare("SELECT name, type FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'").all(),h=!t.forceCanonical&&kv.every(m=>S.some(C=>C.type==="table"&&C.name===m))&&cd.every(m=>S.some(C=>C.type==="index"&&C.name===m))&&Ov.every(m=>S.some(C=>C.type==="view"&&C.name===m))&&(()=>{try{let m=u.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key='schema_version'").get();return u.prepare("SELECT source_path, ctime_ms, file_identity FROM zaip_vw_read_model_source_state LIMIT 1").all(),m?.value===ri}catch{return!1}})(),v=new Map((()=>{try{return u.prepare("SELECT source_path, source_hash FROM zaip_vw_read_model_source_state").all()}catch{return[]}})().map(m=>[m.source_path,m.source_hash]));a={...a,added_sources:o.candidates.filter(m=>!v.has(m.source)).length,changed_sources:o.candidates.filter(m=>{let C=v.get(m.source);return C!==void 0&&C!==m.contentHash}).length,removed_sources:[...v.keys()].filter(m=>!o.candidates.some(C=>C.source===m)).length};let E=o.candidates.filter(m=>v.get(m.source)!==m.contentHash),U=[...v.keys()].filter(m=>!o.candidates.some(C=>C.source===m));if(h&&E.length===0&&U.length===0){let m=u.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key='source_fingerprint'").get(),C=ad(n);for(let L of o.candidates){let Ie=C.get(L.source);Ie&&(Ie.mtimeMs!==L.mtimeMs||Ie.ctimeMs!==L.ctimeMs||Ie.fileIdentity!==L.fileIdentity)&&u.prepare(`UPDATE zaip_aios_activities SET payload_json=json_set(payload_json,'$.mtime_ms',?,'$.ctime_ms',?,'$.file_identity',?,'$.size_bytes',?)
595
595
  WHERE payload_type='source_state' AND activity_key=?`).run(String(L.mtimeMs),String(L.ctimeMs),L.fileIdentity,L.size,`source_state:${L.source}`)}return u.prepare("UPDATE zaip_aios_activities SET payload_json=json_set(payload_json,'$.value',?) WHERE payload_type='metadata' AND activity_key='metadata:source_fingerprint'").run(s),m.value.split(`