@zaip-ai/cli 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/services/adapter-hook-sources.d.ts +1 -0
- package/dist/services/adapter-hook-sources.d.ts.map +1 -1
- package/dist/services/adapter-hook-sources.js +1 -0
- package/dist/services/adapter-hook-sources.js.map +1 -1
- package/dist/services/adapters.d.ts +1 -1
- package/dist/services/adapters.d.ts.map +1 -1
- package/dist/services/adapters.js +17 -19
- package/dist/services/adapters.js.map +1 -1
- package/dist/services/adapters.test.js +1 -0
- package/dist/services/adapters.test.js.map +1 -1
- package/dist/services/codex-config-template.d.ts +2 -2
- package/dist/services/codex-config-template.d.ts.map +1 -1
- package/dist/services/codex-config-template.js +4 -3
- package/dist/services/codex-config-template.js.map +1 -1
- package/dist/services/codex-pre-tool-hook-template.d.ts.map +1 -1
- package/dist/services/codex-pre-tool-hook-template.js +23 -55
- package/dist/services/codex-pre-tool-hook-template.js.map +1 -1
- package/dist/services/codex-pre-tool-hook-template.test.d.ts +2 -0
- package/dist/services/codex-pre-tool-hook-template.test.d.ts.map +1 -0
- package/dist/services/codex-pre-tool-hook-template.test.js +95 -0
- package/dist/services/codex-pre-tool-hook-template.test.js.map +1 -0
- package/dist/services/codex-pre-tool-support-template.d.ts +2 -0
- package/dist/services/codex-pre-tool-support-template.d.ts.map +1 -0
- package/dist/services/codex-pre-tool-support-template.js +110 -0
- package/dist/services/codex-pre-tool-support-template.js.map +1 -0
- package/dist/services/codex-subagent-hook-template.d.ts +1 -1
- package/dist/services/codex-subagent-hook-template.d.ts.map +1 -1
- package/dist/services/codex-subagent-hook-template.js +40 -8
- package/dist/services/codex-subagent-hook-template.js.map +1 -1
- package/dist/services/codex-windows-hook-command.d.ts +3 -0
- package/dist/services/codex-windows-hook-command.d.ts.map +1 -0
- package/dist/services/codex-windows-hook-command.js +12 -0
- package/dist/services/codex-windows-hook-command.js.map +1 -0
- package/dist/services/codex-windows-hook-command.test.d.ts +2 -0
- package/dist/services/codex-windows-hook-command.test.d.ts.map +1 -0
- package/dist/services/codex-windows-hook-command.test.js +44 -0
- package/dist/services/codex-windows-hook-command.test.js.map +1 -0
- package/dist/services/developer-identity-fixture.d.ts +3 -0
- package/dist/services/developer-identity-fixture.d.ts.map +1 -0
- package/dist/services/developer-identity-fixture.js +17 -0
- package/dist/services/developer-identity-fixture.js.map +1 -0
- package/dist/services/global-codex-config.d.ts.map +1 -1
- package/dist/services/global-codex-config.js +27 -13
- package/dist/services/global-codex-config.js.map +1 -1
- package/dist/services/global-codex-config.test.js +27 -2
- package/dist/services/global-codex-config.test.js.map +1 -1
- package/dist/services/runtime-template.test.js +3 -0
- package/dist/services/runtime-template.test.js.map +1 -1
- package/package.json +1 -1
- package/templates/.agents/config/agents/discovery.json +1 -1
- package/templates/.agents/dashboard/.zaip-managed.json +14 -14
- package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
- package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
- package/templates/.agents/dashboard/modules/operations/package.json +1 -1
- package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
- package/templates/.agents/dashboard/packages/branding/package.json +1 -1
- package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
- package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +141 -141
- package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +2 -2
- package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/server.mjs +141 -141
- package/templates/.agents/dashboard/packages/ui/package.json +1 -1
- package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
- package/templates/.agents/design/.zaip-managed.json +3 -3
- package/templates/.agents/design/apps/catalog/package.json +1 -1
- package/templates/.agents/design/packages/local-runtime/package.json +1 -1
- package/templates/.agents/requirements/autonomous-assurance.md +1 -1
- package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
- package/templates/.agents/requirements/comparative-audit.md +1 -1
- package/templates/.agents/requirements/context-engine.md +1 -1
- package/templates/.agents/requirements/cost-observability.md +1 -1
- package/templates/.agents/requirements/dashboard-launch.md +1 -1
- package/templates/.agents/requirements/data-export.md +1 -1
- package/templates/.agents/requirements/design-system.md +1 -1
- package/templates/.agents/requirements/execution-engine.md +1 -1
- package/templates/.agents/requirements/kanban-dashboard.md +1 -1
- package/templates/.agents/requirements/model-orchestration.md +1 -1
- package/templates/.agents/requirements/public-distribution.md +1 -1
- package/templates/.agents/requirements/software-architecture.md +1 -1
- package/templates/.agents/requirements/strategic-improvements.md +1 -1
- package/templates/.agents/requirements/work-lifecycle.md +1 -1
- package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
- package/templates/.agents/runtime/VERSION +1 -1
- package/templates/.agents/runtime/bin/zaip.mjs +206 -98
- package/templates/.agents/runtime/checksums.sha256 +5 -5
- package/templates/.agents/runtime/manifest.json +1 -1
- package/templates/.agents/runtime/provenance.json +4 -4
- package/templates/.agents/runtime/sbom.cdx.json +1 -1
- package/templates/.agents/zaip-aios/VERSION +1 -1
- package/templates/template-manifest.json +45 -45
|
@@ -705,7 +705,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
705
705
|
total_output_tokens, total_reasoning_tokens, total_tokens, total_cost_usd,
|
|
706
706
|
total_cost_brl FROM grouped ORDER BY total_cost_brl DESC, group_value LIMIT ? OFFSET ?
|
|
707
707
|
) SELECT totals.*, paged.* FROM totals LEFT JOIN paged ON 1
|
|
708
|
-
ORDER BY paged.total_cost_brl DESC, paged.id`).all(...E,h,S),T=x[0];if(!T)throw new Error("Canonical macro query did not return its aggregate row.");let R=Number(T.__entity_count),V={entity_count:T.__entity_count,invocation_count:T.__invocation_count,total_duration:T.__total_duration,total_tokens:T.__total_tokens,total_cost_usd:T.__total_cost_usd,total_cost_brl:T.__total_cost_brl},G=x.filter(U=>U.__row_present===1).map(U=>Object.fromEntries(Object.entries(U).filter(([_e])=>!_e.startsWith("__"))));return{data_source:"sqlite_read_model",view:t,offset:S,limit:h,total_count:R,has_more:S+G.length<R,totals:V,rows:G}}if(!!(n.provider||n.model||n.agent||n.phase||n.status||n.origin||n.workType||n.priority||n.risk)){let s={task:"i.task_id",spec:"i.spec_id",prd:"i.prd_id",execution:"i.execution_id",conversation:"i.conversation_id"}[i],l=i==="task"?"tasks":i==="spec"?"specs":i==="prd"?"prds":null,c=[`${s} IS NOT NULL`],u=[];n.from&&(c.push("i.occurred_day_sp >= ?"),u.push(n.from.slice(0,10))),n.to&&(c.push("i.occurred_day_sp <= ?"),u.push(n.to.slice(0,10))),n.agent&&(c.push("i.zaip_agent = ?"),u.push(n.agent)),n.phase&&(c.push("i.phase = ?"),u.push(n.phase)),n.status&&(c.push(l==="specs"||l==="prds"?"COALESCE(entity.status, i.status) = ?":"COALESCE(task_entity.status, i.status) = ?"),u.push(n.status)),n.risk&&(c.push("task_entity.risk = ?"),u.push(n.risk)),n.origin&&c.push(n.origin==="prd"?"i.prd_id IS NOT NULL":n.origin==="spec"?"i.prd_id IS NULL AND i.spec_id IS NOT NULL":n.origin==="task"?"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NOT NULL":"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NULL"),n.workType&&(c.push("i.work_type = ?"),u.push(n.workType)),n.priority&&(c.push("task_entity.priority = ?"),u.push(n.priority));let d=[];n.provider&&(n.provider==="unavailable"?c.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_provider WHERE known_provider.agent_invocation_id=i.agent_invocation_id AND known_provider.provider IS NOT NULL AND known_provider.provider <> 'unavailable')"):(d.push("u.provider = ?"),u.push(n.provider))),n.model&&(n.model==="unavailable"?c.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_model WHERE known_model.agent_invocation_id=i.agent_invocation_id AND known_model.model IS NOT NULL AND known_model.model <> 'unavailable')"):(d.push("u.model = ?"),u.push(n.model))),d.length>0&&c.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=i.agent_invocation_id AND ${d.join(" AND ")})`),n.query&&(c.push(l===null?`${s} LIKE ?`:`(${s} LIKE ? OR COALESCE(entity.title, '') LIKE ?)`),u.push(`%${n.query}%`,...l===null?[]:[`%${n.query}%`]));let f=`${l===null?"":`LEFT JOIN ${l} entity ON entity.id=${s}`} LEFT JOIN tasks task_entity ON task_entity.id=i.task_id`,g=c.join(" AND "),h=l===null?s:`COALESCE(MAX(entity.title), ${s})`,E=`WITH grouped AS (SELECT ${s} AS group_value, ${h} AS title, ${l===null?"NULL":"MAX(entity.status)"} AS status, MAX(task_entity.risk) AS risk, MAX(i.occurred_at) AS occurred_at, COUNT(*) AS invocation_count, SUM(i.duration_ms) AS total_duration, SUM(i.total_tokens) AS total_tokens, SUM(i.cost_usd) AS total_cost_usd, SUM(i.cost_brl) AS total_cost_brl FROM invocations i ${f} WHERE ${g} GROUP BY ${s})`,x=Math.min(200,Math.max(1,n.limit??50)),T=Math.max(0,n.offset??0),R=Number(e.database.prepare(`${E} SELECT COUNT(*) AS count FROM grouped`).get(...u).count),V=e.database.prepare(`${E} SELECT COUNT(*) AS entity_count, COALESCE(SUM(invocation_count), 0) AS invocation_count, ROUND(SUM(total_duration)) AS total_duration, SUM(total_tokens) AS total_tokens, SUM(total_cost_usd) AS total_cost_usd, SUM(total_cost_brl) AS total_cost_brl FROM grouped`).get(...u),G=e.database.prepare(`${E} SELECT group_value AS id, group_value AS key, title, status, risk, occurred_at, invocation_count, total_duration, total_tokens, total_cost_usd, total_cost_brl FROM grouped ORDER BY total_cost_brl DESC, group_value LIMIT ? OFFSET ?`).all(...u,x,T);return{data_source:"sqlite_read_model",view:t,offset:T,limit:x,total_count:R,has_more:T+G.length<R,totals:V,rows:G}}return lb(e.database,t,i,n)}function Vc(e,t){let n=e.length;return{tasks:qc(e.map(i=>i.task_count),n),specs:qc(e.map(i=>i.spec_count),n),prds:qc(e.map(i=>i.prd_count),n),durationMs:qc(e.map(i=>i.duration_ms),n),tokens:db(e.map(i=>i.total_tokens)),cost:db(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function db(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function qc(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}var Po={"2026-08-02":4809511,"2026-08-01":8894527,"2026-07-31":9472804,"2026-07-30":5167818,"2026-07-29":11336221,"2026-07-28":8262282,"2026-07-27":4862150,"2026-07-26":970899,"2026-07-25":7465970,"2026-07-24":9041538,"2026-07-23":19750,"2026-07-22":1371560,"2026-07-21":14992543,"2026-07-20":3168460,"2026-07-19":929990,"2026-07-18":9232700,"2026-07-17":16882853,"2026-07-16":20054785,"2026-07-15":35459620,"2026-07-14":24078852,"2026-07-13":22611635,"2026-07-12":8339738,"2026-07-11":1859980},Wc={cutoff:"2026-08-02T03:14:00.000Z",cutoffDay:"2026-08-02",durationMs:Object.values(Po).reduce((e,t)=>e+t,0),costXlsxSha256:"C3EE0495667289FB81DD8F9268697CEB7692433C14CB19934C89B5F39129902A",operationsXlsxSha256:"94E9577A7CA27F7FDD277D81E34156296CB28FE39CF6D7636B259EBBB7E56BCC"},CZ=76*36e5;var fe=Ie(Ne(),1);var qt=Ie(Ne(),1);var w=Ie(Ne(),1);var zt=Ie(Ne(),1),wU=zt.z.string().datetime({offset:!0}).or(zt.z.string().datetime()),_b=zt.z.object({schema_version:zt.z.literal(2),event_id:zt.z.string().min(1).max(200),run_id:zt.z.string().startsWith("RUN-"),sequence:zt.z.number().int().positive(),occurred_at:wU,type:zt.z.literal("run.attribution.recovered"),phase:zt.z.literal("execution"),execution_id:zt.z.string().startsWith("EXEC-"),task_id:zt.z.string().startsWith("TASK-"),change_id:zt.z.string().startsWith("CHG-")}).strict();function pb(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 r_(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 i_(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 Zc(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 _t=Ie(Ne(),1),mb=_t.z.string().datetime({offset:!0}).or(_t.z.string().datetime()),AU=_t.z.string().regex(/^DEC-(?:HUMAN|AI)-/),TU=_t.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation","rollback"]),i6=_t.z.object({schema_version:_t.z.literal(2),id:AU,title:_t.z.string().min(1),scope_type:_t.z.enum(["change","execution"]),scope_id:_t.z.string().min(1),origin:_t.z.enum(["human","agent"]),category:TU,context:_t.z.string().min(1),decision:_t.z.string().min(1),reason:_t.z.string().min(1),alternatives:_t.z.array(_t.z.string().min(1)),consequences:_t.z.array(_t.z.string().min(1)),reversible:_t.z.boolean(),rollback:_t.z.string().min(1),confidence:_t.z.number().min(0).max(1).nullable(),created_at:mb,confirmed_at:mb.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 Lt=w.z.string().datetime({offset:!0}).or(w.z.string().datetime()),Bc=w.z.enum(["conversation","planning","execution"]),Hc=w.z.string().startsWith("RUN-"),$U=w.z.string().startsWith("CONV-"),fb=w.z.string().startsWith("EXEC-").nullable(),gb=w.z.string().startsWith("TASK-").nullable(),yb=w.z.string().startsWith("SPEC-").nullable(),hb=w.z.string().startsWith("PRD-").nullable(),vb=w.z.string().startsWith("CHG-").nullable(),o_=Hc.nullable(),Br=w.z.string().regex(/^(?:AINV|INV)-/).max(200),bb=w.z.string().startsWith("MCALL-").max(200),d6=w.z.enum(["intake","orchestrator","subagent"]),LU=w.z.enum(["intake","orchestrator","subagent","owner","contributor"]),Sb=w.z.enum(["intake","orchestration","execution","review","audit","finalization"]),kb=w.z.enum(["none","minimal","low","medium","high","xhigh","max","ultra"]),Uo=w.z.object({schema_version:w.z.literal(1),provider:w.z.literal("github"),account_id:w.z.string().min(1).max(100),login_snapshot:w.z.string().min(1).max(100),attribution_source:w.z.enum(["verified_local_account","last_verified_local_account","cached_fallback","human_assigned"]),verified_at:Lt.nullable(),expires_at:Lt.nullable().optional(),last_verified_at:Lt.nullable().optional()}).strict();var Eb=w.z.enum(["orchestrator","delegated"]);var a_=w.z.object({input:w.z.number().int().nonnegative().nullable(),cached_input:w.z.number().int().nonnegative().nullable(),cache_write_input:w.z.number().int().nonnegative().nullable().optional(),output:w.z.number().int().nonnegative().nullable(),reasoning:w.z.number().int().nonnegative().nullable(),total:w.z.number().int().nonnegative().nullable(),source:w.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"})}),wb=w.z.object({usd:w.z.number().nonnegative().nullable(),brl:w.z.number().nonnegative().nullable(),fx_rate:w.z.number().positive().nullable().optional()}).strict(),Hr={schema_version:w.z.literal(2),event_id:w.z.string().min(1).max(200),run_id:Hc,sequence:w.z.number().int().positive(),occurred_at:Lt},MU=w.z.object({intent:w.z.enum(["conversation","continue","refine","rework","new_work"]),classification_source:w.z.enum(["agent","explicit","fallback"]),confidence:w.z.number().min(0).max(1),reason_codes:w.z.array(w.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(12)}).strict(),Ab=w.z.object({...Hr,type:w.z.literal("run.started"),attribution_status:w.z.enum(["attributed","legacy_unattributed"]),developer_identity:Uo.nullable().optional(),phase:Bc,run_role:LU.optional(),run_purpose:Sb.optional(),requires_finalizer:w.z.boolean().optional(),execution_kind:w.z.enum(["interaction","delivery"]).optional(),execution_eligibility:w.z.array(w.z.enum(["interaction","delivery"])).optional(),direct_execution_authorization:w.z.string().trim().min(1).max(1e3).optional(),entrypoint:w.z.enum(["conversation","task","spec","prd"]),work_type:w.z.enum(["new","rework"]),storage_mode:w.z.enum(["tracked_sanitized","local_only"]),client:w.z.string().min(1).max(100),agent:w.z.string().min(1).max(100),agent_name:w.z.string().min(1).max(100).nullable().optional(),agent_identity_warning:w.z.object({code:w.z.literal("deprecated-agent-identity"),kind:w.z.enum(["id","codex_name","codex_task_name"]),requested:w.z.string().min(1),canonical_id:w.z.string().min(1),deprecated_at:w.z.iso.date(),remove_after:w.z.iso.date()}).strict().optional(),provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200),reasoning_effort:kb.nullable().optional(),client_thread_id:w.z.string().min(1).max(200).nullable().optional(),client_turn_id:w.z.string().min(1).max(200).nullable().optional(),conversation_id:$U,execution_id:fb,task_id:gb,spec_id:yb,prd_id:hb,change_id:vb,parent_run_id:o_,continuation_of_run_id:o_,retry_of_run_id:o_,agent_invocation_id:Br.optional(),root_agent_invocation_id:Br.optional(),parent_agent_invocation_id:Br.nullable().optional(),invocation_kind:Eb.optional(),delegation_depth:w.z.number().int().nonnegative().optional(),intake:MU.nullable().optional()}).strict().superRefine((e,t)=>{e.direct_execution_authorization!==void 0&&(e.execution_kind!=="delivery"||e.agent!=="agent-orchestrator"||e.run_role!=="orchestrator"||e.parent_run_id!==null||e.task_id===null||e.change_id===null||e.execution_id===null||!e.client_thread_id||!e.client_turn_id||e.client_turn_id.startsWith("local-")||["unknown","unavailable","manual"].includes(e.model))&&t.addIssue({code:"custom",path:["direct_execution_authorization"],message:"Direct execution requires an observed Task-scoped delivery root and explicit authorization"}),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`})}),Tb=w.z.object({...Hr,type:w.z.literal("usage.recorded"),phase:Bc,activity_kind:w.z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),classification_source:w.z.enum(["explicit","current_context","default","legacy_inferred"]),tokens:a_,cost:wb,provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),source_segment_key:w.z.string().min(1).max(500).nullable(),attributed_spec_id:w.z.string().min(1).max(200).nullable().optional(),model_call_id:bb.nullable().optional(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict().optional(),supersedes_event_id:w.z.string().min(1).max(200).nullable(),retrospective_correction:w.z.literal(!0).optional(),source_occurred_at:Lt.optional(),source_started_at:Lt.optional(),source_finished_at:Lt.optional(),duration_ms:w.z.number().int().nonnegative().nullable().optional(),duration_provenance:w.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().optional(),context_stats:w.z.object({initial_pack_tokens:w.z.number().int().nonnegative().nullable(),tool_output_tokens:w.z.number().int().nonnegative().nullable(),files_opened:w.z.number().int().nonnegative().nullable(),snippets_opened:w.z.number().int().nonnegative().nullable()}).strict().optional()}).strict(),Ob=w.z.object({...Hr,type:w.z.literal("model.call.observed"),call_id:bb,agent_invocation_id:Br,coverage:w.z.enum(["complete","partial","unavailable"]),tokens:a_,cost:wb,provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),source_call_key:w.z.string().min(1).max(500).nullable(),source_occurred_at:Lt.optional(),source_started_at:Lt.optional(),source_finished_at:Lt.optional(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict().optional()}).strict(),xb=w.z.object({schema_version:w.z.literal(1),run_id:Hc,execution_id:fb.nullable().default(null),task_id:gb.nullable().default(null),spec_id:yb.nullable().default(null),prd_id:hb.nullable().default(null),change_id:vb.nullable().default(null),developer_identity:Uo.nullable().optional(),zaip_agent:w.z.string().min(1).max(100).nullable().default(null),phase:Bc.nullable().default(null),purpose:Sb.nullable().default(null),agent_invocation_id:Br,root_agent_invocation_id:Br,parent_agent_invocation_id:Br.nullable(),invocation_kind:Eb,delegation_depth:w.z.number().int().nonnegative(),client:w.z.enum(["codex","codex-desktop","codex-subagent"]),thread_id:w.z.string().min(1).max(200).nullable(),turn_id:w.z.string().min(1).max(200).nullable(),agent_path:w.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"})}),Rb=w.z.object({correlation:xb,event_kind:w.z.enum(["response","usage","terminal","error"]),source:w.z.enum(["codex_app_server","codex_session_fallback","unavailable"]),source_event_key:w.z.string().min(1).max(500),source_method:w.z.enum(["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"]).optional(),stream_boundary:w.z.enum(["item_completed","response_completed","usage_updated","error","turn_completed"]).optional(),source_occurred_at:Lt.nullable(),captured_at:Lt,coverage:w.z.enum(["complete","partial","unavailable"]),tokens:a_.nullable(),provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict(),status:w.z.enum(["completed","failed","cancelled"]).nullable(),will_retry:w.z.boolean().nullable().optional(),latency_ms:w.z.number().int().nonnegative().nullable(),historical_cost:w.z.object({estimated_usd:w.z.number().nonnegative().nullable(),estimated_brl:w.z.number().nonnegative().nullable(),fx_rate:w.z.number().positive().nullable(),pricing_model:w.z.string().nullable(),pricing_source:w.z.string().nullable(),pricing_source_url:w.z.string().url().nullable().optional(),pricing_catalog_updated_at:Lt.nullable().optional(),input_usd:w.z.number().nonnegative().nullable(),cached_input_usd:w.z.number().nonnegative().nullable(),cache_write_input_usd:w.z.number().nonnegative().nullable().optional(),output_usd:w.z.number().nonnegative().nullable(),reasoning_usd:w.z.number().nonnegative().nullable()}).strict().nullable().optional(),context_stats:w.z.object({initial_pack_tokens:w.z.number().int().nonnegative().nullable(),tool_output_tokens:w.z.number().int().nonnegative().nullable(),files_opened:w.z.number().int().nonnegative().nullable(),snippets_opened:w.z.number().int().nonnegative().nullable()}).strict().nullable(),discarded_counts:w.z.object({prompt:w.z.number().int().nonnegative(),response_text:w.z.number().int().nonnegative(),reasoning:w.z.number().int().nonnegative(),secrets:w.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"})}),Ib=w.z.object({schema_version:w.z.literal(1),event_id:w.z.string().startsWith("CEVT-").max(200),checksum_sha256:w.z.string().regex(/^[a-f0-9]{64}$/),compaction:w.z.object({status:w.z.enum(["pending","compacted"]),compacted_at:Lt.nullable()}).strict(),event:Rb}).strict(),Cb=w.z.string().startsWith("INV-").max(200),Nb=w.z.object({...Hr,type:w.z.literal("model.selection.recorded"),invocation_id:Cb,requested:w.z.object({model:w.z.string().min(1).max(200),reasoning_effort:w.z.enum(["low","medium","high","xhigh"]).nullable(),velocity:w.z.literal("standard")}).strict(),selection:w.z.object({source:w.z.enum(["execution-override","task-override","auto-policy","project-default"]),policy_version:w.z.number().int().positive(),reasons:w.z.array(w.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(20)}).strict()}).strict(),$b=w.z.object({...Hr,type:w.z.literal("provider.invocation.finished"),invocation_id:Cb,status:w.z.enum(["completed","failed","cancelled"]),effective:w.z.object({provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),reasoning_effort:kb.nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict(),latency_ms:w.z.number().int().nonnegative().nullable()}).strict(),Lb=w.z.object({...Hr,type:w.z.literal("run.finished"),phase:Bc,status:w.z.enum(["completed","failed","cancelled"]),duration_ms:w.z.number().int().nonnegative().nullable().default(null),duration_provenance:w.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().default(null)}).strict(),PU=w.z.object({...Hr,type:w.z.literal("run.finalization.decided"),finalizer_run_id:Hc,outcome:w.z.enum(["completed","blocked","failed","cancelled"]),summary:w.z.string().min(1).max(4e3),evidence_ids:w.z.array(w.z.string().min(1).max(200)).max(100),changed_files:w.z.array(w.z.string().min(1).max(500)).max(1e4).default([])}).strict(),Fo=w.z.discriminatedUnion("type",[Ab,Tb,Ob,Nb,$b,_b,PU,Lb]);var Mb=".local/codex-telemetry-spool/v1",DU=`${Mb}/events`,h6=`${Mb}/events.index.json`;var v6=64*1024,b6=64*1024*1024;var jU=qt.z.object({path:qt.z.string().startsWith(`${DU}/`).endsWith(".json"),stat:qt.z.object({dev:qt.z.string(),ino:qt.z.string(),size:qt.z.string(),mtime_ns:qt.z.string(),ctime_ns:qt.z.string()}).strict(),envelope:Ib}).strict(),S6=qt.z.object({schema_version:qt.z.literal(1),events:qt.z.array(jU),checksum_sha256:qt.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var Vt=Ie(Ne(),1);var UU=Vt.z.object({run_id:Vt.z.string().startsWith("RUN-"),path:Vt.z.string().startsWith(".agents/records/runs/"),content_sha256:Vt.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),FU=Vt.z.object({schema_version:Vt.z.literal(1),manifest_id:Vt.z.string().min(1),created_at:Vt.z.string().datetime({offset:!0}),kind:Vt.z.literal("historical_developer_attribution"),assignment:Uo.extend({attribution_source:Vt.z.literal("human_assigned")}),source_streams:Vt.z.array(UU).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)}),w6=FU.extend({manifest_hash:Vt.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var O6=1440*60*1e3;function qb(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(!Vb(i,r))throw new Error(`Divergent duplicate source segment: ${i.source_segment_key}`)}return n}function Vb(e,t){return JSON.stringify(zb(e))===JSON.stringify(zb(t))}function zb(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 Wb(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=Fo.parse(Array.isArray(o)?t(o,i):o);i??=a.run_id,n.push(a)}return n}function Zb(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 Jc(e){return Wb(e,GU)}function Gc(e){let t=new Map;for(let h of e){let S=Fo.parse(h),E=t.get(S.event_id);if(E!==void 0){if(JSON.stringify(E)!==JSON.stringify(S))throw new Error(`Divergent duplicate Run V2 event: ${S.event_id}`);continue}t.set(S.event_id,S)}let n=[...t.values()].sort((h,S)=>h.sequence-S.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[h,S]of n.entries()){if(S.run_id!==i.run_id)throw new Error("Run V2 stream mixes run ids");if(S.sequence!==h+1)throw new Error("Run V2 sequence must be contiguous");let E=l.get(S.sequence);if(E!==void 0&&E!==S.event_id)throw new Error(`Run V2 sequence is duplicated: ${S.sequence}`);if(l.set(S.sequence,S.event_id),h>0&&S.type==="run.started")throw new Error("Run V2 has multiple starts");if(o!==null&&S.type!=="run.finalization.decided"&&!i_(S,o,c))throw new Error("Run V2 contains a non-retrospective record after run.finished");if(S.type==="usage.recorded"){if(Zc(r,S.phase),S.phase==="execution"&&i.execution_id===null&&i.attribution_status!=="legacy_unattributed")throw new Error("Execution phase requires execution_id");if(S.supersedes_event_id!==null&&!c.has(S.supersedes_event_id))throw new Error(`Superseded usage event must occur earlier: ${S.supersedes_event_id}`);c.set(S.event_id,S),r=S.phase}if(S.type==="run.attribution.recovered"){if(!pb(i,S))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");Zc(r,S.phase),r=S.phase,s=S}if(S.type==="model.selection.recorded"){if(Zb(i,n.slice(0,h),{invocationId:S.invocation_id,requested:S.requested,selection:S.selection}),u.has(S.invocation_id))throw new Error(`Duplicate model selection for invocation: ${S.invocation_id}`);u.set(S.invocation_id,S)}if(S.type==="provider.invocation.finished"){if(!u.has(S.invocation_id))throw new Error(`Provider invocation requires earlier model selection: ${S.invocation_id}`);if(d.has(S.invocation_id))throw new Error(`Duplicate provider terminal for invocation: ${S.invocation_id}`);d.set(S.invocation_id,S)}if(S.type==="model.call.observed"){let x=p.get(S.call_id);if(x!==void 0&&JSON.stringify(x)!==JSON.stringify(S)&&!r_(x,S))throw new Error(`Divergent duplicate Model Call: ${S.call_id}`);p.set(S.call_id,S)}if(S.type==="run.finalization.decided"){if(a!==null)throw new Error("Run V2 has multiple finalization decisions");a=S}if(S.type==="run.finished"){if(S.phase!==r)throw new Error("run.finished phase must match the latest phase");o=S}}let m=n.filter(h=>h.type==="usage.recorded"),f=new Set(m.map(h=>h.supersedes_event_id).filter(h=>h!==null)),g=qb(m.filter(h=>!f.has(h.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:m,effective_usage_records:g,model_selection_records:[...u.values()],provider_invocation_records:[...d.values()],model_call_records:[...p.values()]}}function GU(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],m=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],...d[6]===void 0?{}:{cache_write_input:d[6]}},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]},...m===null||!Array.isArray(m)?{}:{runtime:{reasoning_effort:m[0],service_tier:m[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],...n[6]===void 0?{}:{cache_write_input:n[6]}},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 Kc=fe.z.string().datetime({offset:!0}),KU=fe.z.preprocess(e=>e==="client"?"provider_reported":e,fe.z.enum(["provider_reported","estimated","unavailable"])),pB=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:Kc,confirmed_at:Kc.nullable()}).strict();var mB=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:Kc,finished_at:Kc.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:KU}),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 De=Ie(Ne(),1);function nn(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 bB=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}),SB=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"});var Hb=".agents/records/lifecycle/views",CB=`${Hb}/manifest.json`;var Jr=".agents/records/lifecycle",c4=`${Jr}/manifest.json`,l4=`${Jr}/entity-snapshot.json`,u4=`${Jr}/entity-state.json`,d4=`${Jr}/indexes`;var _4=`${Jr}/summary.json`,p4=`${Jr}/overview.json`,m4=`${Jr}/active-work.json`;var Gb=De.z.enum(["prd","spec","change","task","execution","run","decision","validation","evidence"]),f4=Gb.options,YU=De.z.enum(["parent","child","references","evidence","requirement"]),QU=De.z.enum(["explicit","derived"]),e1=De.z.object({target_id:De.z.string().min(1),type:YU,direction:De.z.enum(["outbound","inbound"]),provenance:QU,source_locator:De.z.string().min(1).nullable().default(null)}).strict(),t1=De.z.object({input_tokens:De.z.number().int().nonnegative().nullable().default(null),output_tokens:De.z.number().int().nonnegative().nullable().default(null),cached_input_tokens:De.z.number().int().nonnegative().nullable().default(null),total_tokens:De.z.number().int().nonnegative().nullable().default(null),cost:De.z.number().nonnegative().nullable().default(null),currency:De.z.string().min(1).nullable().default(null)}).strict(),n1=De.z.object({kind:Gb,id:De.z.string().min(1),title:De.z.string().min(1).nullable().default(null),status:De.z.string().min(1).nullable().default(null),risk:De.z.string().min(1).nullable().default(null),priority:De.z.string().min(1).nullable().default(null),updated_at:De.z.string().datetime({offset:!0}),relations:De.z.array(De.z.string().min(1)).default([]),relation_edges:De.z.array(e1).optional(),usage:t1.nullable().default(null),data:De.z.record(De.z.string(),De.z.unknown()).nullable().default(null)}).strict(),g4=De.z.object({schema_version:De.z.literal(1),event_id:De.z.string().min(1),occurred_at:De.z.string().datetime({offset:!0}),operation:De.z.enum(["upsert","remove"]),entity:n1}).strict();var ot=Ie(Ne(),1);var s_=["objective","requirement_ids","acceptance_ids","write_scopes"],E4={simple:{level:"simple",requiredFields:[...s_,"verification"],optionalFields:["risk_notes","rollback"],maximumUnresolvedQuestions:0},standard:{level:"standard",requiredFields:[...s_,"included_scope","excluded_scope","design","risks","verification","rollback"],optionalFields:["rollout","open_questions"],maximumUnresolvedQuestions:2},complex:{level:"complex",requiredFields:[...s_,"problem","outcomes","included_scope","excluded_scope","architecture","security","dag","budgets","risks","rollout","rollback","verification","independent_reviewer"],optionalFields:["open_questions"],maximumUnresolvedQuestions:3}};var re=Ie(Ne(),1);var xe=Ie(Ne(),1),Xc=xe.z.enum(["test","eval","check","review","spec_review","quality_review","mutation","integration","cross_spec_e2e"]),Kb=xe.z.object({schema_version:xe.z.literal(2),assurance_version:xe.z.literal(1),profile:xe.z.enum(["task-lite","task-standard-2","task-standard-3","task-critical"]),risk:xe.z.enum(["lite","standard","critical"]),minimum_validation_artifacts:xe.z.number().int().positive(),maximum_validation_artifacts:xe.z.number().int().positive().nullable(),minimum_evidence_artifacts:xe.z.number().int().positive(),maximum_evidence_artifacts:xe.z.number().int().positive().nullable(),minimum_distinct_modalities:xe.z.number().int().positive(),complete_acceptance_coverage:xe.z.literal(!0),evidence_per_acceptance:xe.z.boolean(),requires_independent_verifier:xe.z.boolean(),requires_mutation_discrimination:xe.z.boolean(),minimum_mutation_kill_ratio:xe.z.number().min(0).max(1).nullable(),requires_rollback:xe.z.boolean(),requires_final_commit_evidence:xe.z.boolean(),requires_test:xe.z.boolean(),required_modalities:xe.z.array(Xc)}).strict().superRefine((e,t)=>{e.maximum_validation_artifacts!==null&&e.maximum_validation_artifacts<e.minimum_validation_artifacts&&t.addIssue({code:"custom",path:["maximum_validation_artifacts"],message:"maximum validation artifacts cannot be lower than the minimum"}),e.maximum_evidence_artifacts!==null&&e.maximum_evidence_artifacts<e.minimum_evidence_artifacts&&t.addIssue({code:"custom",path:["maximum_evidence_artifacts"],message:"maximum Evidence artifacts cannot be lower than the minimum"})});var x4=xe.z.object({schema_version:xe.z.literal(2),assurance_version:xe.z.literal(1),profile:xe.z.enum(["spec-delivery","prd-delivery"]),origin:xe.z.enum(["spec","prd"]),minimum_parent_validation_artifacts:xe.z.number().int().positive(),minimum_parent_evidence_artifacts:xe.z.number().int().positive(),minimum_distinct_modalities:xe.z.number().int().positive(),complete_acceptance_coverage:xe.z.literal(!0),requires_acceptance_matrix:xe.z.literal(!0),requires_independent_verifier:xe.z.literal(!0),integration_modality:xe.z.enum(["integration","cross_spec_e2e"]),evidence_per_acceptance:xe.z.boolean(),evidence_per_outcome:xe.z.boolean(),requires_mutation_discrimination:xe.z.boolean(),minimum_mutation_kill_ratio:xe.z.number().min(0).max(1).nullable(),requires_rollback:xe.z.boolean(),requires_final_commit_evidence:xe.z.boolean(),required_modalities:xe.z.array(Xc).min(3)}).strict();var Ei=re.z.string().datetime({offset:!0}),zo=re.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/).nullable(),c_=Cr(re.z.string().startsWith("AC-")).min(1),r1=re.z.object({kind:re.z.literal("isolated_git_worktree"),protocol:re.z.literal("committed_node_harness_v1").optional(),harness_path:re.z.string().min(1).optional(),harness_blob_sha:zo.unwrap().optional(),commit_sha:zo.unwrap(),tree_sha:zo.unwrap(),exit_code:re.z.number().int().min(-1),diagnostic:re.z.string().nullable().optional(),started_at:Ei,finished_at:Ei}).strict(),Xb={test:"TEST-",eval:"EVAL-",check:"CHECK-",review:"REVIEW-",spec_review:"REVIEW-SPEC-",quality_review:"REVIEW-QUALITY-",mutation:"MUT-",integration:"INT-",cross_spec_e2e:"E2E-"},C4=re.z.object({schema_version:re.z.literal(2),id:re.z.string().min(1),kind:Xc,task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,executed_at:Ei,command:re.z.string().min(1).nullable(),status:re.z.enum(["passed","failed","not_applicable"]),asserted_outcomes:Cr(re.z.string().min(1)).min(1),locators:Cr(re.z.string().min(1)).min(1),author_id:re.z.string().min(1),commit_sha:zo,candidate_execution:r1.nullable().optional(),not_applicable_reason:re.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{e.id.startsWith(Xb[e.kind])||t.addIssue({code:"custom",path:["id"],message:`${e.kind} validation id must start with ${Xb[e.kind]}`}),!c1(e.kind)&&e.command===null&&t.addIssue({code:"custom",path:["command"],message:`${e.kind} validation requires its executed command`}),Yb(e.status,e.not_applicable_reason,t),e.candidate_execution!==null&&e.candidate_execution!==void 0&&(Date.parse(e.candidate_execution.finished_at)<Date.parse(e.candidate_execution.started_at)&&t.addIssue({code:"custom",path:["candidate_execution","finished_at"],message:"isolated validation cannot finish before it starts"}),e.commit_sha!==e.candidate_execution.commit_sha&&t.addIssue({code:"custom",path:["candidate_execution","commit_sha"],message:"isolated candidate execution must match validation commit"}),e.status==="passed"&&e.candidate_execution.exit_code!==0&&t.addIssue({code:"custom",path:["status"],message:"a non-zero isolated candidate exit code cannot pass validation"}))}),N4=re.z.object({schema_version:re.z.literal(2),id:re.z.string().startsWith("EVD-"),task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,outcome_ids:Cr(re.z.string().startsWith("OUT-")).default([]),validation_artifact_ids:Cr(re.z.string().min(1)).min(1),observed_at:Ei,status:re.z.enum(["passed","not_applicable"]),summary:re.z.string().min(1),locators:Cr(re.z.string().min(1)).min(1),commit_sha:zo,not_applicable_reason:re.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{Yb(e.status,e.not_applicable_reason,t)}),i1=re.z.enum(["confirmed","limited","pending","failed","not_applicable"]),o1=re.z.enum(["visual","interaction","api","database_schema","persistence","logs","integration"]),a1=re.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),$4=re.z.object({schema_version:re.z.literal(1),id:re.z.string().regex(/^OBS-[A-Z0-9]+(?:-[A-Z0-9]+)*$/),task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,proof_kind:o1,state:i1,scenario:re.z.string().min(1).nullable(),expected:re.z.string().min(1).nullable(),observed:re.z.string().min(1).nullable(),observed_at:Ei,examiner_id:re.z.string().min(1),commit_sha:a1.nullable(),candidate_version:re.z.string().min(1).nullable(),environment:re.z.object({class:re.z.string().min(1).nullable(),id:re.z.string().min(1).nullable(),version:re.z.string().min(1).nullable()}).strict(),visual:re.z.object({url:re.z.string().url(),viewport:re.z.string().regex(/^\d{2,5}x\d{2,5}$/),captured_at:Ei,loaded_version:re.z.string().min(1),examination:re.z.string().min(1)}).strict().nullable(),correlation_ids:Cr(re.z.string().min(1)).default([]),locators:Cr(re.z.string().min(1)).default([]),limitations:re.z.string().min(1).nullable(),not_applicable_reason:re.z.string().min(1).nullable(),pending_reason:re.z.string().min(1).nullable(),dependency:re.z.string().min(1).nullable(),resume_plan:re.z.string().min(1).nullable(),attempts:re.z.array(re.z.object({kind:re.z.enum(["initial","retry","alternative"]),recovery_action:re.z.string().min(1).nullable(),alternative_available:re.z.boolean().nullable()}).strict()).max(3)}).strict().superRefine((e,t)=>{let n=e.attempts.map(i=>i.kind);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["attempts"],message:"observations allow each attempt kind at most once"}),e.state!=="pending"&&e.state!=="not_applicable"&&n[0]!=="initial"&&t.addIssue({code:"custom",path:["attempts"],message:"settled observations require an initial attempt"}),n.join(",")!==[...n].sort(s1).join(",")&&t.addIssue({code:"custom",path:["attempts"],message:"observation attempts must be initial, retry, then alternative"});for(let[i,r]of e.attempts.entries())r.kind==="retry"&&(i===0||r.recovery_action===null)&&t.addIssue({code:"custom",path:["attempts",i],message:"retry observations require a preceding initial attempt and recovery_action"}),r.kind==="alternative"&&r.alternative_available!==!0&&t.addIssue({code:"custom",path:["attempts",i,"alternative_available"],message:"alternative observations require an available permitted mechanism"});if(e.state==="not_applicable"&&e.not_applicable_reason===null&&t.addIssue({code:"custom",path:["not_applicable_reason"],message:"not_applicable observations require a reason"}),e.state!=="not_applicable"&&e.not_applicable_reason!==null&&t.addIssue({code:"custom",path:["not_applicable_reason"],message:"applicable observations cannot retain a not-applicable reason"}),e.proof_kind!=="visual"&&e.visual!==null&&t.addIssue({code:"custom",path:["visual"],message:"only visual observations may include visual metadata"}),e.proof_kind==="visual"&&e.state==="confirmed"&&e.visual===null&&t.addIssue({code:"custom",path:["visual"],message:"confirmed visual observations require visual examination metadata"}),e.visual!==null){let i;try{i=new URL(e.visual.url)}catch{t.addIssue({code:"custom",path:["visual","url"],message:"visual URL must be a sanitized http(s) URL"});return}(i.protocol!=="http:"&&i.protocol!=="https:"||i.username||i.password||i.search||i.hash)&&t.addIssue({code:"custom",path:["visual","url"],message:"visual URL must be http(s) without credentials or query"})}e.state==="confirmed"&&e.locators.length===0&&t.addIssue({code:"custom",path:["locators"],message:"confirmed observations require locators"}),e.state==="confirmed"&&(e.candidate_version===null||e.environment.version===null)&&t.addIssue({code:"custom",path:["candidate_version"],message:"confirmed observations require observed candidate and environment versions"}),e.state==="confirmed"&&e.proof_kind==="integration"&&e.correlation_ids.length===0&&t.addIssue({code:"custom",path:["correlation_ids"],message:"confirmed integration observations require scenario correlation"}),e.state==="limited"&&e.limitations===null&&t.addIssue({code:"custom",path:["limitations"],message:"limited observations require a limitation"}),e.state==="pending"&&(e.pending_reason===null||e.dependency===null||e.resume_plan===null)&&t.addIssue({code:"custom",path:["pending_reason"],message:"pending observations require reason, dependency, and resume plan"}),e.state!=="pending"&&e.commit_sha===null&&t.addIssue({code:"custom",path:["commit_sha"],message:"settled observations require candidate commit"}),e.state!=="pending"&&(e.environment.class===null||e.environment.id===null)&&t.addIssue({code:"custom",path:["environment"],message:"settled observations require an identified environment"}),e.state!=="pending"&&(e.scenario===null||e.expected===null||e.observed===null)&&t.addIssue({code:"custom",message:"settled observations require scenario, expected, and observed"}),e.proof_kind==="visual"&&e.state==="confirmed"&&(e.candidate_version===null||e.visual===null||e.visual.loaded_version!==e.candidate_version)&&t.addIssue({code:"custom",path:["candidate_version"],message:"confirmed visual observations require candidate and loaded versions to agree"})});function Cr(e){return re.z.array(e).superRefine((t,n)=>{let i=new Set;for(let[r,o]of t.entries())i.has(o)&&n.addIssue({code:"custom",path:[r],message:`duplicate value: ${o}`}),i.add(o)})}function s1(e,t){return{initial:0,retry:1,alternative:2}[e]-{initial:0,retry:1,alternative:2}[t]}function Yb(e,t,n){e==="not_applicable"&&t===null&&n.addIssue({code:"custom",path:["not_applicable_reason"],message:"not-applicable artifacts require a reason"}),e!=="not_applicable"&&t!==null&&n.addIssue({code:"custom",path:["not_applicable_reason"],message:"applicable artifacts cannot retain a not-applicable reason"})}function c1(e){return e==="review"||e==="spec_review"||e==="quality_review"}var J=Ie(Ne(),1);var Qb=require("node:crypto");function eS(e){return(0,Qb.createHash)("sha256").update(JSON.stringify(l_(e))).digest("hex")}function l_(e){return Array.isArray(e)?e.map(l_):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,l_(n)])):e}var tS=Ie(Ne(),1),Yc=tS.z.string().min(1).superRefine((e,t)=>{(e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||/^[A-Za-z]:/.test(e)||e.split("/").some(n=>n.length===0||n==="."||n===".."))&&t.addIssue({code:"custom",message:"write_scope must be workspace-relative"})});var Wt=Ie(Ne(),1),l1=Wt.z.string().min(1).superRefine((e,t)=>{(e.toLowerCase()==="latest"||/[<>=~^*|,\s]/.test(e)||/(?:^|[.-])[xX](?:$|[.-])/.test(e))&&t.addIssue({code:"custom",message:"Expected an exact resolved version, not a range, wildcard, or moving tag"})}),u1=Wt.z.string().min(1).superRefine((e,t)=>{(e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||/^[A-Za-z]:/.test(e)||e.split("/").some(n=>n.length===0||n==="."||n===".."))&&t.addIssue({code:"custom",message:"version_source must be a canonical workspace-relative file path"})}),d1=Wt.z.object({name:Wt.z.string().min(1),kind:Wt.z.enum(["language","runtime","framework","library","persistence","database","tooling","platform"]),version:l1,version_source:u1}).strict(),Qc=Wt.z.object({stack_profile:Wt.z.string().min(1),stack_overrides:Wt.z.record(Wt.z.string(),Wt.z.unknown()),stack_description:Wt.z.string().min(20),stack_components:Wt.z.array(d1).min(1)}).strict().superRefine((e,t)=>{e.stack_components.some(i=>i.kind==="language")||t.addIssue({code:"custom",path:["stack_components"],message:"SPEC implementation requires at least one exact programming language"});let n=e.stack_description.toLocaleLowerCase("en");for(let[i,r]of e.stack_components.entries())(!n.includes(r.name.toLocaleLowerCase("en"))||!n.includes(r.version.toLocaleLowerCase("en")))&&t.addIssue({code:"custom",path:["stack_components",i],message:`stack_description must mention ${r.name} ${r.version}`})});var sn=Ie(Ne(),1),Rt=sn.z.string().datetime({offset:!0}),wi=sn.z.string().regex(/^[a-f0-9]{64}$/),Gr=sn.z.string().startsWith("PRD-"),Nr=sn.z.string().startsWith("SPEC-"),Ai=sn.z.string().startsWith("CHG-"),At=sn.z.string().startsWith("TASK-"),Ti=sn.z.string().startsWith("EXEC-"),$r=sn.z.string().startsWith("REQ-"),Kr=sn.z.string().startsWith("AC-"),nS=sn.z.string().startsWith("OUT-");var Oi=J.z.enum(["lite","standard","critical"]),_1=J.z.enum(["low","medium","high","urgent"]),Vo=J.z.object({revision:J.z.number().int().positive(),hash:wi,execution_id:Ti}).strict();var xi=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("task"),task_id:At}).strict(),J.z.object({type:J.z.literal("spec"),spec_id:Nr}).strict(),J.z.object({type:J.z.literal("prd"),prd_id:Gr}).strict()]),u_=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("task"),task_id:At}).strict(),J.z.object({type:J.z.literal("spec"),spec_id:Nr}).strict(),J.z.object({type:J.z.literal("prd"),prd_id:Gr,spec_id:Nr.nullable()}).strict()]),d_=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("none"),reason:J.z.string().min(1)}).strict(),J.z.object({type:J.z.literal("update"),requirement_ids:J.z.array($r).min(1)}).strict()]),iS=J.z.object({model:Os,reasoning_effort:sg,velocity:eu.optional()}).strict(),oS=iS.extend({client:J.z.string().min(1),provider:J.z.string().min(1)}).strict(),el=J.z.object({failure_policy:J.z.enum(["stop_on_terminal_failure","continue_independent"]),max_parallelism:J.z.number().int().positive(),independent_branches:J.z.boolean().optional(),max_cost_usd:J.z.number().nonnegative().nullable().optional(),max_operational_retries:J.z.number().int().nonnegative(),max_repair_cycles_per_task:J.z.number().int().nonnegative(),soft_model_cycle_budget:J.z.number().int().positive().optional(),soft_input_token_budget:J.z.number().int().positive().optional(),context_refresh_after_cycles:J.z.number().int().positive().optional(),verification_mode:J.z.enum(["scoped","full"]).optional(),runtime_defaults:oS.optional()}).strict(),__=el.extend({runtime_defaults:oS.extend({model:J.z.union([Os,J.z.enum(["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"])])}).optional()}),aS=J.z.string().regex(/^[a-z][a-z0-9-]*$/),sS=J.z.object({key:aS,id:Ai,title:J.z.string().min(1),short_name:J.z.string().min(1),risk:Oi,source:u_,requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),requirement_impact:d_}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t)}),cS=J.z.object({id:Nr,title:J.z.string().min(1),short_name:J.z.string().min(1),objective:J.z.string().min(1),summary:J.z.string().min(1),risk:Oi,included_scope:J.z.array(Yc).min(1),excluded_scope:J.z.array(Yc),requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),implementation:Qc,rollout:J.z.string().min(1),fallback:J.z.string().min(1),model_signals:Cs}).strict().superRefine((e,t)=>{Zt(e.included_scope,"included_scope",t),Zt(e.excluded_scope,"excluded_scope",t),Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t)}),lS={key:aS,id:At,change_id:Ai,title:J.z.string().min(1),short_name:J.z.string().min(1),objective:J.z.string().min(1),priority:_1,owner:J.z.string().min(1).nullable(),requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),write_scopes:J.z.array(Yc),runtime:iS.optional()},p1=J.z.object({...lS,risk:Oi,model_profile:jr.optional()}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t),Zt(e.write_scopes,"write_scopes",t)}),m1=J.z.object({...lS,risk:Oi.optional(),model_signals:Cs.optional(),model_profile:jr.optional()}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t),Zt(e.write_scopes,"write_scopes",t)}),uS=J.z.object({task_id:At,depends_on:J.z.array(At)}).strict().superRefine((e,t)=>{e.depends_on.includes(e.task_id)&&t.addIssue({code:"custom",path:["depends_on"],message:"self dependency"}),Zt(e.depends_on,"depends_on",t)}),f1=J.z.object({revision:J.z.number().int().positive(),source:xi,execution_id:Ti,prepared_at:Rt,policy:el,blueprints:J.z.object({specs:J.z.array(cS).min(1).optional(),changes:J.z.array(sS).min(1),tasks:J.z.array(m1).min(1)}).strict(),dag:J.z.object({nodes:J.z.array(uS).min(1)}).strict()}).strict(),g1=f1.extend({schema_version:J.z.literal(2),policy:__,blueprints:J.z.object({specs:J.z.array(cS).min(1).optional(),changes:J.z.array(sS).min(1),tasks:J.z.array(p1).min(1)}).strict(),dag:J.z.object({nodes:J.z.array(uS).min(1),topological_order:J.z.array(At).min(1)}).strict(),hash:wi}).strict(),Ri=g1.superRefine((e,t)=>{for(let n of dS(e))t.addIssue({code:"custom",path:[...n.path],message:n.message})});function dS(e){let t=[],n=new Map(e.blueprints.changes.map(c=>[c.id,c])),i=new Map(e.blueprints.tasks.map(c=>[c.id,c])),r=new Map((e.blueprints.specs??[]).map(c=>[c.id,c]));qo(e.blueprints.changes.map(c=>c.key),"duplicate-key",["blueprints","changes"],t),qo((e.blueprints.specs??[]).map(c=>c.id),"duplicate-id",["blueprints","specs"],t),qo(e.blueprints.tasks.map(c=>c.key),"duplicate-key",["blueprints","tasks"],t),qo([...e.blueprints.changes,...e.blueprints.tasks].map(c=>c.id),"duplicate-id",["blueprints"],t);for(let[c,u]of e.blueprints.tasks.entries()){u.model_profile!==void 0&&u.risk!==u.model_profile.risk&&t.push({rule:"risk-classification",path:["blueprints","tasks",c,"risk"],message:`Task risk ${u.risk} does not match classified risk ${u.model_profile.risk}`});let d=n.get(u.change_id);if(d===void 0){t.push({rule:"missing-change",path:["blueprints","tasks",c,"change_id"],message:`${u.change_id} does not resolve`});continue}for(let p of u.requirement_ids)d.requirement_ids.includes(p)||t.push({rule:"requirement-outside-change",path:["blueprints","tasks",c,"requirement_ids"],message:`${p} is absent from ${d.id}`});for(let p of u.acceptance_ids)d.acceptance_ids.includes(p)||t.push({rule:"acceptance-outside-change",path:["blueprints","tasks",c,"acceptance_ids"],message:`${p} is absent from ${d.id}`})}for(let[c,u]of e.blueprints.changes.entries())[...i.values()].some(d=>d.change_id===u.id)||t.push({rule:"change-without-task",path:["blueprints","changes",c],message:`${u.id} has no task`}),v1(e.source,u.source)||t.push({rule:"source-mismatch",path:["blueprints","changes",c,"source"],message:`${u.id} source does not match the prepared plan source`}),e.source.type==="prd"&&u.source.type==="prd"&&u.source.spec_id===null&&t.push({rule:"prd-change-without-spec",path:["blueprints","changes",c,"source","spec_id"],message:`${u.id} must belong to a SPEC of ${e.source.prd_id}`}),e.source.type==="prd"&&u.source.type==="prd"&&u.source.spec_id!==null&&e.blueprints.specs!==void 0&&!r.has(u.source.spec_id)&&t.push({rule:"missing-spec-blueprint",path:["blueprints","changes",c,"source","spec_id"],message:`${u.source.spec_id} requires a composite SPEC blueprint`});if(e.blueprints.specs!==void 0&&e.source.type==="prd"){let c=e.source.prd_id,u=new Set(e.blueprints.changes.flatMap(p=>p.source.type==="prd"&&p.source.prd_id===c?[p.source.spec_id]:[]));for(let[p,m]of e.blueprints.specs.entries()){u.has(m.id)||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"id"],message:`${m.id} has no PRD Change`});for(let f of m.requirement_ids)e.blueprints.changes.some(g=>g.source.type==="prd"&&g.source.spec_id===m.id&&g.requirement_ids.includes(f))||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"requirement_ids"],message:`${f} is not used by ${m.id}`});for(let f of m.acceptance_ids)e.blueprints.changes.some(g=>g.source.type==="prd"&&g.source.spec_id===m.id&&g.acceptance_ids.includes(f))||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"acceptance_ids"],message:`${f} is not used by ${m.id}`})}let d=new Map(e.blueprints.tasks.map(p=>{let m=n.get(p.change_id);return[p.id,m?.source.type==="prd"?m.source.spec_id:null]}));for(let[p,m]of e.dag.nodes.entries())for(let f of m.depends_on){let g=d.get(m.task_id),h=d.get(f);g!==null&&h!==null&&g!==h&&t.push({rule:"cross-spec-dependency",path:["dag","nodes",p,"depends_on"],message:`${m.task_id} crosses SPEC boundary; compose it into one SPEC instead`})}for(let p=0;p<e.blueprints.specs.length;p+=1)for(let m=p+1;m<e.blueprints.specs.length;m+=1){let f=e.blueprints.specs[p],g=e.blueprints.specs[m];if(f===void 0||g===void 0)continue;let h=f.included_scope.find(S=>g.included_scope.some(E=>rS(S,E)));h!==void 0&&t.push({rule:"overlapping-spec-scope",path:["blueprints","specs"],message:`${f.id} and ${g.id} overlap at ${h}; compose them into one SPEC`})}}e.source.type==="spec"&&e.blueprints.specs!==void 0&&(e.blueprints.specs.length!==1||e.blueprints.specs[0]?.id!==e.source.spec_id)&&t.push({rule:"missing-spec-blueprint",path:["blueprints","specs"],message:`SPEC plan must contain exactly its source blueprint ${e.source.spec_id}`}),e.source.type==="task"&&!i.has(e.source.task_id)&&t.push({rule:"missing-task",path:["source","task_id"],message:`${e.source.task_id} does not resolve`});let o=new Map(e.dag.nodes.map(c=>[c.task_id,c]));qo(e.dag.nodes.map(c=>c.task_id),"duplicate-id",["dag","nodes"],t);for(let c of i.values())o.has(c.id)||t.push({rule:"missing-task",path:["dag","nodes"],message:`${c.id} is missing from the DAG`});for(let[c,u]of e.dag.nodes.entries()){i.has(u.task_id)||t.push({rule:"missing-task",path:["dag","nodes",c,"task_id"],message:`${u.task_id} does not resolve`});for(let d of u.depends_on)d===u.task_id?t.push({rule:"self-dependency",path:["dag","nodes",c,"depends_on"],message:`${u.task_id} depends on itself`}):i.has(d)||t.push({rule:"missing-dependency",path:["dag","nodes",c,"depends_on"],message:`${d} does not resolve`})}let a=y1(e.dag.nodes);if(a.length!==i.size?t.push({rule:"cycle",path:["dag"],message:"DAG contains a cycle"}):JSON.stringify(a)!==JSON.stringify(e.dag.topological_order)&&t.push({rule:"topological-order",path:["dag","topological_order"],message:"topological_order is not canonical"}),a.length===i.size){let c=h1(e.dag.nodes),u=[...i.values()];for(let d=0;d<u.length;d+=1)for(let p=d+1;p<u.length;p+=1){let m=u[d],f=u[p];if(m===void 0||f===void 0)continue;let g=m.write_scopes.find(S=>f.write_scopes.some(E=>rS(S,E)));if(g===void 0)continue;c.get(m.id)?.has(f.id)===!0||c.get(f.id)?.has(m.id)===!0||t.push({rule:"overlapping-write-scope",path:["blueprints","tasks"],message:`${m.id} and ${f.id} may overlap at ${g}; add a DAG dependency`})}}let{hash:s,...l}=e;return eS(l)!==e.hash&&t.push({rule:"hash",path:["hash"],message:"prepared plan hash does not match"}),t}function y1(e){let t=new Set(e.map(a=>a.task_id)),n=new Map(e.map(a=>[a.task_id,0])),i=new Map;for(let a of e)for(let s of new Set(a.depends_on))!t.has(s)||s===a.task_id||(n.set(a.task_id,(n.get(a.task_id)??0)+1),i.set(s,[...i.get(s)??[],a.task_id]));let r=[...n].filter(([,a])=>a===0).map(([a])=>a).sort(),o=[];for(;r.length>0;){let a=r.shift();o.push(a);for(let s of(i.get(a)??[]).sort()){let l=(n.get(s)??0)-1;n.set(s,l),l===0&&(r.push(s),r.sort())}}return o}function h1(e){let t=new Map(e.map(r=>[r.task_id,r.depends_on])),n=new Map,i=(r,o)=>{let a=n.get(r);if(a!==void 0)return a;if(o.has(r))return new Set;let s=new Set;for(let l of t.get(r)??[]){s.add(l);for(let c of i(l,new Set([...o,r])))s.add(c)}return n.set(r,s),s};for(let r of t.keys())i(r,new Set);return n}function rS(e,t){if(e===t)return!0;let n=e.search(/[*?]/),i=t.search(/[*?]/);if(n===-1&&i===-1)return!1;let r=e.slice(0,n===-1?e.length:n).replace(/\/$/,""),o=t.slice(0,i===-1?t.length:i).replace(/\/$/,"");return r===o||r.startsWith(`${o}/`)||o.startsWith(`${r}/`)}function v1(e,t){return e.type!==t.type?!1:e.type==="task"&&t.type==="task"?e.task_id===t.task_id:e.type==="spec"&&t.type==="spec"?e.spec_id===t.spec_id:e.type==="prd"&&t.type==="prd"&&e.prd_id===t.prd_id}function qo(e,t,n,i){let r=new Set;for(let o of e)r.has(o)&&i.push({rule:t,path:n,message:`Duplicate value: ${o}`}),r.add(o)}function Zt(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var F=Ie(Ne(),1);var b1=F.z.object({schema_version:F.z.literal(2),id:Gr,revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","ready","active","delivered","blocked","failed","cancelled"]),status_reason:F.z.string().min(1).nullable().default(null),outcome_status:F.z.enum(["unmeasured","measuring","met","not_met","inconclusive"]),problem:F.z.string().min(1),audiences:F.z.array(F.z.string().min(1)),outcomes:F.z.array(F.z.string().min(1)),outcome_ids:F.z.array(nS),constraints:F.z.array(F.z.string().min(1)),non_goals:F.z.array(F.z.string().min(1)),prepared_plan:Ri.nullable(),plan_ref:Vo.nullable().default(null),creation_run_id:F.z.string().startsWith("RUN-").nullable().default(null),rework_of_prd_id:Gr.nullable().default(null),tags:F.z.array(F.z.string().min(1)).default([]),created_at:Rt,updated_at:Rt}).strict().superRefine((e,t)=>{e.prepared_plan!==null&&e.plan_ref!==null&&t.addIssue({code:"custom",message:"PRD cannot contain prepared_plan and plan_ref"}),e.outcome_ids.length!==e.outcomes.length&&t.addIssue({code:"custom",path:["outcome_ids"],message:"PRD outcome_ids must identify every declared outcome exactly once"}),new Set(e.outcome_ids).size!==e.outcome_ids.length&&t.addIssue({code:"custom",path:["outcome_ids"],message:"PRD outcome_ids must be unique"})}),S1=F.z.preprocess(I1,b1),k1=F.z.object({schema_version:F.z.literal(2),id:Nr,prd_id:Gr.nullable(),revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","ready","active","delivered","blocked","failed","cancelled"]),status_reason:F.z.string().min(1).nullable().default(null),objective:F.z.string().min(1),included_scope:F.z.array(F.z.string().min(1)),excluded_scope:F.z.array(F.z.string().min(1)),requirement_ids:F.z.array($r),acceptance_ids:F.z.array(Kr),implementation:Qc.nullable().default(null),prepared_plan:Ri.nullable(),plan_ref:Vo.nullable().default(null),creation_run_id:F.z.string().startsWith("RUN-").nullable().default(null),created_at:Rt,updated_at:Rt}).strict().superRefine((e,t)=>{e.prepared_plan!==null&&e.plan_ref!==null&&t.addIssue({code:"custom",message:"SPEC cannot contain prepared_plan and plan_ref"})}),_S=F.z.object({schema_version:F.z.literal(2),id:Ai,revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:F.z.string().min(1).nullable().optional(),risk:Oi,source:u_,requirement_ids:F.z.array($r).min(1),acceptance_ids:F.z.array(Kr).min(1),requirement_impact:d_,task_ids:F.z.array(At).min(1),plan_revision:F.z.number().int().positive().nullable(),plan_hash:wi.nullable(),created_at:Rt,updated_at:Rt,started_at:Rt.nullable(),finished_at:Rt.nullable(),result:F.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||(e.status==="blocked"||e.status==="cancelled")&&n?n||t.addIssue({code:"custom",message:"draft Change cannot contain a prepared plan"}):(n||e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Change requires plan_revision and plan_hash`}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Change requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Change requires started_at`})}),Wo=F.z.object({task_id:At,change_id:Ai,depends_on:F.z.array(At)}).strict(),E1=F.z.object({max_total_invocations:F.z.number().int().positive().nullable(),cancelled:F.z.boolean().default(!1),finalizer_scope:F.z.enum(["spec","parent"]).default("spec")}).strict(),w1=F.z.record(Nr,E1).optional(),Zo={schema_version:F.z.literal(2),id:Ti,parent_execution_id:Ti.nullable().optional(),revision:F.z.number().int().positive(),status:F.z.enum(["planned","running","paused","verifying","completed","failed","blocked","cancelled"]),status_reason:F.z.string().min(1).nullable().optional(),policy:__,spec_execution_policies:w1,created_at:Rt,updated_at:Rt,started_at:Rt.nullable(),finished_at:Rt.nullable(),result:F.z.string().min(1).nullable()},A1=F.z.object({...Zo,kind:F.z.literal("delivery").optional(),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,plan_revision:F.z.number().int().positive(),plan_hash:wi,dag:F.z.object({nodes:F.z.array(Wo).min(1),topological_order:F.z.array(At).min(1)}).strict()}).strict(),T1=F.z.object({...Zo,kind:F.z.literal("delivery"),client_turn_id:F.z.string().min(1).max(200),origin:xi,status:F.z.enum(["planned","blocked"]),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),O1=F.z.object({...Zo,kind:F.z.literal("delivery"),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,status:F.z.literal("cancelled"),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),x1=F.z.object({...Zo,kind:F.z.literal("interaction"),client_turn_id:F.z.string().min(1).max(200),origin:F.z.object({type:F.z.literal("interaction"),conversation_id:F.z.string().startsWith("CONV-")}).strict(),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),R1=F.z.object({...Zo,kind:F.z.literal("interaction"),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),p_=F.z.union([x1,R1,O1,T1,A1]).superRefine((e,t)=>{e.status==="blocked"&&e.status_reason==null&&t.addIssue({code:"custom",message:"blocked Execution requires status_reason"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Execution requires finished_at and result"}),["running","paused","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Execution requires started_at`})});function I1(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Object.hasOwn(t,"outcome_ids")||typeof t.id!="string"||!Array.isArray(t.outcomes)?e:{...t,outcome_ids:pS(t.id,t.outcomes)}}function pS(e,t){let n=e.replace(/^PRD-/,"OUT-");return t.map((i,r)=>`${n}-${String(r+1).padStart(2,"0")}`)}var N1=["lite","standard","critical"],tl=ot.z.string().datetime({offset:!0}),zH=ot.z.object({id:ot.z.string().startsWith("SPEC-"),capability:ot.z.string().min(1),title:ot.z.string().min(1),status:ot.z.enum(["active","deprecated"]).default("active"),version:ot.z.number().int().positive().default(1),updated_at:tl}).strict();var qH=ot.z.object({id:ot.z.string().startsWith("CHG-"),title:ot.z.string().min(1),status:ot.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:ot.z.enum(N1),capabilities:ot.z.array(ot.z.string().startsWith("SPEC-")),requirements:ot.z.array(ot.z.string().startsWith("REQ-")),tasks:ot.z.array(ot.z.string().startsWith("TASK-")),human_decisions:ot.z.array(ot.z.string().startsWith("DEC-HUMAN-")),agent_decisions:ot.z.array(ot.z.string().startsWith("DEC-AI-")),created_at:tl,updated_at:tl,completed_at:tl.nullable().default(null)}).strict();var pt=Ie(Ne(),1);var Xr=["validate","develop","review","fix","verify","close"];var Bo=Ie(Ne(),1);var VJ=5*6e4;var tG=Bo.z.object({hypothesis:Bo.z.string().trim().min(1),test:Bo.z.string().trim().min(1),executor_model:Bo.z.enum(["gpt-6-luna","gpt-6-sol","gpt-6-astra"])}).strict();var Lr=Ie(Ne(),1),Jo=Lr.z.object({outcome:Lr.z.enum(["completed","blocked","failed","cancelled"]),summary:Lr.z.string().trim().min(1),evidence_ids:Lr.z.array(Lr.z.string().min(1)),changed_files:Lr.z.array(Lr.z.string().min(1))}).strict();var y=Ie(Ne(),1);var h_=y.z.string().datetime(),v_=y.z.object({id:y.z.string().min(1),acceptance_ids:y.z.array(y.z.string().min(1))}).strict(),Z1=y.z.object({soft_cycles:y.z.number().int().positive(),max_attempts:y.z.number().int().positive().nullable()}).strict(),B1=y.z.object({phase:y.z.enum(Xr),event_id:y.z.string().min(1),state_hash:y.z.string().regex(/^[a-f0-9]{64}$/),cycles:y.z.number().int().nonnegative(),input_tokens:y.z.number().int().nonnegative().nullable(),measurement_source:y.z.enum(["provider-uncached-input","observable-context-fallback","unavailable"]),checkpoint_required:y.z.boolean()}).strict(),H1=y.z.object({schema_version:y.z.literal(1),id:y.z.string().min(1),phase:y.z.enum(Xr),status:y.z.enum(["running","blocked","completed"]),revision:y.z.number().int().positive(),acceptance_ids:y.z.array(y.z.string().min(1)).min(1),budgets:y.z.object(Object.fromEntries(Xr.map(e=>[e,Z1]))),attempts:y.z.object(Object.fromEntries(Xr.map(e=>[e,y.z.number().int().nonnegative()]))),checkpoints:y.z.array(B1),evidence:y.z.array(v_),processed_event_ids:y.z.array(y.z.string().min(1)),blocker:y.z.string().min(1).nullable()}).strict(),il=y.z.enum(["execution_override","task_override","automatic_policy","project_defaults"]),J1=y.z.enum(["EXECUTION_OVERRIDE","TASK_OVERRIDE","XHIGH_ELIGIBLE","SIMPLE_BOUNDED_WORK","SOL_PLANNING_OR_REVIEW","SOL_AMBIGUOUS_OR_TRANSVERSAL","SOL_STRUCTURAL_REWORK","ASTRA_DIAGNOSTIC","ASTRA_HANDBACK","SOL_IMPLEMENTATION_BASELINE","TERRA_IMPLEMENTATION_BASELINE","PROJECT_DEFAULTS","RISK_ASSURANCE_ONLY"]),G1=y.z.object({model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]),velocity:y.z.literal("standard"),origin:il,sources:y.z.object({model:il,reasoning_effort:il,velocity:il}).strict(),policy_version:y.z.string().min(1),reasons:y.z.array(J1).min(1)}).strict(),K1=y.z.object({invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/),run_id:y.z.string().min(1).nullable().default(null),phase:y.z.enum(Xr),role:y.z.enum(["builder","verifier","finalizer"]),checkpoint_id:y.z.string().min(1).nullable(),checkpoint_hash:y.z.string().regex(/^[a-f0-9]{64}$/).nullable(),selection:G1.nullable().default(null)}).strict(),X1=y.z.object({astra_diagnostic:Rs.optional(),rework:y.z.enum(["localized","structural"]),rework_cost:y.z.enum(["medium","high"]),findings:y.z.array(y.z.string().min(1)).default([]),complexity:y.z.enum(["simple","standard","complex"]),transversality:y.z.enum(["local","multi_module","cross_system"]),ambiguity:y.z.enum(["low","medium","high"]),bounded:y.z.boolean(),high_volume:y.z.boolean(),xhigh_triggers:y.z.array(y.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"]))}).strict(),vS=y.z.object({task_id:y.z.string().min(1),status:y.z.enum(["available","unavailable","quality_below_floor"]),evidence_ids:y.z.array(y.z.string().min(1)),validation_ids:y.z.array(y.z.string().min(1)),rework_count:y.z.number().int().nonnegative().nullable(),quality_score:y.z.number().nonnegative().nullable(),quality_floor:y.z.number().nonnegative().nullable(),cost_delta_usd:y.z.number().nullable(),economy_status:y.z.enum(["available","unavailable"])}).strict(),Y1=y.z.object({baseline_task_id:y.z.string().min(1).nullable(),baseline_equivalence_id:y.z.string().min(1).nullable(),model:y.z.string().min(1).nullable(),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).nullable(),context_budget_tokens:y.z.number().int().nonnegative().nullable(),cached_context_tokens:y.z.number().int().nonnegative().nullable(),early_stop_reason:y.z.string().min(1).nullable(),retry_count:y.z.number().int().nonnegative().nullable(),rework_count:y.z.number().int().nonnegative().nullable(),observed_cost_usd:y.z.number().nonnegative().nullable(),baseline_observed_cost_usd:y.z.number().nonnegative().nullable(),quality_score:y.z.number().nonnegative().nullable(),quality_floor:y.z.number().nonnegative().nullable()}).strict(),Q1=y.z.object({provider:y.z.enum(["codex","claude"]),host_authentication_available:y.z.boolean(),requires_external_provider:y.z.boolean(),requires_remote_operation:y.z.boolean()}).strict(),eF=y.z.object({identity:y.z.string().min(1),replay_key:y.z.string().regex(/^[a-f0-9]{64}$/),validation_ids:y.z.array(y.z.string().min(1)),evidence_ids:y.z.array(y.z.string().min(1))}).strict(),tF=y.z.object({candidate_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/).nullable(),proof_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/),semantic_attempts:y.z.number().int().nonnegative(),classification:y.z.enum(["unknown","localized","structural"]),proof_delta:y.z.enum(["none","added","replaced"]),repeated_without_delta:y.z.boolean(),elapsed_reassessment:y.z.literal("unavailable"),decision:y.z.enum(["shadow_continue","shadow_rereview","shadow_block"])}).strict(),nF=y.z.object({id:y.z.string().min(1),rule:y.z.string(),path:y.z.string(),line:y.z.number().int().positive(),severity:y.z.enum(["low","medium","high","critical"]),message:y.z.string(),status:y.z.enum(["open","resolved","waived"]),resolution_evidence_id:y.z.string().nullable()}).strict(),rF=y.z.object({id:y.z.string().min(1),executor_id:y.z.string().min(1),reviewer_id:y.z.string().min(1),max_repair_cycles:y.z.number().int().nonnegative().nullable(),repair_cycles:y.z.number().int().nonnegative(),findings:y.z.array(nF),reviewer_approved:y.z.boolean()}).strict(),iF=y.z.object({autonomy:Ql.optional(),finalizer_decision:Jo.optional(),recovery_invocation:y.z.object({id:y.z.string().min(1),run_id:y.z.string().nullable()}).strict().optional(),recovery_plan:y.z.object({hypothesis:y.z.string().min(1),test:y.z.string().min(1),executor_model:y.z.string().min(1)}).strict().optional(),id:y.z.string().min(1),change_id:y.z.string().min(1),title:y.z.string().min(1),objective:y.z.string().min(1),risk:y.z.enum(["lite","standard","critical"]),priority:y.z.number().int(),depends_on:y.z.array(y.z.string().min(1)),acceptance_ids:y.z.array(y.z.string().min(1)).min(1),write_scopes:y.z.array(y.z.string().min(1)),scope_receipt:y.z.object({receipt_id:y.z.string().min(1),current_scopes:y.z.array(y.z.string().min(1)),delta_scopes:y.z.array(y.z.string().min(1))}).optional(),child_execution_id:y.z.string().min(1).optional(),builder:y.z.object({id:y.z.string().min(1),model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).optional(),tools:y.z.array(y.z.string()).optional(),execution_eligibility:y.z.array(y.z.enum(["interaction","delivery"])).optional()}).optional(),verifier:y.z.object({id:y.z.string().min(1),model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).optional(),tools:y.z.array(y.z.string()).optional(),execution_eligibility:y.z.array(y.z.enum(["interaction","delivery"])).optional()}).optional(),commit:y.z.object({agent:y.z.enum(["CODEX","CLAUDE"]),execution_id:y.z.string().min(1),change_id:y.z.string().min(1),task_id:y.z.string().min(1),title:y.z.string().min(1),prd_id:y.z.string().min(1).nullable(),spec_id:y.z.string().min(1).nullable()}).strict().optional(),runtime:xs.optional(),model_profile:jr.optional(),assurance_contract:Kb.optional(),outcome_measurement:Y1.optional(),status:y.z.enum(["planned","running","completed","failed","blocked"]),worktree_path:y.z.string().min(1).nullable(),integration_commit:y.z.string().min(1).nullable(),changed_files:y.z.array(y.z.string().min(1)).default([]),task_run_id:y.z.string().min(1).nullable().default(null),finalizer_approved:y.z.boolean().default(!1),closure_pending:y.z.boolean().default(!1),finalization_pending:y.z.boolean().default(!1),lifecycle_cleanup:y.z.object({handoff_path:y.z.string().min(1),invocation_run_id:y.z.string().min(1).nullable(),task_run_id:y.z.string().min(1).nullable(),invocation_finished:y.z.boolean(),task_finished:y.z.boolean(),last_error:y.z.string().nullable()}).strict().optional(),active_invocation:K1.nullable(),active_diagnostic:y.z.object({invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/),run_id:y.z.string().min(1).nullable(),status:y.z.enum(["requested","completed","blocked"]),cycle:y.z.union([y.z.literal(1),y.z.literal(2),y.z.literal(3)]),evidence_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/),executor_attempt_id:y.z.string().min(1).nullable(),handback:Is.nullable()}).strict().nullable().default(null),handback:Is.nullable().default(null),last_executor_invocation_id:y.z.string().min(1).nullable().default(null),rework_profile:X1.nullable().default(null),sdc:H1,validation_ids:y.z.array(y.z.string().min(1)),evidence:y.z.array(v_),outcome_projection:vS.nullable().default(null),validation_attempts:y.z.array(eF).default([]),convergence_observations:y.z.array(tF).default([]),qa_session:rF.nullable().default(null),qa_pending_resolutions:y.z.array(y.z.object({finding_id:y.z.string().min(1),evidence_id:y.z.string().min(1)}).strict()).default([]),qa_approval_observed:y.z.boolean().default(!1),qa_review_candidate_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/).nullable().default(null),last_error:y.z.string().min(1).nullable()}).strict(),AK=y.z.object({schema_version:y.z.literal(1),execution_id:y.z.string().min(1),lease_ms:y.z.number().int().min(5e3).max(Number.MAX_SAFE_INTEGER).nullable().default(null),source:y.z.enum(["task","spec","prd"]),operational_context:Q1.default({provider:"codex",host_authentication_available:!1,requires_external_provider:!1,requires_remote_operation:!1}),status:y.z.enum(["running","completed","failed","blocked"]),revision:y.z.number().int().nonnegative(),created_at:h_,updated_at:h_,execution_started_at:h_.nullable().default(null),invocation_count:y.z.number().int().nonnegative().default(0),stalled_cycles:y.z.number().int().nonnegative().default(0),handoff_worktree_path:y.z.string().min(1).nullable().default(null),handoff_branch:y.z.string().min(1).nullable().default(null),handoff_commit:y.z.string().min(1).nullable().default(null),parent_acceptance:y.z.object({run_id:y.z.string().min(1).nullable(),finalizer_run_id:y.z.string().min(1).nullable().default(null),invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/).nullable().default(null),checkpoint_id:y.z.string().min(1).nullable().default(null),checkpoint_hash:y.z.string().min(1).nullable().default(null),candidate:y.z.object({handoff_worktree_path:y.z.string().min(1),handoff_commit:y.z.string().min(1),validation_ids:y.z.array(y.z.string().min(1)),evidence:y.z.array(v_),task_outcomes:y.z.array(y.z.object({task_id:y.z.string().min(1),integration_commit:y.z.string().min(1),changed_files:y.z.array(y.z.string().min(1)),outcome_projection:vS.nullable()}).strict())}).strict().nullable().default(null),decision_observed:y.z.boolean().default(!1),decision:Jo.optional(),status:y.z.enum(["pending","approved","blocked"])}).default({run_id:null,finalizer_run_id:null,invocation_id:null,checkpoint_id:null,checkpoint_hash:null,candidate:null,decision_observed:!1,status:"pending"}),tasks:y.z.array(iF).min(1),last_error:y.z.string().min(1).nullable()}).strict();var Xe=Ie(Ne(),1);var cn=Ie(Ne(),1),b_=cn.z.object({editorial_delivery:cn.z.boolean().optional(),production_impact:cn.z.boolean().optional(),external_action:cn.z.boolean().optional(),irreversible_change:cn.z.boolean().optional(),security_or_critical_data:cn.z.boolean().optional(),data_migration:cn.z.boolean().optional(),broad_audit:cn.z.boolean().optional(),rollback:cn.z.enum(["trivial","planned","complex"]).optional(),verification_scope:cn.z.enum(["scoped","package","cross_scope","full"]).optional()}).strict();var gr=Ie(Ne(),1),S_=gr.z.preprocess(e=>typeof e=="string"?{summary:e,changed_files:[],evidence_ids:[],completed_run_id:null}:e,gr.z.object({summary:gr.z.string().min(1),changed_files:gr.z.array(gr.z.string().min(1)),evidence_ids:gr.z.array(gr.z.string().startsWith("EVD-")),completed_run_id:gr.z.string().startsWith("RUN-").nullable()}).strict());function Go(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var ol=Xe.z.string().datetime({offset:!0}),aF=Xe.z.string().regex(/^[a-f0-9]{64}$/),bS=Xe.z.string().startsWith("TASK-"),sF=Xe.z.string().startsWith("CHG-"),cF=Xe.z.string().startsWith("REQ-"),lF=Xe.z.string().startsWith("AC-"),lY=Xe.z.object({schema_version:Xe.z.literal(2),id:bS,revision:Xe.z.number().int().positive(),change_id:sF,title:Xe.z.string().min(1),short_name:Xe.z.string().min(1),objective:Xe.z.string().min(1),status:Xe.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:Xe.z.string().min(1).nullable().optional(),attempt_count:Xe.z.number().int().nonnegative().optional(),risk:Xe.z.enum(["lite","standard","critical"]),priority:Xe.z.enum(["low","medium","high","urgent"]),owner:Xe.z.string().min(1).nullable(),requirement_ids:Xe.z.array(cF).min(1),acceptance_ids:Xe.z.array(lF).min(1),depends_on:Xe.z.array(bS),write_scopes:Xe.z.array(Xe.z.string().min(1)),runtime:xs.optional(),model_profile:jr.optional(),assurance_risk_signals:b_.optional(),assurance_risk_signals_source:Xe.z.enum(["explicit","risk_default"]).optional(),plan_revision:Xe.z.number().int().positive().nullable(),plan_hash:aF.nullable(),prepared_plan:Ri.optional(),plan_ref:Vo.optional(),created_at:ol,updated_at:ol,started_at:ol.nullable(),finished_at:ol.nullable(),result:S_.nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||n&&["blocked","failed","cancelled"].includes(e.status)?(!n||e.prepared_plan!==void 0||e.plan_ref!==void 0)&&t.addIssue({code:"custom",message:`${e.status} Task without materialization cannot contain a prepared plan`}):(e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Task requires plan_revision and plan_hash`}),e.prepared_plan!==void 0&&e.plan_ref!==void 0&&t.addIssue({code:"custom",message:"Task cannot contain prepared_plan and plan_ref"}),e.plan_ref!==void 0&&e.plan_ref.hash!==e.plan_hash&&t.addIssue({code:"custom",path:["plan_ref"],message:"plan_ref must match plan_hash"}),e.prepared_plan!==void 0&&(e.prepared_plan.source.type!=="task"||e.prepared_plan.source.task_id!==e.id||e.prepared_plan.hash!==e.plan_hash)&&t.addIssue({code:"custom",path:["prepared_plan"],message:"prepared_plan must belong to the Task and match plan_hash"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Task requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Task requires started_at`}),e.status==="completed"&&(e.result?.completed_run_id===null||e.result?.evidence_ids.length===0)&&t.addIssue({code:"custom",path:["result"],message:"completed Task requires completed_run_id and at least one Evidence"}),Go(e.requirement_ids,"requirement_ids",t),Go(e.acceptance_ids,"acceptance_ids",t),Go(e.depends_on,"depends_on",t),Go(e.write_scopes,"write_scopes",t)});var k_=pt.z.string().datetime({offset:!0}),pY=pt.z.object({id:pt.z.string().startsWith("TASK-"),title:pt.z.string().min(1),short_name:pt.z.string().min(1),status:pt.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:pt.z.enum(["lite","standard","critical"]),priority:pt.z.enum(["low","medium","high","urgent"]),owner:pt.z.string().min(1).nullable().default(null),progress:pt.z.number().int().min(0).max(100),spec:pt.z.string().startsWith("SPEC-"),change:pt.z.string().startsWith("CHG-"),requirements:pt.z.array(pt.z.string().startsWith("REQ-")),depends_on:pt.z.array(pt.z.string().startsWith("TASK-")),human_decisions:pt.z.array(pt.z.string().startsWith("DEC-HUMAN-")),agent_decisions:pt.z.array(pt.z.string().startsWith("DEC-AI-")),created_at:k_,started_at:k_.nullable(),finished_at:k_.nullable()}).strict();function TS(e){let t={};for(let n of["prd_count","spec_count","task_count","total_run_count","validation_count","evidence_count","total_duration","total_tokens","total_cost_usd","total_cost_brl"]){let i=e.map(r=>r[n]).filter(r=>typeof r=="number"&&Number.isFinite(r));t[n]=i.length===0?null:i.reduce((r,o)=>r+o,0)}return t.duration_known=t.total_duration??0,t.duration_unknown=e.reduce((n,i)=>n+(typeof i.duration_unknown=="number"?i.duration_unknown:typeof i.total_duration!="number"?1:0),0),t}function al(e){let t=e.map(n=>{let i=r=>typeof n[r]=="number"&&Number.isFinite(n[r])?n[r]:null;return{task_count:i("task_count"),spec_count:i("spec_count"),prd_count:i("prd_count"),duration_ms:i("total_duration"),total_tokens:i("total_tokens"),estimated_usd:i("total_cost_usd"),estimated_brl:i("total_cost_brl")}});return{BRL:Vc(t,"BRL"),USD:Vc(t,"USD")}}function OS(e,t,n,i){let r=i==="day"||i==="month"||i==="year",o,a,s=i==="day"?"date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours')":i==="month"?"substr(date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours'), 1, 7)":i==="year"?"substr(date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours'), 1, 4)":"i.provider_group",l=[`${s} IS NOT NULL`,"(i.total_tokens IS NOT NULL OR i.cost_usd IS NOT NULL OR i.cost_brl IS NOT NULL)"],c=[];n.from&&(l.push("date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours') >= ?"),c.push(Ke(n.from))),n.to&&(l.push("date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours') <= ?"),c.push(Ke(n.to)));let u=[];if(n.provider&&(n.provider==="unavailable"?l.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_provider WHERE known_provider.agent_invocation_id=i.agent_invocation_id AND known_provider.provider IS NOT NULL AND known_provider.provider <> 'unavailable')"):(u.push("f.provider=?"),c.push(n.provider))),n.model&&(n.model==="unavailable"?l.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_model WHERE known_model.agent_invocation_id=i.agent_invocation_id AND known_model.model IS NOT NULL AND known_model.model <> 'unavailable')"):(u.push("f.model=?"),c.push(n.model))),u.length>0&&l.push(`EXISTS (SELECT 1 FROM invocation_usage f WHERE f.agent_invocation_id=i.agent_invocation_id AND ${u.join(" AND ")})`),n.agent&&(l.push("i.zaip_agent = ?"),c.push(n.agent)),n.phase&&(l.push("i.phase = ?"),c.push(n.phase)),n.status&&(l.push("COALESCE(i.task_status, i.status) = ?"),c.push(n.status)),n.priority&&(l.push("i.task_priority = ?"),c.push(n.priority)),n.risk&&(l.push("i.task_risk = ?"),c.push(n.risk)),n.origin&&l.push(n.origin==="prd"?"i.prd_id IS NOT NULL":n.origin==="spec"?"i.prd_id IS NULL AND i.spec_id IS NOT NULL":n.origin==="task"?"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NOT NULL":"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NULL"),n.workType&&(l.push("i.work_type = ?"),c.push(n.workType)),n.query){let E=`%${n.query}%`;l.push("(i.agent_invocation_id LIKE ? OR i.execution_id LIKE ? OR i.task_id LIKE ? OR i.spec_id LIKE ? OR i.prd_id LIKE ? OR i.conversation_id LIKE ? OR i.zaip_agent LIKE ? OR i.purpose LIKE ?)"),c.push(E,E,E,E,E,E,E,E)}let d=`WITH usage_rollup AS (
|
|
708
|
+
ORDER BY paged.total_cost_brl DESC, paged.id`).all(...E,h,S),T=x[0];if(!T)throw new Error("Canonical macro query did not return its aggregate row.");let R=Number(T.__entity_count),V={entity_count:T.__entity_count,invocation_count:T.__invocation_count,total_duration:T.__total_duration,total_tokens:T.__total_tokens,total_cost_usd:T.__total_cost_usd,total_cost_brl:T.__total_cost_brl},G=x.filter(U=>U.__row_present===1).map(U=>Object.fromEntries(Object.entries(U).filter(([_e])=>!_e.startsWith("__"))));return{data_source:"sqlite_read_model",view:t,offset:S,limit:h,total_count:R,has_more:S+G.length<R,totals:V,rows:G}}if(!!(n.provider||n.model||n.agent||n.phase||n.status||n.origin||n.workType||n.priority||n.risk)){let s={task:"i.task_id",spec:"i.spec_id",prd:"i.prd_id",execution:"i.execution_id",conversation:"i.conversation_id"}[i],l=i==="task"?"tasks":i==="spec"?"specs":i==="prd"?"prds":null,c=[`${s} IS NOT NULL`],u=[];n.from&&(c.push("i.occurred_day_sp >= ?"),u.push(n.from.slice(0,10))),n.to&&(c.push("i.occurred_day_sp <= ?"),u.push(n.to.slice(0,10))),n.agent&&(c.push("i.zaip_agent = ?"),u.push(n.agent)),n.phase&&(c.push("i.phase = ?"),u.push(n.phase)),n.status&&(c.push(l==="specs"||l==="prds"?"COALESCE(entity.status, i.status) = ?":"COALESCE(task_entity.status, i.status) = ?"),u.push(n.status)),n.risk&&(c.push("task_entity.risk = ?"),u.push(n.risk)),n.origin&&c.push(n.origin==="prd"?"i.prd_id IS NOT NULL":n.origin==="spec"?"i.prd_id IS NULL AND i.spec_id IS NOT NULL":n.origin==="task"?"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NOT NULL":"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NULL"),n.workType&&(c.push("i.work_type = ?"),u.push(n.workType)),n.priority&&(c.push("task_entity.priority = ?"),u.push(n.priority));let d=[];n.provider&&(n.provider==="unavailable"?c.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_provider WHERE known_provider.agent_invocation_id=i.agent_invocation_id AND known_provider.provider IS NOT NULL AND known_provider.provider <> 'unavailable')"):(d.push("u.provider = ?"),u.push(n.provider))),n.model&&(n.model==="unavailable"?c.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_model WHERE known_model.agent_invocation_id=i.agent_invocation_id AND known_model.model IS NOT NULL AND known_model.model <> 'unavailable')"):(d.push("u.model = ?"),u.push(n.model))),d.length>0&&c.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=i.agent_invocation_id AND ${d.join(" AND ")})`),n.query&&(c.push(l===null?`${s} LIKE ?`:`(${s} LIKE ? OR COALESCE(entity.title, '') LIKE ?)`),u.push(`%${n.query}%`,...l===null?[]:[`%${n.query}%`]));let f=`${l===null?"":`LEFT JOIN ${l} entity ON entity.id=${s}`} LEFT JOIN tasks task_entity ON task_entity.id=i.task_id`,g=c.join(" AND "),h=l===null?s:`COALESCE(MAX(entity.title), ${s})`,E=`WITH grouped AS (SELECT ${s} AS group_value, ${h} AS title, ${l===null?"NULL":"MAX(entity.status)"} AS status, MAX(task_entity.risk) AS risk, MAX(i.occurred_at) AS occurred_at, COUNT(*) AS invocation_count, SUM(i.duration_ms) AS total_duration, SUM(i.total_tokens) AS total_tokens, SUM(i.cost_usd) AS total_cost_usd, SUM(i.cost_brl) AS total_cost_brl FROM invocations i ${f} WHERE ${g} GROUP BY ${s})`,x=Math.min(200,Math.max(1,n.limit??50)),T=Math.max(0,n.offset??0),R=Number(e.database.prepare(`${E} SELECT COUNT(*) AS count FROM grouped`).get(...u).count),V=e.database.prepare(`${E} SELECT COUNT(*) AS entity_count, COALESCE(SUM(invocation_count), 0) AS invocation_count, ROUND(SUM(total_duration)) AS total_duration, SUM(total_tokens) AS total_tokens, SUM(total_cost_usd) AS total_cost_usd, SUM(total_cost_brl) AS total_cost_brl FROM grouped`).get(...u),G=e.database.prepare(`${E} SELECT group_value AS id, group_value AS key, title, status, risk, occurred_at, invocation_count, total_duration, total_tokens, total_cost_usd, total_cost_brl FROM grouped ORDER BY total_cost_brl DESC, group_value LIMIT ? OFFSET ?`).all(...u,x,T);return{data_source:"sqlite_read_model",view:t,offset:T,limit:x,total_count:R,has_more:T+G.length<R,totals:V,rows:G}}return lb(e.database,t,i,n)}function Vc(e,t){let n=e.length;return{tasks:qc(e.map(i=>i.task_count),n),specs:qc(e.map(i=>i.spec_count),n),prds:qc(e.map(i=>i.prd_count),n),durationMs:qc(e.map(i=>i.duration_ms),n),tokens:db(e.map(i=>i.total_tokens)),cost:db(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function db(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function qc(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}var Po={"2026-08-02":4809511,"2026-08-01":8894527,"2026-07-31":9472804,"2026-07-30":5167818,"2026-07-29":11336221,"2026-07-28":8262282,"2026-07-27":4862150,"2026-07-26":970899,"2026-07-25":7465970,"2026-07-24":9041538,"2026-07-23":19750,"2026-07-22":1371560,"2026-07-21":14992543,"2026-07-20":3168460,"2026-07-19":929990,"2026-07-18":9232700,"2026-07-17":16882853,"2026-07-16":20054785,"2026-07-15":35459620,"2026-07-14":24078852,"2026-07-13":22611635,"2026-07-12":8339738,"2026-07-11":1859980},Wc={cutoff:"2026-08-02T03:14:00.000Z",cutoffDay:"2026-08-02",durationMs:Object.values(Po).reduce((e,t)=>e+t,0),costXlsxSha256:"C3EE0495667289FB81DD8F9268697CEB7692433C14CB19934C89B5F39129902A",operationsXlsxSha256:"94E9577A7CA27F7FDD277D81E34156296CB28FE39CF6D7636B259EBBB7E56BCC"},CZ=76*36e5;var fe=Ie(Ne(),1);var qt=Ie(Ne(),1);var w=Ie(Ne(),1);var zt=Ie(Ne(),1),wU=zt.z.string().datetime({offset:!0}).or(zt.z.string().datetime()),_b=zt.z.object({schema_version:zt.z.literal(2),event_id:zt.z.string().min(1).max(200),run_id:zt.z.string().startsWith("RUN-"),sequence:zt.z.number().int().positive(),occurred_at:wU,type:zt.z.literal("run.attribution.recovered"),phase:zt.z.literal("execution"),execution_id:zt.z.string().startsWith("EXEC-"),task_id:zt.z.string().startsWith("TASK-"),change_id:zt.z.string().startsWith("CHG-")}).strict();function pb(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 r_(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 i_(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 Zc(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 _t=Ie(Ne(),1),mb=_t.z.string().datetime({offset:!0}).or(_t.z.string().datetime()),AU=_t.z.string().regex(/^DEC-(?:HUMAN|AI)-/),TU=_t.z.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation","rollback"]),i6=_t.z.object({schema_version:_t.z.literal(2),id:AU,title:_t.z.string().min(1),scope_type:_t.z.enum(["change","execution"]),scope_id:_t.z.string().min(1),origin:_t.z.enum(["human","agent"]),category:TU,context:_t.z.string().min(1),decision:_t.z.string().min(1),reason:_t.z.string().min(1),alternatives:_t.z.array(_t.z.string().min(1)),consequences:_t.z.array(_t.z.string().min(1)),reversible:_t.z.boolean(),rollback:_t.z.string().min(1),confidence:_t.z.number().min(0).max(1).nullable(),created_at:mb,confirmed_at:mb.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 Lt=w.z.string().datetime({offset:!0}).or(w.z.string().datetime()),Bc=w.z.enum(["conversation","planning","execution"]),Hc=w.z.string().startsWith("RUN-"),$U=w.z.string().startsWith("CONV-"),fb=w.z.string().startsWith("EXEC-").nullable(),gb=w.z.string().startsWith("TASK-").nullable(),yb=w.z.string().startsWith("SPEC-").nullable(),hb=w.z.string().startsWith("PRD-").nullable(),vb=w.z.string().startsWith("CHG-").nullable(),o_=Hc.nullable(),Br=w.z.string().regex(/^(?:AINV|INV)-/).max(200),bb=w.z.string().startsWith("MCALL-").max(200),d6=w.z.enum(["intake","orchestrator","subagent"]),LU=w.z.enum(["intake","orchestrator","subagent","owner","contributor"]),Sb=w.z.enum(["intake","orchestration","execution","review","audit","finalization"]),kb=w.z.enum(["none","minimal","low","medium","high","xhigh","max","ultra"]),Uo=w.z.object({schema_version:w.z.literal(1),provider:w.z.literal("github"),account_id:w.z.string().min(1).max(100),login_snapshot:w.z.string().min(1).max(100),attribution_source:w.z.enum(["verified_local_account","last_verified_local_account","cached_fallback","human_assigned"]),verified_at:Lt.nullable(),expires_at:Lt.nullable().optional(),last_verified_at:Lt.nullable().optional()}).strict();var Eb=w.z.enum(["orchestrator","delegated"]);var a_=w.z.object({input:w.z.number().int().nonnegative().nullable(),cached_input:w.z.number().int().nonnegative().nullable(),cache_write_input:w.z.number().int().nonnegative().nullable().optional(),output:w.z.number().int().nonnegative().nullable(),reasoning:w.z.number().int().nonnegative().nullable(),total:w.z.number().int().nonnegative().nullable(),source:w.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"})}),wb=w.z.object({usd:w.z.number().nonnegative().nullable(),brl:w.z.number().nonnegative().nullable(),fx_rate:w.z.number().positive().nullable().optional()}).strict(),Hr={schema_version:w.z.literal(2),event_id:w.z.string().min(1).max(200),run_id:Hc,sequence:w.z.number().int().positive(),occurred_at:Lt},MU=w.z.object({intent:w.z.enum(["conversation","continue","refine","rework","new_work"]),classification_source:w.z.enum(["agent","explicit","fallback"]),confidence:w.z.number().min(0).max(1),reason_codes:w.z.array(w.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(12)}).strict(),Ab=w.z.object({...Hr,type:w.z.literal("run.started"),attribution_status:w.z.enum(["attributed","legacy_unattributed"]),developer_identity:Uo.nullable().optional(),phase:Bc,run_role:LU.optional(),run_purpose:Sb.optional(),requires_finalizer:w.z.boolean().optional(),execution_kind:w.z.enum(["interaction","delivery"]).optional(),execution_eligibility:w.z.array(w.z.enum(["interaction","delivery"])).optional(),direct_execution_authorization:w.z.string().trim().min(1).max(1e3).optional(),entrypoint:w.z.enum(["conversation","task","spec","prd"]),work_type:w.z.enum(["new","rework"]),storage_mode:w.z.enum(["tracked_sanitized","local_only"]),client:w.z.string().min(1).max(100),agent:w.z.string().min(1).max(100),agent_name:w.z.string().min(1).max(100).nullable().optional(),agent_identity_warning:w.z.object({code:w.z.literal("deprecated-agent-identity"),kind:w.z.enum(["id","codex_name","codex_task_name"]),requested:w.z.string().min(1),canonical_id:w.z.string().min(1),deprecated_at:w.z.iso.date(),remove_after:w.z.iso.date()}).strict().optional(),provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200),reasoning_effort:kb.nullable().optional(),client_thread_id:w.z.string().min(1).max(200).nullable().optional(),client_turn_id:w.z.string().min(1).max(200).nullable().optional(),conversation_id:$U,execution_id:fb,task_id:gb,spec_id:yb,prd_id:hb,change_id:vb,parent_run_id:o_,continuation_of_run_id:o_,retry_of_run_id:o_,agent_invocation_id:Br.optional(),root_agent_invocation_id:Br.optional(),parent_agent_invocation_id:Br.nullable().optional(),invocation_kind:Eb.optional(),delegation_depth:w.z.number().int().nonnegative().optional(),intake:MU.nullable().optional()}).strict().superRefine((e,t)=>{e.direct_execution_authorization!==void 0&&(e.execution_kind!=="delivery"||e.agent!=="agent-orchestrator"||e.run_role!=="orchestrator"||e.parent_run_id!==null||e.task_id===null||e.change_id===null||e.execution_id===null||!e.client_thread_id||!e.client_turn_id||e.client_turn_id.startsWith("local-")||["unknown","unavailable","manual"].includes(e.model))&&t.addIssue({code:"custom",path:["direct_execution_authorization"],message:"Direct execution requires an observed Task-scoped delivery root and explicit authorization"}),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`})}),Tb=w.z.object({...Hr,type:w.z.literal("usage.recorded"),phase:Bc,activity_kind:w.z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),classification_source:w.z.enum(["explicit","current_context","default","legacy_inferred"]),tokens:a_,cost:wb,provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),source_segment_key:w.z.string().min(1).max(500).nullable(),attributed_spec_id:w.z.string().min(1).max(200).nullable().optional(),model_call_id:bb.nullable().optional(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict().optional(),supersedes_event_id:w.z.string().min(1).max(200).nullable(),retrospective_correction:w.z.literal(!0).optional(),source_occurred_at:Lt.optional(),source_started_at:Lt.optional(),source_finished_at:Lt.optional(),duration_ms:w.z.number().int().nonnegative().nullable().optional(),duration_provenance:w.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().optional(),context_stats:w.z.object({initial_pack_tokens:w.z.number().int().nonnegative().nullable(),tool_output_tokens:w.z.number().int().nonnegative().nullable(),files_opened:w.z.number().int().nonnegative().nullable(),snippets_opened:w.z.number().int().nonnegative().nullable()}).strict().optional()}).strict(),Ob=w.z.object({...Hr,type:w.z.literal("model.call.observed"),call_id:bb,agent_invocation_id:Br,coverage:w.z.enum(["complete","partial","unavailable"]),tokens:a_,cost:wb,provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),source_call_key:w.z.string().min(1).max(500).nullable(),source_occurred_at:Lt.optional(),source_started_at:Lt.optional(),source_finished_at:Lt.optional(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict().optional()}).strict(),xb=w.z.object({schema_version:w.z.literal(1),run_id:Hc,execution_id:fb.nullable().default(null),task_id:gb.nullable().default(null),spec_id:yb.nullable().default(null),prd_id:hb.nullable().default(null),change_id:vb.nullable().default(null),developer_identity:Uo.nullable().optional(),zaip_agent:w.z.string().min(1).max(100).nullable().default(null),phase:Bc.nullable().default(null),purpose:Sb.nullable().default(null),agent_invocation_id:Br,root_agent_invocation_id:Br,parent_agent_invocation_id:Br.nullable(),invocation_kind:Eb,delegation_depth:w.z.number().int().nonnegative(),client:w.z.enum(["codex","codex-desktop","codex-subagent"]),thread_id:w.z.string().min(1).max(200).nullable(),turn_id:w.z.string().min(1).max(200).nullable(),agent_path:w.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"})}),Rb=w.z.object({correlation:xb,event_kind:w.z.enum(["response","usage","terminal","error"]),source:w.z.enum(["codex_app_server","codex_session_fallback","unavailable"]),source_event_key:w.z.string().min(1).max(500),source_method:w.z.enum(["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"]).optional(),stream_boundary:w.z.enum(["item_completed","response_completed","usage_updated","error","turn_completed"]).optional(),source_occurred_at:Lt.nullable(),captured_at:Lt,coverage:w.z.enum(["complete","partial","unavailable"]),tokens:a_.nullable(),provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),runtime:w.z.object({reasoning_effort:w.z.string().min(1).max(40).nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict(),status:w.z.enum(["completed","failed","cancelled"]).nullable(),will_retry:w.z.boolean().nullable().optional(),latency_ms:w.z.number().int().nonnegative().nullable(),historical_cost:w.z.object({estimated_usd:w.z.number().nonnegative().nullable(),estimated_brl:w.z.number().nonnegative().nullable(),fx_rate:w.z.number().positive().nullable(),pricing_model:w.z.string().nullable(),pricing_source:w.z.string().nullable(),pricing_source_url:w.z.string().url().nullable().optional(),pricing_catalog_updated_at:Lt.nullable().optional(),input_usd:w.z.number().nonnegative().nullable(),cached_input_usd:w.z.number().nonnegative().nullable(),cache_write_input_usd:w.z.number().nonnegative().nullable().optional(),output_usd:w.z.number().nonnegative().nullable(),reasoning_usd:w.z.number().nonnegative().nullable()}).strict().nullable().optional(),context_stats:w.z.object({initial_pack_tokens:w.z.number().int().nonnegative().nullable(),tool_output_tokens:w.z.number().int().nonnegative().nullable(),files_opened:w.z.number().int().nonnegative().nullable(),snippets_opened:w.z.number().int().nonnegative().nullable()}).strict().nullable(),discarded_counts:w.z.object({prompt:w.z.number().int().nonnegative(),response_text:w.z.number().int().nonnegative(),reasoning:w.z.number().int().nonnegative(),secrets:w.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"})}),Ib=w.z.object({schema_version:w.z.literal(1),event_id:w.z.string().startsWith("CEVT-").max(200),checksum_sha256:w.z.string().regex(/^[a-f0-9]{64}$/),compaction:w.z.object({status:w.z.enum(["pending","compacted"]),compacted_at:Lt.nullable()}).strict(),event:Rb}).strict(),Cb=w.z.string().startsWith("INV-").max(200),Nb=w.z.object({...Hr,type:w.z.literal("model.selection.recorded"),invocation_id:Cb,requested:w.z.object({model:w.z.string().min(1).max(200),reasoning_effort:w.z.enum(["low","medium","high","xhigh"]).nullable(),velocity:w.z.literal("standard")}).strict(),selection:w.z.object({source:w.z.enum(["execution-override","task-override","auto-policy","project-default"]),policy_version:w.z.number().int().positive(),reasons:w.z.array(w.z.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(20)}).strict()}).strict(),$b=w.z.object({...Hr,type:w.z.literal("provider.invocation.finished"),invocation_id:Cb,status:w.z.enum(["completed","failed","cancelled"]),effective:w.z.object({provider:w.z.string().min(1).max(100).nullable(),model:w.z.string().min(1).max(200).nullable(),reasoning_effort:kb.nullable(),service_tier:w.z.string().min(1).max(40).nullable()}).strict(),latency_ms:w.z.number().int().nonnegative().nullable()}).strict(),Lb=w.z.object({...Hr,type:w.z.literal("run.finished"),phase:Bc,status:w.z.enum(["completed","failed","cancelled"]),duration_ms:w.z.number().int().nonnegative().nullable().default(null),duration_provenance:w.z.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().default(null)}).strict(),PU=w.z.object({...Hr,type:w.z.literal("run.finalization.decided"),finalizer_run_id:Hc,outcome:w.z.enum(["completed","blocked","failed","cancelled"]),summary:w.z.string().min(1).max(4e3),evidence_ids:w.z.array(w.z.string().min(1).max(200)).max(100),changed_files:w.z.array(w.z.string().min(1).max(500)).max(1e4).default([])}).strict(),Fo=w.z.discriminatedUnion("type",[Ab,Tb,Ob,Nb,$b,_b,PU,Lb]);var Mb=".local/codex-telemetry-spool/v1",DU=`${Mb}/events`,h6=`${Mb}/events.index.json`;var v6=64*1024,b6=64*1024*1024;var jU=qt.z.object({path:qt.z.string().startsWith(`${DU}/`).endsWith(".json"),stat:qt.z.object({dev:qt.z.string(),ino:qt.z.string(),size:qt.z.string(),mtime_ns:qt.z.string(),ctime_ns:qt.z.string()}).strict(),envelope:Ib}).strict(),S6=qt.z.object({schema_version:qt.z.literal(1),events:qt.z.array(jU),checksum_sha256:qt.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var Vt=Ie(Ne(),1);var UU=Vt.z.object({run_id:Vt.z.string().startsWith("RUN-"),path:Vt.z.string().startsWith(".agents/records/runs/"),content_sha256:Vt.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),FU=Vt.z.object({schema_version:Vt.z.literal(1),manifest_id:Vt.z.string().min(1),created_at:Vt.z.string().datetime({offset:!0}),kind:Vt.z.literal("historical_developer_attribution"),assignment:Uo.extend({attribution_source:Vt.z.literal("human_assigned")}),source_streams:Vt.z.array(UU).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)}),w6=FU.extend({manifest_hash:Vt.z.string().regex(/^[a-f0-9]{64}$/)}).strict();var O6=1440*60*1e3;function qb(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(!Vb(i,r))throw new Error(`Divergent duplicate source segment: ${i.source_segment_key}`)}return n}function Vb(e,t){return JSON.stringify(zb(e))===JSON.stringify(zb(t))}function zb(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 Wb(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=Fo.parse(Array.isArray(o)?t(o,i):o);i??=a.run_id,n.push(a)}return n}function Zb(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 Jc(e){return Wb(e,GU)}function Gc(e){let t=new Map;for(let h of e){let S=Fo.parse(h),E=t.get(S.event_id);if(E!==void 0){if(JSON.stringify(E)!==JSON.stringify(S))throw new Error(`Divergent duplicate Run V2 event: ${S.event_id}`);continue}t.set(S.event_id,S)}let n=[...t.values()].sort((h,S)=>h.sequence-S.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[h,S]of n.entries()){if(S.run_id!==i.run_id)throw new Error("Run V2 stream mixes run ids");if(S.sequence!==h+1)throw new Error("Run V2 sequence must be contiguous");let E=l.get(S.sequence);if(E!==void 0&&E!==S.event_id)throw new Error(`Run V2 sequence is duplicated: ${S.sequence}`);if(l.set(S.sequence,S.event_id),h>0&&S.type==="run.started")throw new Error("Run V2 has multiple starts");if(o!==null&&S.type!=="run.finalization.decided"&&!i_(S,o,c))throw new Error("Run V2 contains a non-retrospective record after run.finished");if(S.type==="usage.recorded"){if(Zc(r,S.phase),S.phase==="execution"&&i.execution_id===null&&i.attribution_status!=="legacy_unattributed")throw new Error("Execution phase requires execution_id");if(S.supersedes_event_id!==null&&!c.has(S.supersedes_event_id))throw new Error(`Superseded usage event must occur earlier: ${S.supersedes_event_id}`);c.set(S.event_id,S),r=S.phase}if(S.type==="run.attribution.recovered"){if(!pb(i,S))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");Zc(r,S.phase),r=S.phase,s=S}if(S.type==="model.selection.recorded"){if(Zb(i,n.slice(0,h),{invocationId:S.invocation_id,requested:S.requested,selection:S.selection}),u.has(S.invocation_id))throw new Error(`Duplicate model selection for invocation: ${S.invocation_id}`);u.set(S.invocation_id,S)}if(S.type==="provider.invocation.finished"){if(!u.has(S.invocation_id))throw new Error(`Provider invocation requires earlier model selection: ${S.invocation_id}`);if(d.has(S.invocation_id))throw new Error(`Duplicate provider terminal for invocation: ${S.invocation_id}`);d.set(S.invocation_id,S)}if(S.type==="model.call.observed"){let x=p.get(S.call_id);if(x!==void 0&&JSON.stringify(x)!==JSON.stringify(S)&&!r_(x,S))throw new Error(`Divergent duplicate Model Call: ${S.call_id}`);p.set(S.call_id,S)}if(S.type==="run.finalization.decided"){if(a!==null)throw new Error("Run V2 has multiple finalization decisions");a=S}if(S.type==="run.finished"){if(S.phase!==r)throw new Error("run.finished phase must match the latest phase");o=S}}let m=n.filter(h=>h.type==="usage.recorded"),f=new Set(m.map(h=>h.supersedes_event_id).filter(h=>h!==null)),g=qb(m.filter(h=>!f.has(h.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:m,effective_usage_records:g,model_selection_records:[...u.values()],provider_invocation_records:[...d.values()],model_call_records:[...p.values()]}}function GU(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],m=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],...d[6]===void 0?{}:{cache_write_input:d[6]}},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]},...m===null||!Array.isArray(m)?{}:{runtime:{reasoning_effort:m[0],service_tier:m[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],...n[6]===void 0?{}:{cache_write_input:n[6]}},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 Kc=fe.z.string().datetime({offset:!0}),KU=fe.z.preprocess(e=>e==="client"?"provider_reported":e,fe.z.enum(["provider_reported","estimated","unavailable"])),pB=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:Kc,confirmed_at:Kc.nullable()}).strict();var mB=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:Kc,finished_at:Kc.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:KU}),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 De=Ie(Ne(),1);function nn(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 bB=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}),SB=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"});var Hb=".agents/records/lifecycle/views",CB=`${Hb}/manifest.json`;var Jr=".agents/records/lifecycle",c4=`${Jr}/manifest.json`,l4=`${Jr}/entity-snapshot.json`,u4=`${Jr}/entity-state.json`,d4=`${Jr}/indexes`;var _4=`${Jr}/summary.json`,p4=`${Jr}/overview.json`,m4=`${Jr}/active-work.json`;var Gb=De.z.enum(["prd","spec","change","task","execution","run","decision","validation","evidence"]),f4=Gb.options,YU=De.z.enum(["parent","child","references","evidence","requirement"]),QU=De.z.enum(["explicit","derived"]),e1=De.z.object({target_id:De.z.string().min(1),type:YU,direction:De.z.enum(["outbound","inbound"]),provenance:QU,source_locator:De.z.string().min(1).nullable().default(null)}).strict(),t1=De.z.object({input_tokens:De.z.number().int().nonnegative().nullable().default(null),output_tokens:De.z.number().int().nonnegative().nullable().default(null),cached_input_tokens:De.z.number().int().nonnegative().nullable().default(null),total_tokens:De.z.number().int().nonnegative().nullable().default(null),cost:De.z.number().nonnegative().nullable().default(null),currency:De.z.string().min(1).nullable().default(null)}).strict(),n1=De.z.object({kind:Gb,id:De.z.string().min(1),title:De.z.string().min(1).nullable().default(null),status:De.z.string().min(1).nullable().default(null),risk:De.z.string().min(1).nullable().default(null),priority:De.z.string().min(1).nullable().default(null),updated_at:De.z.string().datetime({offset:!0}),relations:De.z.array(De.z.string().min(1)).default([]),relation_edges:De.z.array(e1).optional(),usage:t1.nullable().default(null),data:De.z.record(De.z.string(),De.z.unknown()).nullable().default(null)}).strict(),g4=De.z.object({schema_version:De.z.literal(1),event_id:De.z.string().min(1),occurred_at:De.z.string().datetime({offset:!0}),operation:De.z.enum(["upsert","remove"]),entity:n1}).strict();var ot=Ie(Ne(),1);var s_=["objective","requirement_ids","acceptance_ids","write_scopes"],E4={simple:{level:"simple",requiredFields:[...s_,"verification"],optionalFields:["risk_notes","rollback"],maximumUnresolvedQuestions:0},standard:{level:"standard",requiredFields:[...s_,"included_scope","excluded_scope","design","risks","verification","rollback"],optionalFields:["rollout","open_questions"],maximumUnresolvedQuestions:2},complex:{level:"complex",requiredFields:[...s_,"problem","outcomes","included_scope","excluded_scope","architecture","security","dag","budgets","risks","rollout","rollback","verification","independent_reviewer"],optionalFields:["open_questions"],maximumUnresolvedQuestions:3}};var re=Ie(Ne(),1);var xe=Ie(Ne(),1),Xc=xe.z.enum(["test","eval","check","review","spec_review","quality_review","mutation","integration","cross_spec_e2e"]),Kb=xe.z.object({schema_version:xe.z.literal(2),assurance_version:xe.z.literal(1),profile:xe.z.enum(["task-lite","task-standard-2","task-standard-3","task-critical"]),risk:xe.z.enum(["lite","standard","critical"]),minimum_validation_artifacts:xe.z.number().int().positive(),maximum_validation_artifacts:xe.z.number().int().positive().nullable(),minimum_evidence_artifacts:xe.z.number().int().positive(),maximum_evidence_artifacts:xe.z.number().int().positive().nullable(),minimum_distinct_modalities:xe.z.number().int().positive(),complete_acceptance_coverage:xe.z.literal(!0),evidence_per_acceptance:xe.z.boolean(),requires_independent_verifier:xe.z.boolean(),requires_mutation_discrimination:xe.z.boolean(),minimum_mutation_kill_ratio:xe.z.number().min(0).max(1).nullable(),requires_rollback:xe.z.boolean(),requires_final_commit_evidence:xe.z.boolean(),requires_test:xe.z.boolean(),required_modalities:xe.z.array(Xc)}).strict().superRefine((e,t)=>{e.maximum_validation_artifacts!==null&&e.maximum_validation_artifacts<e.minimum_validation_artifacts&&t.addIssue({code:"custom",path:["maximum_validation_artifacts"],message:"maximum validation artifacts cannot be lower than the minimum"}),e.maximum_evidence_artifacts!==null&&e.maximum_evidence_artifacts<e.minimum_evidence_artifacts&&t.addIssue({code:"custom",path:["maximum_evidence_artifacts"],message:"maximum Evidence artifacts cannot be lower than the minimum"})});var x4=xe.z.object({schema_version:xe.z.literal(2),assurance_version:xe.z.literal(1),profile:xe.z.enum(["spec-delivery","prd-delivery"]),origin:xe.z.enum(["spec","prd"]),minimum_parent_validation_artifacts:xe.z.number().int().positive(),minimum_parent_evidence_artifacts:xe.z.number().int().positive(),minimum_distinct_modalities:xe.z.number().int().positive(),complete_acceptance_coverage:xe.z.literal(!0),requires_acceptance_matrix:xe.z.literal(!0),requires_independent_verifier:xe.z.literal(!0),integration_modality:xe.z.enum(["integration","cross_spec_e2e"]),evidence_per_acceptance:xe.z.boolean(),evidence_per_outcome:xe.z.boolean(),requires_mutation_discrimination:xe.z.boolean(),minimum_mutation_kill_ratio:xe.z.number().min(0).max(1).nullable(),requires_rollback:xe.z.boolean(),requires_final_commit_evidence:xe.z.boolean(),required_modalities:xe.z.array(Xc).min(3)}).strict();var Ei=re.z.string().datetime({offset:!0}),zo=re.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/).nullable(),c_=Cr(re.z.string().startsWith("AC-")).min(1),r1=re.z.object({kind:re.z.literal("isolated_git_worktree"),protocol:re.z.literal("committed_node_harness_v1").optional(),harness_path:re.z.string().min(1).optional(),harness_blob_sha:zo.unwrap().optional(),commit_sha:zo.unwrap(),tree_sha:zo.unwrap(),exit_code:re.z.number().int().min(-1),diagnostic:re.z.string().nullable().optional(),started_at:Ei,finished_at:Ei}).strict(),Xb={test:"TEST-",eval:"EVAL-",check:"CHECK-",review:"REVIEW-",spec_review:"REVIEW-SPEC-",quality_review:"REVIEW-QUALITY-",mutation:"MUT-",integration:"INT-",cross_spec_e2e:"E2E-"},C4=re.z.object({schema_version:re.z.literal(2),id:re.z.string().min(1),kind:Xc,task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,executed_at:Ei,command:re.z.string().min(1).nullable(),status:re.z.enum(["passed","failed","not_applicable"]),asserted_outcomes:Cr(re.z.string().min(1)).min(1),locators:Cr(re.z.string().min(1)).min(1),author_id:re.z.string().min(1),commit_sha:zo,candidate_execution:r1.nullable().optional(),not_applicable_reason:re.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{e.id.startsWith(Xb[e.kind])||t.addIssue({code:"custom",path:["id"],message:`${e.kind} validation id must start with ${Xb[e.kind]}`}),!c1(e.kind)&&e.command===null&&t.addIssue({code:"custom",path:["command"],message:`${e.kind} validation requires its executed command`}),Yb(e.status,e.not_applicable_reason,t),e.candidate_execution!==null&&e.candidate_execution!==void 0&&(Date.parse(e.candidate_execution.finished_at)<Date.parse(e.candidate_execution.started_at)&&t.addIssue({code:"custom",path:["candidate_execution","finished_at"],message:"isolated validation cannot finish before it starts"}),e.commit_sha!==e.candidate_execution.commit_sha&&t.addIssue({code:"custom",path:["candidate_execution","commit_sha"],message:"isolated candidate execution must match validation commit"}),e.status==="passed"&&e.candidate_execution.exit_code!==0&&t.addIssue({code:"custom",path:["status"],message:"a non-zero isolated candidate exit code cannot pass validation"}))}),N4=re.z.object({schema_version:re.z.literal(2),id:re.z.string().startsWith("EVD-"),task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,outcome_ids:Cr(re.z.string().startsWith("OUT-")).default([]),validation_artifact_ids:Cr(re.z.string().min(1)).min(1),observed_at:Ei,status:re.z.enum(["passed","not_applicable"]),summary:re.z.string().min(1),locators:Cr(re.z.string().min(1)).min(1),commit_sha:zo,not_applicable_reason:re.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{Yb(e.status,e.not_applicable_reason,t)}),i1=re.z.enum(["confirmed","limited","pending","failed","not_applicable"]),o1=re.z.enum(["visual","interaction","api","database_schema","persistence","logs","integration"]),a1=re.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),$4=re.z.object({schema_version:re.z.literal(1),id:re.z.string().regex(/^OBS-[A-Z0-9]+(?:-[A-Z0-9]+)*$/),task_id:re.z.string().startsWith("TASK-"),change_id:re.z.string().startsWith("CHG-"),execution_id:re.z.string().startsWith("EXEC-"),run_id:re.z.string().startsWith("RUN-"),acceptance_ids:c_,proof_kind:o1,state:i1,scenario:re.z.string().min(1).nullable(),expected:re.z.string().min(1).nullable(),observed:re.z.string().min(1).nullable(),observed_at:Ei,examiner_id:re.z.string().min(1),commit_sha:a1.nullable(),candidate_version:re.z.string().min(1).nullable(),environment:re.z.object({class:re.z.string().min(1).nullable(),id:re.z.string().min(1).nullable(),version:re.z.string().min(1).nullable()}).strict(),visual:re.z.object({url:re.z.string().url(),viewport:re.z.string().regex(/^\d{2,5}x\d{2,5}$/),captured_at:Ei,loaded_version:re.z.string().min(1),examination:re.z.string().min(1)}).strict().nullable(),correlation_ids:Cr(re.z.string().min(1)).default([]),locators:Cr(re.z.string().min(1)).default([]),limitations:re.z.string().min(1).nullable(),not_applicable_reason:re.z.string().min(1).nullable(),pending_reason:re.z.string().min(1).nullable(),dependency:re.z.string().min(1).nullable(),resume_plan:re.z.string().min(1).nullable(),attempts:re.z.array(re.z.object({kind:re.z.enum(["initial","retry","alternative"]),recovery_action:re.z.string().min(1).nullable(),alternative_available:re.z.boolean().nullable()}).strict()).max(3)}).strict().superRefine((e,t)=>{let n=e.attempts.map(i=>i.kind);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["attempts"],message:"observations allow each attempt kind at most once"}),e.state!=="pending"&&e.state!=="not_applicable"&&n[0]!=="initial"&&t.addIssue({code:"custom",path:["attempts"],message:"settled observations require an initial attempt"}),n.join(",")!==[...n].sort(s1).join(",")&&t.addIssue({code:"custom",path:["attempts"],message:"observation attempts must be initial, retry, then alternative"});for(let[i,r]of e.attempts.entries())r.kind==="retry"&&(i===0||r.recovery_action===null)&&t.addIssue({code:"custom",path:["attempts",i],message:"retry observations require a preceding initial attempt and recovery_action"}),r.kind==="alternative"&&r.alternative_available!==!0&&t.addIssue({code:"custom",path:["attempts",i,"alternative_available"],message:"alternative observations require an available permitted mechanism"});if(e.state==="not_applicable"&&e.not_applicable_reason===null&&t.addIssue({code:"custom",path:["not_applicable_reason"],message:"not_applicable observations require a reason"}),e.state!=="not_applicable"&&e.not_applicable_reason!==null&&t.addIssue({code:"custom",path:["not_applicable_reason"],message:"applicable observations cannot retain a not-applicable reason"}),e.proof_kind!=="visual"&&e.visual!==null&&t.addIssue({code:"custom",path:["visual"],message:"only visual observations may include visual metadata"}),e.proof_kind==="visual"&&e.state==="confirmed"&&e.visual===null&&t.addIssue({code:"custom",path:["visual"],message:"confirmed visual observations require visual examination metadata"}),e.visual!==null){let i;try{i=new URL(e.visual.url)}catch{t.addIssue({code:"custom",path:["visual","url"],message:"visual URL must be a sanitized http(s) URL"});return}(i.protocol!=="http:"&&i.protocol!=="https:"||i.username||i.password||i.search||i.hash)&&t.addIssue({code:"custom",path:["visual","url"],message:"visual URL must be http(s) without credentials or query"})}e.state==="confirmed"&&e.locators.length===0&&t.addIssue({code:"custom",path:["locators"],message:"confirmed observations require locators"}),e.state==="confirmed"&&(e.candidate_version===null||e.environment.version===null)&&t.addIssue({code:"custom",path:["candidate_version"],message:"confirmed observations require observed candidate and environment versions"}),e.state==="confirmed"&&e.proof_kind==="integration"&&e.correlation_ids.length===0&&t.addIssue({code:"custom",path:["correlation_ids"],message:"confirmed integration observations require scenario correlation"}),e.state==="limited"&&e.limitations===null&&t.addIssue({code:"custom",path:["limitations"],message:"limited observations require a limitation"}),e.state==="pending"&&(e.pending_reason===null||e.dependency===null||e.resume_plan===null)&&t.addIssue({code:"custom",path:["pending_reason"],message:"pending observations require reason, dependency, and resume plan"}),e.state!=="pending"&&e.commit_sha===null&&t.addIssue({code:"custom",path:["commit_sha"],message:"settled observations require candidate commit"}),e.state!=="pending"&&(e.environment.class===null||e.environment.id===null)&&t.addIssue({code:"custom",path:["environment"],message:"settled observations require an identified environment"}),e.state!=="pending"&&(e.scenario===null||e.expected===null||e.observed===null)&&t.addIssue({code:"custom",message:"settled observations require scenario, expected, and observed"}),e.proof_kind==="visual"&&e.state==="confirmed"&&(e.candidate_version===null||e.visual===null||e.visual.loaded_version!==e.candidate_version)&&t.addIssue({code:"custom",path:["candidate_version"],message:"confirmed visual observations require candidate and loaded versions to agree"})});function Cr(e){return re.z.array(e).superRefine((t,n)=>{let i=new Set;for(let[r,o]of t.entries())i.has(o)&&n.addIssue({code:"custom",path:[r],message:`duplicate value: ${o}`}),i.add(o)})}function s1(e,t){return{initial:0,retry:1,alternative:2}[e]-{initial:0,retry:1,alternative:2}[t]}function Yb(e,t,n){e==="not_applicable"&&t===null&&n.addIssue({code:"custom",path:["not_applicable_reason"],message:"not-applicable artifacts require a reason"}),e!=="not_applicable"&&t!==null&&n.addIssue({code:"custom",path:["not_applicable_reason"],message:"applicable artifacts cannot retain a not-applicable reason"})}function c1(e){return e==="review"||e==="spec_review"||e==="quality_review"}var J=Ie(Ne(),1);var Qb=require("node:crypto");function eS(e){return(0,Qb.createHash)("sha256").update(JSON.stringify(l_(e))).digest("hex")}function l_(e){return Array.isArray(e)?e.map(l_):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,l_(n)])):e}var tS=Ie(Ne(),1),Yc=tS.z.string().min(1).superRefine((e,t)=>{(e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||/^[A-Za-z]:/.test(e)||e.split("/").some(n=>n.length===0||n==="."||n===".."))&&t.addIssue({code:"custom",message:"write_scope must be workspace-relative"})});var Wt=Ie(Ne(),1),l1=Wt.z.string().min(1).superRefine((e,t)=>{(e.toLowerCase()==="latest"||/[<>=~^*|,\s]/.test(e)||/(?:^|[.-])[xX](?:$|[.-])/.test(e))&&t.addIssue({code:"custom",message:"Expected an exact resolved version, not a range, wildcard, or moving tag"})}),u1=Wt.z.string().min(1).superRefine((e,t)=>{(e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.startsWith("./")||/^[A-Za-z]:/.test(e)||e.split("/").some(n=>n.length===0||n==="."||n===".."))&&t.addIssue({code:"custom",message:"version_source must be a canonical workspace-relative file path"})}),d1=Wt.z.object({name:Wt.z.string().min(1),kind:Wt.z.enum(["language","runtime","framework","library","persistence","database","tooling","platform"]),version:l1,version_source:u1}).strict(),Qc=Wt.z.object({stack_profile:Wt.z.string().min(1),stack_overrides:Wt.z.record(Wt.z.string(),Wt.z.unknown()),stack_description:Wt.z.string().min(20),stack_components:Wt.z.array(d1).min(1)}).strict().superRefine((e,t)=>{e.stack_components.some(i=>i.kind==="language")||t.addIssue({code:"custom",path:["stack_components"],message:"SPEC implementation requires at least one exact programming language"});let n=e.stack_description.toLocaleLowerCase("en");for(let[i,r]of e.stack_components.entries())(!n.includes(r.name.toLocaleLowerCase("en"))||!n.includes(r.version.toLocaleLowerCase("en")))&&t.addIssue({code:"custom",path:["stack_components",i],message:`stack_description must mention ${r.name} ${r.version}`})});var sn=Ie(Ne(),1),Rt=sn.z.string().datetime({offset:!0}),wi=sn.z.string().regex(/^[a-f0-9]{64}$/),Gr=sn.z.string().startsWith("PRD-"),Nr=sn.z.string().startsWith("SPEC-"),Ai=sn.z.string().startsWith("CHG-"),At=sn.z.string().startsWith("TASK-"),Ti=sn.z.string().startsWith("EXEC-"),$r=sn.z.string().startsWith("REQ-"),Kr=sn.z.string().startsWith("AC-"),nS=sn.z.string().startsWith("OUT-");var Oi=J.z.enum(["lite","standard","critical"]),_1=J.z.enum(["low","medium","high","urgent"]),Vo=J.z.object({revision:J.z.number().int().positive(),hash:wi,execution_id:Ti}).strict();var xi=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("task"),task_id:At}).strict(),J.z.object({type:J.z.literal("spec"),spec_id:Nr}).strict(),J.z.object({type:J.z.literal("prd"),prd_id:Gr}).strict()]),u_=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("task"),task_id:At}).strict(),J.z.object({type:J.z.literal("spec"),spec_id:Nr}).strict(),J.z.object({type:J.z.literal("prd"),prd_id:Gr,spec_id:Nr.nullable()}).strict()]),d_=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("none"),reason:J.z.string().min(1)}).strict(),J.z.object({type:J.z.literal("update"),requirement_ids:J.z.array($r).min(1)}).strict()]),iS=J.z.object({model:Os,reasoning_effort:sg,velocity:eu.optional()}).strict(),oS=iS.extend({client:J.z.string().min(1),provider:J.z.string().min(1)}).strict(),el=J.z.object({failure_policy:J.z.enum(["stop_on_terminal_failure","continue_independent"]),max_parallelism:J.z.number().int().positive(),independent_branches:J.z.boolean().optional(),max_cost_usd:J.z.number().nonnegative().nullable().optional(),max_operational_retries:J.z.number().int().nonnegative(),max_repair_cycles_per_task:J.z.number().int().nonnegative(),soft_model_cycle_budget:J.z.number().int().positive().optional(),soft_input_token_budget:J.z.number().int().positive().optional(),context_refresh_after_cycles:J.z.number().int().positive().optional(),verification_mode:J.z.enum(["scoped","full"]).optional(),runtime_defaults:oS.optional()}).strict(),__=el.extend({runtime_defaults:oS.extend({model:J.z.union([Os,J.z.enum(["gpt-5.6-luna","gpt-5.6-terra","gpt-5.6-sol"])])}).optional()}),aS=J.z.string().regex(/^[a-z][a-z0-9-]*$/),sS=J.z.object({key:aS,id:Ai,title:J.z.string().min(1),short_name:J.z.string().min(1),risk:Oi,source:u_,requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),requirement_impact:d_}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t)}),cS=J.z.object({id:Nr,title:J.z.string().min(1),short_name:J.z.string().min(1),objective:J.z.string().min(1),summary:J.z.string().min(1),risk:Oi,included_scope:J.z.array(Yc).min(1),excluded_scope:J.z.array(Yc),requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),implementation:Qc,rollout:J.z.string().min(1),fallback:J.z.string().min(1),model_signals:Cs}).strict().superRefine((e,t)=>{Zt(e.included_scope,"included_scope",t),Zt(e.excluded_scope,"excluded_scope",t),Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t)}),lS={key:aS,id:At,change_id:Ai,title:J.z.string().min(1),short_name:J.z.string().min(1),objective:J.z.string().min(1),priority:_1,owner:J.z.string().min(1).nullable(),requirement_ids:J.z.array($r).min(1),acceptance_ids:J.z.array(Kr).min(1),write_scopes:J.z.array(Yc),runtime:iS.optional()},p1=J.z.object({...lS,risk:Oi,model_profile:jr.optional()}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t),Zt(e.write_scopes,"write_scopes",t)}),m1=J.z.object({...lS,risk:Oi.optional(),model_signals:Cs.optional(),model_profile:jr.optional()}).strict().superRefine((e,t)=>{Zt(e.requirement_ids,"requirement_ids",t),Zt(e.acceptance_ids,"acceptance_ids",t),Zt(e.write_scopes,"write_scopes",t)}),uS=J.z.object({task_id:At,depends_on:J.z.array(At)}).strict().superRefine((e,t)=>{e.depends_on.includes(e.task_id)&&t.addIssue({code:"custom",path:["depends_on"],message:"self dependency"}),Zt(e.depends_on,"depends_on",t)}),f1=J.z.object({revision:J.z.number().int().positive(),source:xi,execution_id:Ti,prepared_at:Rt,policy:el,blueprints:J.z.object({specs:J.z.array(cS).min(1).optional(),changes:J.z.array(sS).min(1),tasks:J.z.array(m1).min(1)}).strict(),dag:J.z.object({nodes:J.z.array(uS).min(1)}).strict()}).strict(),g1=f1.extend({schema_version:J.z.literal(2),policy:__,blueprints:J.z.object({specs:J.z.array(cS).min(1).optional(),changes:J.z.array(sS).min(1),tasks:J.z.array(p1).min(1)}).strict(),dag:J.z.object({nodes:J.z.array(uS).min(1),topological_order:J.z.array(At).min(1)}).strict(),hash:wi}).strict(),Ri=g1.superRefine((e,t)=>{for(let n of dS(e))t.addIssue({code:"custom",path:[...n.path],message:n.message})});function dS(e){let t=[],n=new Map(e.blueprints.changes.map(c=>[c.id,c])),i=new Map(e.blueprints.tasks.map(c=>[c.id,c])),r=new Map((e.blueprints.specs??[]).map(c=>[c.id,c]));qo(e.blueprints.changes.map(c=>c.key),"duplicate-key",["blueprints","changes"],t),qo((e.blueprints.specs??[]).map(c=>c.id),"duplicate-id",["blueprints","specs"],t),qo(e.blueprints.tasks.map(c=>c.key),"duplicate-key",["blueprints","tasks"],t),qo([...e.blueprints.changes,...e.blueprints.tasks].map(c=>c.id),"duplicate-id",["blueprints"],t);for(let[c,u]of e.blueprints.tasks.entries()){u.model_profile!==void 0&&u.risk!==u.model_profile.risk&&t.push({rule:"risk-classification",path:["blueprints","tasks",c,"risk"],message:`Task risk ${u.risk} does not match classified risk ${u.model_profile.risk}`});let d=n.get(u.change_id);if(d===void 0){t.push({rule:"missing-change",path:["blueprints","tasks",c,"change_id"],message:`${u.change_id} does not resolve`});continue}for(let p of u.requirement_ids)d.requirement_ids.includes(p)||t.push({rule:"requirement-outside-change",path:["blueprints","tasks",c,"requirement_ids"],message:`${p} is absent from ${d.id}`});for(let p of u.acceptance_ids)d.acceptance_ids.includes(p)||t.push({rule:"acceptance-outside-change",path:["blueprints","tasks",c,"acceptance_ids"],message:`${p} is absent from ${d.id}`})}for(let[c,u]of e.blueprints.changes.entries())[...i.values()].some(d=>d.change_id===u.id)||t.push({rule:"change-without-task",path:["blueprints","changes",c],message:`${u.id} has no task`}),v1(e.source,u.source)||t.push({rule:"source-mismatch",path:["blueprints","changes",c,"source"],message:`${u.id} source does not match the prepared plan source`}),e.source.type==="prd"&&u.source.type==="prd"&&u.source.spec_id===null&&t.push({rule:"prd-change-without-spec",path:["blueprints","changes",c,"source","spec_id"],message:`${u.id} must belong to a SPEC of ${e.source.prd_id}`}),e.source.type==="prd"&&u.source.type==="prd"&&u.source.spec_id!==null&&e.blueprints.specs!==void 0&&!r.has(u.source.spec_id)&&t.push({rule:"missing-spec-blueprint",path:["blueprints","changes",c,"source","spec_id"],message:`${u.source.spec_id} requires a composite SPEC blueprint`});if(e.blueprints.specs!==void 0&&e.source.type==="prd"){let c=e.source.prd_id,u=new Set(e.blueprints.changes.flatMap(p=>p.source.type==="prd"&&p.source.prd_id===c?[p.source.spec_id]:[]));for(let[p,m]of e.blueprints.specs.entries()){u.has(m.id)||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"id"],message:`${m.id} has no PRD Change`});for(let f of m.requirement_ids)e.blueprints.changes.some(g=>g.source.type==="prd"&&g.source.spec_id===m.id&&g.requirement_ids.includes(f))||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"requirement_ids"],message:`${f} is not used by ${m.id}`});for(let f of m.acceptance_ids)e.blueprints.changes.some(g=>g.source.type==="prd"&&g.source.spec_id===m.id&&g.acceptance_ids.includes(f))||t.push({rule:"orphan-spec-blueprint",path:["blueprints","specs",p,"acceptance_ids"],message:`${f} is not used by ${m.id}`})}let d=new Map(e.blueprints.tasks.map(p=>{let m=n.get(p.change_id);return[p.id,m?.source.type==="prd"?m.source.spec_id:null]}));for(let[p,m]of e.dag.nodes.entries())for(let f of m.depends_on){let g=d.get(m.task_id),h=d.get(f);g!==null&&h!==null&&g!==h&&t.push({rule:"cross-spec-dependency",path:["dag","nodes",p,"depends_on"],message:`${m.task_id} crosses SPEC boundary; compose it into one SPEC instead`})}for(let p=0;p<e.blueprints.specs.length;p+=1)for(let m=p+1;m<e.blueprints.specs.length;m+=1){let f=e.blueprints.specs[p],g=e.blueprints.specs[m];if(f===void 0||g===void 0)continue;let h=f.included_scope.find(S=>g.included_scope.some(E=>rS(S,E)));h!==void 0&&t.push({rule:"overlapping-spec-scope",path:["blueprints","specs"],message:`${f.id} and ${g.id} overlap at ${h}; compose them into one SPEC`})}}e.source.type==="spec"&&e.blueprints.specs!==void 0&&(e.blueprints.specs.length!==1||e.blueprints.specs[0]?.id!==e.source.spec_id)&&t.push({rule:"missing-spec-blueprint",path:["blueprints","specs"],message:`SPEC plan must contain exactly its source blueprint ${e.source.spec_id}`}),e.source.type==="task"&&!i.has(e.source.task_id)&&t.push({rule:"missing-task",path:["source","task_id"],message:`${e.source.task_id} does not resolve`});let o=new Map(e.dag.nodes.map(c=>[c.task_id,c]));qo(e.dag.nodes.map(c=>c.task_id),"duplicate-id",["dag","nodes"],t);for(let c of i.values())o.has(c.id)||t.push({rule:"missing-task",path:["dag","nodes"],message:`${c.id} is missing from the DAG`});for(let[c,u]of e.dag.nodes.entries()){i.has(u.task_id)||t.push({rule:"missing-task",path:["dag","nodes",c,"task_id"],message:`${u.task_id} does not resolve`});for(let d of u.depends_on)d===u.task_id?t.push({rule:"self-dependency",path:["dag","nodes",c,"depends_on"],message:`${u.task_id} depends on itself`}):i.has(d)||t.push({rule:"missing-dependency",path:["dag","nodes",c,"depends_on"],message:`${d} does not resolve`})}let a=y1(e.dag.nodes);if(a.length!==i.size?t.push({rule:"cycle",path:["dag"],message:"DAG contains a cycle"}):JSON.stringify(a)!==JSON.stringify(e.dag.topological_order)&&t.push({rule:"topological-order",path:["dag","topological_order"],message:"topological_order is not canonical"}),a.length===i.size){let c=h1(e.dag.nodes),u=[...i.values()];for(let d=0;d<u.length;d+=1)for(let p=d+1;p<u.length;p+=1){let m=u[d],f=u[p];if(m===void 0||f===void 0)continue;let g=m.write_scopes.find(S=>f.write_scopes.some(E=>rS(S,E)));if(g===void 0)continue;c.get(m.id)?.has(f.id)===!0||c.get(f.id)?.has(m.id)===!0||t.push({rule:"overlapping-write-scope",path:["blueprints","tasks"],message:`${m.id} and ${f.id} may overlap at ${g}; add a DAG dependency`})}}let{hash:s,...l}=e;return eS(l)!==e.hash&&t.push({rule:"hash",path:["hash"],message:"prepared plan hash does not match"}),t}function y1(e){let t=new Set(e.map(a=>a.task_id)),n=new Map(e.map(a=>[a.task_id,0])),i=new Map;for(let a of e)for(let s of new Set(a.depends_on))!t.has(s)||s===a.task_id||(n.set(a.task_id,(n.get(a.task_id)??0)+1),i.set(s,[...i.get(s)??[],a.task_id]));let r=[...n].filter(([,a])=>a===0).map(([a])=>a).sort(),o=[];for(;r.length>0;){let a=r.shift();o.push(a);for(let s of(i.get(a)??[]).sort()){let l=(n.get(s)??0)-1;n.set(s,l),l===0&&(r.push(s),r.sort())}}return o}function h1(e){let t=new Map(e.map(r=>[r.task_id,r.depends_on])),n=new Map,i=(r,o)=>{let a=n.get(r);if(a!==void 0)return a;if(o.has(r))return new Set;let s=new Set;for(let l of t.get(r)??[]){s.add(l);for(let c of i(l,new Set([...o,r])))s.add(c)}return n.set(r,s),s};for(let r of t.keys())i(r,new Set);return n}function rS(e,t){if(e===t)return!0;let n=e.search(/[*?]/),i=t.search(/[*?]/);if(n===-1&&i===-1)return!1;let r=e.slice(0,n===-1?e.length:n).replace(/\/$/,""),o=t.slice(0,i===-1?t.length:i).replace(/\/$/,"");return r===o||r.startsWith(`${o}/`)||o.startsWith(`${r}/`)}function v1(e,t){return e.type!==t.type?!1:e.type==="task"&&t.type==="task"?e.task_id===t.task_id:e.type==="spec"&&t.type==="spec"?e.spec_id===t.spec_id:e.type==="prd"&&t.type==="prd"&&e.prd_id===t.prd_id}function qo(e,t,n,i){let r=new Set;for(let o of e)r.has(o)&&i.push({rule:t,path:n,message:`Duplicate value: ${o}`}),r.add(o)}function Zt(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var F=Ie(Ne(),1);var b1=F.z.object({schema_version:F.z.literal(2),id:Gr,revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","ready","active","delivered","blocked","failed","cancelled"]),status_reason:F.z.string().min(1).nullable().default(null),outcome_status:F.z.enum(["unmeasured","measuring","met","not_met","inconclusive"]),problem:F.z.string().min(1),audiences:F.z.array(F.z.string().min(1)),outcomes:F.z.array(F.z.string().min(1)),outcome_ids:F.z.array(nS),constraints:F.z.array(F.z.string().min(1)),non_goals:F.z.array(F.z.string().min(1)),prepared_plan:Ri.nullable(),plan_ref:Vo.nullable().default(null),creation_run_id:F.z.string().startsWith("RUN-").nullable().default(null),rework_of_prd_id:Gr.nullable().default(null),tags:F.z.array(F.z.string().min(1)).default([]),created_at:Rt,updated_at:Rt}).strict().superRefine((e,t)=>{e.prepared_plan!==null&&e.plan_ref!==null&&t.addIssue({code:"custom",message:"PRD cannot contain prepared_plan and plan_ref"}),e.outcome_ids.length!==e.outcomes.length&&t.addIssue({code:"custom",path:["outcome_ids"],message:"PRD outcome_ids must identify every declared outcome exactly once"}),new Set(e.outcome_ids).size!==e.outcome_ids.length&&t.addIssue({code:"custom",path:["outcome_ids"],message:"PRD outcome_ids must be unique"})}),S1=F.z.preprocess(I1,b1),k1=F.z.object({schema_version:F.z.literal(2),id:Nr,prd_id:Gr.nullable(),revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","ready","active","delivered","blocked","failed","cancelled"]),status_reason:F.z.string().min(1).nullable().default(null),objective:F.z.string().min(1),included_scope:F.z.array(F.z.string().min(1)),excluded_scope:F.z.array(F.z.string().min(1)),requirement_ids:F.z.array($r),acceptance_ids:F.z.array(Kr),implementation:Qc.nullable().default(null),prepared_plan:Ri.nullable(),plan_ref:Vo.nullable().default(null),creation_run_id:F.z.string().startsWith("RUN-").nullable().default(null),created_at:Rt,updated_at:Rt}).strict().superRefine((e,t)=>{e.prepared_plan!==null&&e.plan_ref!==null&&t.addIssue({code:"custom",message:"SPEC cannot contain prepared_plan and plan_ref"})}),_S=F.z.object({schema_version:F.z.literal(2),id:Ai,revision:F.z.number().int().positive(),title:F.z.string().min(1),status:F.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:F.z.string().min(1).nullable().optional(),risk:Oi,source:u_,requirement_ids:F.z.array($r).min(1),acceptance_ids:F.z.array(Kr).min(1),requirement_impact:d_,task_ids:F.z.array(At).min(1),plan_revision:F.z.number().int().positive().nullable(),plan_hash:wi.nullable(),created_at:Rt,updated_at:Rt,started_at:Rt.nullable(),finished_at:Rt.nullable(),result:F.z.string().min(1).nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||(e.status==="blocked"||e.status==="cancelled")&&n?n||t.addIssue({code:"custom",message:"draft Change cannot contain a prepared plan"}):(n||e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Change requires plan_revision and plan_hash`}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Change requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Change requires started_at`})}),Wo=F.z.object({task_id:At,change_id:Ai,depends_on:F.z.array(At)}).strict(),E1=F.z.object({max_total_invocations:F.z.number().int().positive().nullable(),cancelled:F.z.boolean().default(!1),finalizer_scope:F.z.enum(["spec","parent"]).default("spec")}).strict(),w1=F.z.record(Nr,E1).optional(),Zo={schema_version:F.z.literal(2),id:Ti,parent_execution_id:Ti.nullable().optional(),revision:F.z.number().int().positive(),status:F.z.enum(["planned","running","paused","verifying","completed","failed","blocked","cancelled"]),status_reason:F.z.string().min(1).nullable().optional(),policy:__,spec_execution_policies:w1,created_at:Rt,updated_at:Rt,started_at:Rt.nullable(),finished_at:Rt.nullable(),result:F.z.string().min(1).nullable()},A1=F.z.object({...Zo,kind:F.z.literal("delivery").optional(),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,plan_revision:F.z.number().int().positive(),plan_hash:wi,dag:F.z.object({nodes:F.z.array(Wo).min(1),topological_order:F.z.array(At).min(1)}).strict()}).strict(),T1=F.z.object({...Zo,kind:F.z.literal("delivery"),client_turn_id:F.z.string().min(1).max(200),origin:xi,status:F.z.enum(["planned","blocked"]),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),O1=F.z.object({...Zo,kind:F.z.literal("delivery"),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,status:F.z.literal("cancelled"),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),x1=F.z.object({...Zo,kind:F.z.literal("interaction"),client_turn_id:F.z.string().min(1).max(200),origin:F.z.object({type:F.z.literal("interaction"),conversation_id:F.z.string().startsWith("CONV-")}).strict(),plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),R1=F.z.object({...Zo,kind:F.z.literal("interaction"),client_turn_id:F.z.string().min(1).max(200).nullable().optional(),origin:xi,plan_revision:F.z.null(),plan_hash:F.z.null(),dag:F.z.object({nodes:F.z.array(Wo).length(0),topological_order:F.z.array(At).length(0)}).strict()}).strict(),p_=F.z.union([x1,R1,O1,T1,A1]).superRefine((e,t)=>{e.status==="blocked"&&e.status_reason==null&&t.addIssue({code:"custom",message:"blocked Execution requires status_reason"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Execution requires finished_at and result"}),["running","paused","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Execution requires started_at`})});function I1(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Object.hasOwn(t,"outcome_ids")||typeof t.id!="string"||!Array.isArray(t.outcomes)?e:{...t,outcome_ids:pS(t.id,t.outcomes)}}function pS(e,t){let n=e.replace(/^PRD-/,"OUT-");return t.map((i,r)=>`${n}-${String(r+1).padStart(2,"0")}`)}var N1=["lite","standard","critical"],tl=ot.z.string().datetime({offset:!0}),zH=ot.z.object({id:ot.z.string().startsWith("SPEC-"),capability:ot.z.string().min(1),title:ot.z.string().min(1),status:ot.z.enum(["active","deprecated"]).default("active"),version:ot.z.number().int().positive().default(1),updated_at:tl}).strict();var qH=ot.z.object({id:ot.z.string().startsWith("CHG-"),title:ot.z.string().min(1),status:ot.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:ot.z.enum(N1),capabilities:ot.z.array(ot.z.string().startsWith("SPEC-")),requirements:ot.z.array(ot.z.string().startsWith("REQ-")),tasks:ot.z.array(ot.z.string().startsWith("TASK-")),human_decisions:ot.z.array(ot.z.string().startsWith("DEC-HUMAN-")),agent_decisions:ot.z.array(ot.z.string().startsWith("DEC-AI-")),created_at:tl,updated_at:tl,completed_at:tl.nullable().default(null)}).strict();var pt=Ie(Ne(),1);var Xr=["validate","develop","review","fix","verify","close"];var Bo=Ie(Ne(),1);var VJ=5*6e4;var tG=Bo.z.object({hypothesis:Bo.z.string().trim().min(1),test:Bo.z.string().trim().min(1),executor_model:Bo.z.enum(["gpt-6-luna","gpt-6-sol","gpt-6-astra"])}).strict();var Lr=Ie(Ne(),1),Jo=Lr.z.object({outcome:Lr.z.enum(["completed","blocked","failed","cancelled"]),summary:Lr.z.string().trim().min(1),evidence_ids:Lr.z.array(Lr.z.string().min(1)),changed_files:Lr.z.array(Lr.z.string().min(1))}).strict();var y=Ie(Ne(),1);var h_=y.z.string().datetime(),v_=y.z.object({id:y.z.string().min(1),acceptance_ids:y.z.array(y.z.string().min(1))}).strict(),Z1=y.z.object({soft_cycles:y.z.number().int().positive(),max_attempts:y.z.number().int().positive().nullable()}).strict(),B1=y.z.object({phase:y.z.enum(Xr),event_id:y.z.string().min(1),state_hash:y.z.string().regex(/^[a-f0-9]{64}$/),cycles:y.z.number().int().nonnegative(),input_tokens:y.z.number().int().nonnegative().nullable(),measurement_source:y.z.enum(["provider-uncached-input","observable-context-fallback","unavailable"]),checkpoint_required:y.z.boolean()}).strict(),H1=y.z.object({schema_version:y.z.literal(1),id:y.z.string().min(1),phase:y.z.enum(Xr),status:y.z.enum(["running","blocked","completed"]),revision:y.z.number().int().positive(),acceptance_ids:y.z.array(y.z.string().min(1)).min(1),budgets:y.z.object(Object.fromEntries(Xr.map(e=>[e,Z1]))),attempts:y.z.object(Object.fromEntries(Xr.map(e=>[e,y.z.number().int().nonnegative()]))),checkpoints:y.z.array(B1),evidence:y.z.array(v_),processed_event_ids:y.z.array(y.z.string().min(1)),blocker:y.z.string().min(1).nullable()}).strict(),il=y.z.enum(["execution_override","task_override","automatic_policy","project_defaults"]),J1=y.z.enum(["EXECUTION_OVERRIDE","TASK_OVERRIDE","XHIGH_ELIGIBLE","SIMPLE_BOUNDED_WORK","SOL_PLANNING_OR_REVIEW","SOL_AMBIGUOUS_OR_TRANSVERSAL","SOL_STRUCTURAL_REWORK","ASTRA_DIAGNOSTIC","ASTRA_HANDBACK","SOL_IMPLEMENTATION_BASELINE","TERRA_IMPLEMENTATION_BASELINE","PROJECT_DEFAULTS","RISK_ASSURANCE_ONLY"]),G1=y.z.object({model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]),velocity:y.z.literal("standard"),origin:il,sources:y.z.object({model:il,reasoning_effort:il,velocity:il}).strict(),policy_version:y.z.string().min(1),reasons:y.z.array(J1).min(1)}).strict(),K1=y.z.object({invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/),run_id:y.z.string().min(1).nullable().default(null),phase:y.z.enum(Xr),role:y.z.enum(["builder","verifier","finalizer"]),checkpoint_id:y.z.string().min(1).nullable(),checkpoint_hash:y.z.string().regex(/^[a-f0-9]{64}$/).nullable(),selection:G1.nullable().default(null)}).strict(),X1=y.z.object({astra_diagnostic:Rs.optional(),rework:y.z.enum(["localized","structural"]),rework_cost:y.z.enum(["medium","high"]),findings:y.z.array(y.z.string().min(1)).default([]),complexity:y.z.enum(["simple","standard","complex"]),transversality:y.z.enum(["local","multi_module","cross_system"]),ambiguity:y.z.enum(["low","medium","high"]),bounded:y.z.boolean(),high_volume:y.z.boolean(),xhigh_triggers:y.z.array(y.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"]))}).strict(),vS=y.z.object({task_id:y.z.string().min(1),status:y.z.enum(["available","unavailable","quality_below_floor"]),evidence_ids:y.z.array(y.z.string().min(1)),validation_ids:y.z.array(y.z.string().min(1)),rework_count:y.z.number().int().nonnegative().nullable(),quality_score:y.z.number().nonnegative().nullable(),quality_floor:y.z.number().nonnegative().nullable(),cost_delta_usd:y.z.number().nullable(),economy_status:y.z.enum(["available","unavailable"])}).strict(),Y1=y.z.object({baseline_task_id:y.z.string().min(1).nullable(),baseline_equivalence_id:y.z.string().min(1).nullable(),model:y.z.string().min(1).nullable(),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).nullable(),context_budget_tokens:y.z.number().int().nonnegative().nullable(),cached_context_tokens:y.z.number().int().nonnegative().nullable(),early_stop_reason:y.z.string().min(1).nullable(),retry_count:y.z.number().int().nonnegative().nullable(),rework_count:y.z.number().int().nonnegative().nullable(),observed_cost_usd:y.z.number().nonnegative().nullable(),baseline_observed_cost_usd:y.z.number().nonnegative().nullable(),quality_score:y.z.number().nonnegative().nullable(),quality_floor:y.z.number().nonnegative().nullable()}).strict(),Q1=y.z.object({provider:y.z.enum(["codex","claude"]),host_authentication_available:y.z.boolean(),requires_external_provider:y.z.boolean(),requires_remote_operation:y.z.boolean()}).strict(),eF=y.z.object({identity:y.z.string().min(1),replay_key:y.z.string().regex(/^[a-f0-9]{64}$/),validation_ids:y.z.array(y.z.string().min(1)),evidence_ids:y.z.array(y.z.string().min(1))}).strict(),tF=y.z.object({candidate_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/).nullable(),proof_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/),semantic_attempts:y.z.number().int().nonnegative(),classification:y.z.enum(["unknown","localized","structural"]),proof_delta:y.z.enum(["none","added","replaced"]),repeated_without_delta:y.z.boolean(),elapsed_reassessment:y.z.literal("unavailable"),decision:y.z.enum(["shadow_continue","shadow_rereview","shadow_block"])}).strict(),nF=y.z.object({id:y.z.string().min(1),rule:y.z.string(),path:y.z.string(),line:y.z.number().int().positive(),severity:y.z.enum(["low","medium","high","critical"]),message:y.z.string(),status:y.z.enum(["open","resolved","waived"]),resolution_evidence_id:y.z.string().nullable()}).strict(),rF=y.z.object({id:y.z.string().min(1),executor_id:y.z.string().min(1),reviewer_id:y.z.string().min(1),max_repair_cycles:y.z.number().int().nonnegative().nullable(),repair_cycles:y.z.number().int().nonnegative(),findings:y.z.array(nF),reviewer_approved:y.z.boolean()}).strict(),iF=y.z.object({autonomy:Ql.optional(),finalizer_decision:Jo.optional(),recovery_invocation:y.z.object({id:y.z.string().min(1),run_id:y.z.string().nullable()}).strict().optional(),recovery_plan:y.z.object({hypothesis:y.z.string().min(1),test:y.z.string().min(1),executor_model:y.z.string().min(1)}).strict().optional(),id:y.z.string().min(1),change_id:y.z.string().min(1),title:y.z.string().min(1),objective:y.z.string().min(1),risk:y.z.enum(["lite","standard","critical"]),priority:y.z.number().int(),depends_on:y.z.array(y.z.string().min(1)),acceptance_ids:y.z.array(y.z.string().min(1)).min(1),write_scopes:y.z.array(y.z.string().min(1)),scope_receipt:y.z.object({receipt_id:y.z.string().min(1),current_scopes:y.z.array(y.z.string().min(1)),delta_scopes:y.z.array(y.z.string().min(1))}).optional(),child_execution_id:y.z.string().min(1).optional(),builder:y.z.object({id:y.z.string().min(1),model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).optional(),tools:y.z.array(y.z.string()).optional(),execution_eligibility:y.z.array(y.z.enum(["interaction","delivery"])).optional()}).optional(),verifier:y.z.object({id:y.z.string().min(1),model:y.z.string().min(1),reasoning_effort:y.z.enum(["low","medium","high","xhigh"]).optional(),tools:y.z.array(y.z.string()).optional(),execution_eligibility:y.z.array(y.z.enum(["interaction","delivery"])).optional()}).optional(),commit:y.z.object({agent:y.z.enum(["CODEX","CLAUDE"]),execution_id:y.z.string().min(1),change_id:y.z.string().min(1),task_id:y.z.string().min(1),title:y.z.string().min(1),prd_id:y.z.string().min(1).nullable(),spec_id:y.z.string().min(1).nullable()}).strict().optional(),runtime:xs.optional(),model_profile:jr.optional(),assurance_contract:Kb.optional(),outcome_measurement:Y1.optional(),status:y.z.enum(["planned","running","completed","failed","blocked"]),worktree_path:y.z.string().min(1).nullable(),integration_commit:y.z.string().min(1).nullable(),changed_files:y.z.array(y.z.string().min(1)).default([]),task_run_id:y.z.string().min(1).nullable().default(null),finalizer_approved:y.z.boolean().default(!1),closure_pending:y.z.boolean().default(!1),finalization_pending:y.z.boolean().default(!1),lifecycle_cleanup:y.z.object({handoff_path:y.z.string().min(1),invocation_run_id:y.z.string().min(1).nullable(),task_run_id:y.z.string().min(1).nullable(),invocation_finished:y.z.boolean(),task_finished:y.z.boolean(),last_error:y.z.string().nullable()}).strict().optional(),active_invocation:K1.nullable(),active_diagnostic:y.z.object({invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/),run_id:y.z.string().min(1).nullable(),status:y.z.enum(["requested","completed","blocked"]),cycle:y.z.union([y.z.literal(1),y.z.literal(2),y.z.literal(3)]),evidence_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/),executor_attempt_id:y.z.string().min(1).nullable(),handback:Is.nullable()}).strict().nullable().default(null),handback:Is.nullable().default(null),last_executor_invocation_id:y.z.string().min(1).nullable().default(null),rework_profile:X1.nullable().default(null),sdc:H1,validation_ids:y.z.array(y.z.string().min(1)),evidence:y.z.array(v_),outcome_projection:vS.nullable().default(null),validation_attempts:y.z.array(eF).default([]),convergence_observations:y.z.array(tF).default([]),qa_session:rF.nullable().default(null),qa_pending_resolutions:y.z.array(y.z.object({finding_id:y.z.string().min(1),evidence_id:y.z.string().min(1)}).strict()).default([]),qa_approval_observed:y.z.boolean().default(!1),qa_review_candidate_fingerprint:y.z.string().regex(/^[a-f0-9]{64}$/).nullable().default(null),last_error:y.z.string().min(1).nullable()}).strict(),AK=y.z.object({schema_version:y.z.literal(1),execution_id:y.z.string().min(1),lease_ms:y.z.number().int().min(5e3).max(Number.MAX_SAFE_INTEGER).nullable().default(null),source:y.z.enum(["task","spec","prd"]),operational_context:Q1.default({provider:"codex",host_authentication_available:!1,requires_external_provider:!1,requires_remote_operation:!1}),status:y.z.enum(["running","completed","failed","blocked"]),revision:y.z.number().int().nonnegative(),created_at:h_,updated_at:h_,execution_started_at:h_.nullable().default(null),invocation_count:y.z.number().int().nonnegative().default(0),stalled_cycles:y.z.number().int().nonnegative().default(0),handoff_worktree_path:y.z.string().min(1).nullable().default(null),handoff_branch:y.z.string().min(1).nullable().default(null),handoff_commit:y.z.string().min(1).nullable().default(null),parent_acceptance:y.z.object({run_id:y.z.string().min(1).nullable(),finalizer_run_id:y.z.string().min(1).nullable().default(null),invocation_id:y.z.string().regex(/^INV-[A-Z0-9-]+$/).nullable().default(null),checkpoint_id:y.z.string().min(1).nullable().default(null),checkpoint_hash:y.z.string().min(1).nullable().default(null),candidate:y.z.object({handoff_worktree_path:y.z.string().min(1),handoff_commit:y.z.string().min(1),validation_ids:y.z.array(y.z.string().min(1)),evidence:y.z.array(v_),task_outcomes:y.z.array(y.z.object({task_id:y.z.string().min(1),integration_commit:y.z.string().min(1),changed_files:y.z.array(y.z.string().min(1)),outcome_projection:vS.nullable()}).strict())}).strict().nullable().default(null),decision_observed:y.z.boolean().default(!1),decision:Jo.optional(),status:y.z.enum(["pending","approved","blocked"])}).default({run_id:null,finalizer_run_id:null,invocation_id:null,checkpoint_id:null,checkpoint_hash:null,candidate:null,decision_observed:!1,status:"pending"}),tasks:y.z.array(iF).min(1),last_error:y.z.string().min(1).nullable()}).strict();var Xe=Ie(Ne(),1);var cn=Ie(Ne(),1),b_=cn.z.object({editorial_delivery:cn.z.boolean().optional(),production_impact:cn.z.boolean().optional(),external_action:cn.z.boolean().optional(),irreversible_change:cn.z.boolean().optional(),security_or_critical_data:cn.z.boolean().optional(),data_migration:cn.z.boolean().optional(),broad_audit:cn.z.boolean().optional(),rollback:cn.z.enum(["trivial","planned","complex"]).optional(),verification_scope:cn.z.enum(["scoped","package","cross_scope","full"]).optional()}).strict();var gr=Ie(Ne(),1),S_=gr.z.preprocess(e=>typeof e=="string"?{summary:e,changed_files:[],evidence_ids:[],completed_run_id:null}:e,gr.z.object({summary:gr.z.string().min(1),changed_files:gr.z.array(gr.z.string().min(1)),evidence_ids:gr.z.array(gr.z.string().startsWith("EVD-")),completed_run_id:gr.z.string().startsWith("RUN-").nullable()}).strict());function Go(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var ol=Xe.z.string().datetime({offset:!0}),aF=Xe.z.string().regex(/^[a-f0-9]{64}$/),bS=Xe.z.string().startsWith("TASK-"),sF=Xe.z.string().startsWith("CHG-"),cF=Xe.z.string().startsWith("REQ-"),lF=Xe.z.string().startsWith("AC-"),mY=Xe.z.object({schema_version:Xe.z.literal(2),id:bS,revision:Xe.z.number().int().positive(),change_id:sF,title:Xe.z.string().min(1),short_name:Xe.z.string().min(1),objective:Xe.z.string().min(1),status:Xe.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:Xe.z.string().min(1).nullable().optional(),attempt_count:Xe.z.number().int().nonnegative().optional(),risk:Xe.z.enum(["lite","standard","critical"]),priority:Xe.z.enum(["low","medium","high","urgent"]),owner:Xe.z.string().min(1).nullable(),requirement_ids:Xe.z.array(cF).min(1),acceptance_ids:Xe.z.array(lF).min(1),depends_on:Xe.z.array(bS),write_scopes:Xe.z.array(Xe.z.string().min(1)),runtime:xs.optional(),model_profile:jr.optional(),assurance_risk_signals:b_.optional(),assurance_risk_signals_source:Xe.z.enum(["explicit","risk_default"]).optional(),plan_revision:Xe.z.number().int().positive().nullable(),plan_hash:aF.nullable(),prepared_plan:Ri.optional(),plan_ref:Vo.optional(),created_at:ol,updated_at:ol,started_at:ol.nullable(),finished_at:ol.nullable(),result:S_.nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||n&&["blocked","failed","cancelled"].includes(e.status)?(!n||e.prepared_plan!==void 0||e.plan_ref!==void 0)&&t.addIssue({code:"custom",message:`${e.status} Task without materialization cannot contain a prepared plan`}):(e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Task requires plan_revision and plan_hash`}),e.prepared_plan!==void 0&&e.plan_ref!==void 0&&t.addIssue({code:"custom",message:"Task cannot contain prepared_plan and plan_ref"}),e.plan_ref!==void 0&&e.plan_ref.hash!==e.plan_hash&&t.addIssue({code:"custom",path:["plan_ref"],message:"plan_ref must match plan_hash"}),e.prepared_plan!==void 0&&(e.prepared_plan.source.type!=="task"||e.prepared_plan.source.task_id!==e.id||e.prepared_plan.hash!==e.plan_hash)&&t.addIssue({code:"custom",path:["prepared_plan"],message:"prepared_plan must belong to the Task and match plan_hash"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Task requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Task requires started_at`}),e.status==="completed"&&(e.result?.completed_run_id===null||e.result?.evidence_ids.length===0)&&t.addIssue({code:"custom",path:["result"],message:"completed Task requires completed_run_id and at least one Evidence"}),Go(e.requirement_ids,"requirement_ids",t),Go(e.acceptance_ids,"acceptance_ids",t),Go(e.depends_on,"depends_on",t),Go(e.write_scopes,"write_scopes",t)});var k_=pt.z.string().datetime({offset:!0}),vY=pt.z.object({id:pt.z.string().startsWith("TASK-"),title:pt.z.string().min(1),short_name:pt.z.string().min(1),status:pt.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:pt.z.enum(["lite","standard","critical"]),priority:pt.z.enum(["low","medium","high","urgent"]),owner:pt.z.string().min(1).nullable().default(null),progress:pt.z.number().int().min(0).max(100),spec:pt.z.string().startsWith("SPEC-"),change:pt.z.string().startsWith("CHG-"),requirements:pt.z.array(pt.z.string().startsWith("REQ-")),depends_on:pt.z.array(pt.z.string().startsWith("TASK-")),human_decisions:pt.z.array(pt.z.string().startsWith("DEC-HUMAN-")),agent_decisions:pt.z.array(pt.z.string().startsWith("DEC-AI-")),created_at:k_,started_at:k_.nullable(),finished_at:k_.nullable()}).strict();function TS(e){let t={};for(let n of["prd_count","spec_count","task_count","total_run_count","validation_count","evidence_count","total_duration","total_tokens","total_cost_usd","total_cost_brl"]){let i=e.map(r=>r[n]).filter(r=>typeof r=="number"&&Number.isFinite(r));t[n]=i.length===0?null:i.reduce((r,o)=>r+o,0)}return t.duration_known=t.total_duration??0,t.duration_unknown=e.reduce((n,i)=>n+(typeof i.duration_unknown=="number"?i.duration_unknown:typeof i.total_duration!="number"?1:0),0),t}function al(e){let t=e.map(n=>{let i=r=>typeof n[r]=="number"&&Number.isFinite(n[r])?n[r]:null;return{task_count:i("task_count"),spec_count:i("spec_count"),prd_count:i("prd_count"),duration_ms:i("total_duration"),total_tokens:i("total_tokens"),estimated_usd:i("total_cost_usd"),estimated_brl:i("total_cost_brl")}});return{BRL:Vc(t,"BRL"),USD:Vc(t,"USD")}}function OS(e,t,n,i){let r=i==="day"||i==="month"||i==="year",o,a,s=i==="day"?"date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours')":i==="month"?"substr(date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours'), 1, 7)":i==="year"?"substr(date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours'), 1, 4)":"i.provider_group",l=[`${s} IS NOT NULL`,"(i.total_tokens IS NOT NULL OR i.cost_usd IS NOT NULL OR i.cost_brl IS NOT NULL)"],c=[];n.from&&(l.push("date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours') >= ?"),c.push(Ke(n.from))),n.to&&(l.push("date(COALESCE(i.source_started_at, i.source_occurred_at, i.occurred_at), '-3 hours') <= ?"),c.push(Ke(n.to)));let u=[];if(n.provider&&(n.provider==="unavailable"?l.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_provider WHERE known_provider.agent_invocation_id=i.agent_invocation_id AND known_provider.provider IS NOT NULL AND known_provider.provider <> 'unavailable')"):(u.push("f.provider=?"),c.push(n.provider))),n.model&&(n.model==="unavailable"?l.push("NOT EXISTS (SELECT 1 FROM invocation_usage known_model WHERE known_model.agent_invocation_id=i.agent_invocation_id AND known_model.model IS NOT NULL AND known_model.model <> 'unavailable')"):(u.push("f.model=?"),c.push(n.model))),u.length>0&&l.push(`EXISTS (SELECT 1 FROM invocation_usage f WHERE f.agent_invocation_id=i.agent_invocation_id AND ${u.join(" AND ")})`),n.agent&&(l.push("i.zaip_agent = ?"),c.push(n.agent)),n.phase&&(l.push("i.phase = ?"),c.push(n.phase)),n.status&&(l.push("COALESCE(i.task_status, i.status) = ?"),c.push(n.status)),n.priority&&(l.push("i.task_priority = ?"),c.push(n.priority)),n.risk&&(l.push("i.task_risk = ?"),c.push(n.risk)),n.origin&&l.push(n.origin==="prd"?"i.prd_id IS NOT NULL":n.origin==="spec"?"i.prd_id IS NULL AND i.spec_id IS NOT NULL":n.origin==="task"?"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NOT NULL":"i.prd_id IS NULL AND i.spec_id IS NULL AND i.task_id IS NULL"),n.workType&&(l.push("i.work_type = ?"),c.push(n.workType)),n.query){let E=`%${n.query}%`;l.push("(i.agent_invocation_id LIKE ? OR i.execution_id LIKE ? OR i.task_id LIKE ? OR i.spec_id LIKE ? OR i.prd_id LIKE ? OR i.conversation_id LIKE ? OR i.zaip_agent LIKE ? OR i.purpose LIKE ?)"),c.push(E,E,E,E,E,E,E,E)}let d=`WITH usage_rollup AS (
|
|
709
709
|
SELECT agent_invocation_id,
|
|
710
710
|
CASE COUNT(DISTINCT provider) WHEN 0 THEN NULL WHEN 1 THEN MIN(provider) ELSE 'mixed' END AS provider_group,
|
|
711
711
|
CASE COUNT(DISTINCT model) WHEN 0 THEN NULL WHEN 1 THEN MIN(model) ELSE 'mixed' END AS model_group,
|
|
@@ -949,7 +949,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
949
949
|
WHERE payload_type IN (${sl.map(()=>"?").join(", ")})`).get(...sl.map(([r])=>r)).count??0)!==sl.length)return!1;let n=NS(e,"first_fold_all_time_board_cache"),i=NS(e,"first_fold_monthly_quick_cache");return n!==null&&i!==null&&$S(e,n)&&$S(e,i,!0)}function PS(e,t){let n=e.prepare(`INSERT INTO zaip_aios_activities(
|
|
950
950
|
activity_row_id, activity_source_kind, activity_key, source_path, source_hash,
|
|
951
951
|
recorded_at, run_role, root_run_id, payload_type, payload_json
|
|
952
|
-
) VALUES (?, 'technical_payload', ?, ?, '', datetime('now'), 'technical', 'technical', ?, ?)`);for(let[i,r]of sl){let o=e.prepare("SELECT activity_row_id,payload_json FROM zaip_aios_activities WHERE payload_type=? AND activity_key=?").get(i,r);if(o){o.payload_json!==t[i]&&e.prepare("UPDATE zaip_aios_activities SET payload_json=?,recorded_at=datetime('now') WHERE activity_row_id=?").run(t[i],o.activity_row_id);continue}n.run(`TECH-${(0,LS.randomUUID)().toLowerCase()}`,r,`sqlite://${i}/${r.split(":")[1]}`,i,t[i])}}var T_=".local/sqlite/zaip-aios-dashboard.sqlite",lr="84",O_=["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"],cl=["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_duration_activity","zaip_activities_file_path","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"],x_=["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"],
|
|
952
|
+
) VALUES (?, 'technical_payload', ?, ?, '', datetime('now'), 'technical', 'technical', ?, ?)`);for(let[i,r]of sl){let o=e.prepare("SELECT activity_row_id,payload_json FROM zaip_aios_activities WHERE payload_type=? AND activity_key=?").get(i,r);if(o){o.payload_json!==t[i]&&e.prepare("UPDATE zaip_aios_activities SET payload_json=?,recorded_at=datetime('now') WHERE activity_row_id=?").run(t[i],o.activity_row_id);continue}n.run(`TECH-${(0,LS.randomUUID)().toLowerCase()}`,r,`sqlite://${i}/${r.split(":")[1]}`,i,t[i])}}var T_=".local/sqlite/zaip-aios-dashboard.sqlite",lr="84",O_=["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"],cl=["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_duration_activity","zaip_activities_file_path","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"],x_=["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"],s5=2*36e5;function Yr(e){return(0,w_.resolve)(process.env.ZAIP_SQLITE_DB_PATH??(0,w_.resolve)(e,T_))}function ll(e){if(!(0,DS.existsSync)(e))return new Map;let t;try{t=new A_.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 Ci(e){let t=new A_.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(f=>f.type==="table").map(f=>f.name).sort(),o=[...O_].sort();if(r.length!==o.length||r.some((f,g)=>f!==o[g]))throw new Error(`SQLite schema ${lr} requires the complete persisted table contract; found ${r.join(", ")||"none"}`);let a=t.prepare("PRAGMA table_info(operations_work_projection)").all(),s=new Set(a.flatMap(f=>typeof f.name=="string"?[f.name]:[])),l=["task_count","rework_run_count"].filter(f=>!s.has(f));if(l.length>0)throw new Error(`SQLite schema ${lr} requires operations_work_projection columns: ${l.join(", ")}`);let c=new Set(i.map(f=>f.name)),u=x_.filter(f=>!c.has(f));if(u.length>0)throw new Error(`SQLite schema is missing required views: ${u.join(", ")}`);let d=i.filter(f=>f.type==="view").map(f=>f.name);if(d.some(f=>!f.startsWith("zaip_vw_")))throw new Error("SQLite persisted views must use the zaip_vw_ namespace");let p=cl.filter(f=>!c.has(f));if(p.length>0)throw new Error(`SQLite schema is missing required indexes: ${p.join(", ")}`);let m=t.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = ?").get("schema_version")?.value;if(m!==lr)throw new Error(`SQLite schema version must be ${lr}; found ${m??"missing"}`);return{schemaVersion:m,tableCount:r.length,viewCount:d.length,indexCount:i.filter(f=>f.type==="index"&&!f.name.startsWith("sqlite_")).length}}finally{t.close()}}function ul(e){let t=e.prepare("SELECT name FROM sqlite_master WHERE type='index'").all(),n=new Set(t.map(i=>i.name));return cl.every(i=>n.has(i))&&MS(e)}var jS=require("node:sqlite");function R_(e,t,n,i){let r;try{r=new jS.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 I_(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)}`)}}function US(e,t){return encodeURIComponent(JSON.stringify([e,t]))}function FS(e){if(e===null)return null;try{let t=JSON.parse(decodeURIComponent(e));return Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string"?[t[0],t[1]]:null}catch{return null}}var Ni=class extends Io{executionDurationCache=new Map;dailyAggregateRowsCache=null;firstFoldAllTimeCache=null;firstFoldAllTimeBoardCache=null;firstFoldTopTasksAllTimeCache=null;firstFoldViewportCache=null;firstFoldMonthlyQuickCache=void 0;firstFoldViewportTimings={};metadataValues=null;unfilteredViewPageCache=new Map;technicalPayloadRowsCache=new Map;viewPageResultCache=new Map;costMonitorSummaryCache=new Map;canonicalSource(){return this.database.prepare("SELECT 1 FROM files WHERE path LIKE '.agents/data/%' LIMIT 1").get()===void 0?".agents/records":".agents/data"}dailyAggregateRows(){return this.dailyAggregateRowsCache===null&&(this.dailyAggregateRowsCache=this.database.prepare("SELECT * FROM daily_aggregate_cache ORDER BY day").all()),this.dailyAggregateRowsCache}unfilteredViewRows(t){let n=this.unfilteredViewPageCache.get(t);if(n!==void 0)return n;let i=Ii[t].order,r=this.database.prepare(`SELECT * FROM ${t} ORDER BY ${i}`).all();return this.unfilteredViewPageCache.set(t,r),r}technicalPayloadRows(t){let n=this.technicalPayloadRowsCache.get(t);if(n!==void 0)return n;let i=this.database.prepare("SELECT payload_json FROM zaip_aios_activities WHERE payload_type=?").all(t).flatMap(({payload_json:r})=>{try{let o=JSON.parse(r);return o!==null&&typeof o=="object"&&!Array.isArray(o)?[o]:[]}catch{return[]}});return this.technicalPayloadRowsCache.set(t,i),i}database;ownsDatabase;constructor(t,n){super(t),this.ownsDatabase=n===void 0,this.database=n??new C_.DatabaseSync(Yr(t),{readOnly:!0}),I_(this.database)}async exists(t){let n=this.database.prepare("SELECT 1 FROM files WHERE path = ? LIMIT 1").get(t),i=this.database.prepare("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1").get(`${t.replace(/\/$/,"")}/%`);return n!==void 0||i!==void 0}async readText(t){let n=this.database.prepare("SELECT content FROM files WHERE path = ?").get(t);if(n?.content===void 0)throw Object.assign(new Error(`SQLite read model is missing ${t}`),{code:"ENOENT"});return n.content}async readBytes(t){return Buffer.from(await this.readText(t),"utf8")}async readTextFrom(t,n){let i=await this.readText(t),r=Buffer.from(i,"utf8");return{content:r.subarray(Math.min(n,r.byteLength)).toString("utf8"),nextOffset:r.byteLength}}async listFiles(t,n=""){let i=`${t.replace(/\/$/,"")}/%`;return this.database.prepare("SELECT path FROM files WHERE path LIKE ? ORDER BY path").all(i).map(o=>o.path).filter(o=>o.endsWith(n))}async listDirectories(t){let n=`${t.replace(/\/$/,"")}/`,i=this.database.prepare("SELECT path FROM files WHERE path LIKE ?").all(`${n}%`);return[...new Set(i.map(r=>r.path.slice(n.length).split("/")[0]).filter(Boolean).map(r=>`${t.replace(/\/$/,"")}/${r}`))].sort()}close(){this.ownsDatabase&&this.database.close()}reopen(){this.database=new C_.DatabaseSync(Yr(this.root),{readOnly:!0}),I_(this.database),this.executionDurationCache.clear(),this.dailyAggregateRowsCache=null,this.firstFoldAllTimeCache=null,this.firstFoldAllTimeBoardCache=null,this.firstFoldTopTasksAllTimeCache=null,this.firstFoldViewportCache=null,this.firstFoldMonthlyQuickCache=void 0,this.firstFoldViewportTimings={},this.metadataValues=null,this.unfilteredViewPageCache.clear(),this.technicalPayloadRowsCache.clear(),this.costMonitorSummaryCache.clear(),this.viewPageResultCache.clear()}refresh(){this.database.close(),this.reopen()}async rebuildAndRefresh(t){this.database.close();try{await t()}finally{this.reopen()}this.viewPage("cost_monitor_daily",{limit:1,offset:0})}executionDurationByDay(t,n=null){return Qv(this.queryContext(),t,n)}canonicalRunCountByDay(t){return eb(this.queryContext(),t)}dailyPeriods(t){return tb(this.queryContext(),t)}firstFoldAggregate(t){return nb(this.queryContext(),t)}firstFoldMonthlyQuick(t){let n=Pv(this.database,this.firstFoldMonthlyQuickCache,t);return this.firstFoldMonthlyQuickCache=n.cache,n.result}firstFoldRelevantLatestDay(){let t=this.database.prepare(`SELECT MAX(day) AS day FROM (
|
|
953
953
|
SELECT occurred_day_sp AS day FROM activities
|
|
954
954
|
UNION ALL SELECT occurred_day_sp AS day FROM canonical_work_items
|
|
955
955
|
UNION ALL SELECT occurred_day_sp AS day FROM canonical_artifacts
|