@zaip-ai/cli 6.0.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/services/adapters.d.ts +1 -1
  2. package/dist/services/adapters.js +1 -1
  3. package/package.json +1 -1
  4. package/templates/.agents/README-ENG.md +2 -0
  5. package/templates/.agents/README.md +2 -0
  6. package/templates/.agents/config/agents/discovery.json +1 -1
  7. package/templates/.agents/dashboard/.zaip-managed.json +29 -29
  8. package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-CUxpAtio.js → DashboardHelpDialog-Bni7muep.js} +3 -1
  9. package/templates/.agents/dashboard/apps/frontend/dist/assets/{PricingSettingsDialog-niZbV_Wq.js → PricingSettingsDialog-Cctm7uaW.js} +1 -1
  10. package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-DuVzb5-X.js → ProjectSettingsPage-D61ZJG4L.js} +1 -1
  11. package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-DMZXmueM.js → TraceabilityWorkspace-B4VQDPo5.js} +1 -1
  12. package/templates/.agents/dashboard/apps/frontend/dist/assets/{dashboard-localization-EGxe0WHD.js → dashboard-localization-ykDJSpnb.js} +2 -0
  13. package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-CZe1F8Q4.js → index-mZ3OmU_0.js} +2 -2
  14. package/templates/.agents/dashboard/apps/frontend/dist/index.html +1 -1
  15. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  16. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  17. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  18. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  19. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  20. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  21. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  22. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +152 -152
  23. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +90 -90
  24. package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
  25. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +152 -152
  26. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  27. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  28. package/templates/.agents/design/.zaip-managed.json +3 -3
  29. package/templates/.agents/design/apps/catalog/package.json +1 -1
  30. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  31. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  32. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  33. package/templates/.agents/requirements/comparative-audit.md +1 -1
  34. package/templates/.agents/requirements/context-engine.md +1 -1
  35. package/templates/.agents/requirements/cost-observability.md +1 -1
  36. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  37. package/templates/.agents/requirements/data-export.md +1 -1
  38. package/templates/.agents/requirements/design-system.md +1 -1
  39. package/templates/.agents/requirements/execution-engine.md +1 -1
  40. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  41. package/templates/.agents/requirements/model-orchestration.md +1 -1
  42. package/templates/.agents/requirements/public-distribution.md +1 -1
  43. package/templates/.agents/requirements/software-architecture.md +1 -1
  44. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  45. package/templates/.agents/requirements/work-lifecycle.md +1 -1
  46. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  47. package/templates/.agents/rules/core.md +7 -6
  48. package/templates/.agents/runtime/VERSION +1 -1
  49. package/templates/.agents/runtime/bin/zaip.mjs +13 -13
  50. package/templates/.agents/runtime/checksums.sha256 +5 -5
  51. package/templates/.agents/runtime/manifest.json +1 -1
  52. package/templates/.agents/runtime/provenance.json +4 -4
  53. package/templates/.agents/runtime/sbom.cdx.json +1 -1
  54. package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +3 -2
  55. package/templates/.agents/skills/zaip-skill-github-deploy/references/release-identity.md +3 -1
  56. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract-patch.test-support.mjs +25 -0
  57. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.mjs +1 -1
  58. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.test.mjs +2 -0
  59. package/templates/.agents/skills/zaip-skill-release-qualification/SKILL.md +2 -0
  60. package/templates/.agents/skills/zaip-skill-release-qualification/references/local-preparation.md +14 -0
  61. package/templates/template-manifest.json +72 -68
@@ -93,7 +93,7 @@ ${yaml}
93
93
  ${FRONTMATTER_BOUNDARY}
94
94
 
95
95
  ${body}
96
- `}var import_yaml3,FRONTMATTER_BOUNDARY,MAX_SAFE_ALIAS_COUNT2,MarkdownContractError;var init_markdown=__esm({"../core/src/markdown.ts"(){"use strict";import_yaml3=__toESM(require_dist(),1);FRONTMATTER_BOUNDARY="---";MAX_SAFE_ALIAS_COUNT2=10;MarkdownContractError=class extends Error{name="MarkdownContractError"}}});function parseRuleDocument(source){return parseMarkdown(source,ruleMetadataSchema)}function parseRequirementDocument(source){const document=parseMarkdown(source,requirementMetadataSchema);if(!/^## REQ-[A-Z0-9-]+\s/m.test(document.body)){throw new Error("Requirement document must declare at least one REQ section")}if(!/`?AC-[A-Z0-9-]+`?/m.test(document.body)){throw new Error("Requirement document must declare at least one Acceptance Criterion")}return document}function buildRequirementReferenceCatalog(sources){const requirementIds=new Set;const acceptanceIds=new Set;const requirementAliases=new Map;const acceptanceAliases=new Map;for(const source of sources){const document=parseRequirementDocument(source);if(document.metadata.status==="deprecated"){collectAliases(document.body,"REQ",requirementAliases);collectAliases(document.body,"AC",acceptanceAliases);continue}for(const match of document.body.matchAll(/^##\s+(REQ-[A-Z0-9-]+)(?:\s|$)/gm)){if(match[1]!==void 0)requirementIds.add(match[1])}for(const match of document.body.matchAll(/^\s*-\s+`?(AC-[A-Z0-9-]+)`?\s*:/gm)){if(match[1]!==void 0)acceptanceIds.add(match[1])}}const resolvedRequirementAliases=resolvedAliases(requirementAliases,requirementIds);const resolvedAcceptanceAliases=resolvedAliases(acceptanceAliases,acceptanceIds);return{requirement_ids:[...requirementIds].sort(),acceptance_ids:[...acceptanceIds].sort(),requirement_aliases:Object.fromEntries(resolvedRequirementAliases),acceptance_aliases:Object.fromEntries(resolvedAcceptanceAliases)}}function validateRequirementReferences(catalog,requirementIds,acceptanceIds){const knownRequirements=new Set(catalog.requirement_ids);const knownAcceptance=new Set(catalog.acceptance_ids);const findings=[];for(const id of[...new Set(requirementIds)].sort()){if(!knownRequirements.has(id)&&catalog.requirement_aliases[id]===void 0){findings.push({kind:"requirement",id,message:`Requirement does not resolve: ${id}`})}}for(const id of[...new Set(acceptanceIds)].sort()){if(!knownAcceptance.has(id)&&catalog.acceptance_aliases[id]===void 0){findings.push({kind:"acceptance",id,message:`Acceptance Criterion does not resolve: ${id}`})}}return findings}function collectAliases(body,prefix,aliases){const expression=new RegExp(`^\\s*-\\s+\\x60(${prefix}-[A-Z0-9-]+)\\x60\\s*->\\s*\\x60(${prefix}-[A-Z0-9-]+)\\x60`,"gm");for(const match of body.matchAll(expression)){const source=match[1];const target=match[2];if(source===void 0||target===void 0)continue;const existing=aliases.get(source);if(existing!==void 0&&existing!==target){throw new Error(`Divergent ${prefix} alias: ${source}`)}aliases.set(source,target)}}function resolvedAliases(aliases,canonicalIds){const resolved=[];for(const[source,target]of aliases){if(!canonicalIds.has(target)){throw new Error(`Alias target does not resolve: ${source} -> ${target}`)}resolved.push([source,target])}return resolved.sort(([left],[right])=>left.localeCompare(right))}var ruleMetadataSchema,requirementMetadataSchema;var init_governance=__esm({"../core/src/governance.ts"(){"use strict";init_zod();init_markdown();ruleMetadataSchema=external_exports.object({id:external_exports.string().regex(/^RULE-[A-Z0-9-]+$/),load:external_exports.enum(["always","auto","file_match","manual"]),globs:external_exports.array(external_exports.string().min(1)).default([]),priority:external_exports.enum(["critical","high","medium","low"]),max_context_tokens:external_exports.number().int().positive(),requires:external_exports.array(external_exports.string().regex(/^RULE-[A-Z0-9-]+$/)),triggers:external_exports.array(external_exports.string().min(1)).default([]),phases:external_exports.array(external_exports.enum(["conversation","definition","planning","execution","verification","evidence"])).default([]),domains:external_exports.array(external_exports.string().min(1)).default([])}).strict().superRefine((metadata3,context2)=>{if(metadata3.load==="file_match"&&metadata3.globs.length===0){context2.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}});requirementMetadataSchema=external_exports.object({schema_version:external_exports.literal(2),id:external_exports.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:external_exports.string().regex(/^[a-z][a-z0-9-]*$/),title:external_exports.string().min(1),status:external_exports.enum(["proposed","active","deprecated"]),version:external_exports.number().int().positive(),source_change:external_exports.string().min(1).nullable(),source_release:external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((metadata3,context2)=>{if(metadata3.source_change===null&&metadata3.source_release===void 0){context2.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata3.source_change!==null&&metadata3.source_release!==void 0){context2.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})}})}});function validateCodexFirstRoute(input){const profile=hostCapabilityProfileSchema.parse(input.profile);if(profile.default_mode!=="codex_host_native"||!input.host_authentication_available){return{status:"exception",code:"host_authentication_unavailable"}}if(input.requires_external_provider===true){return{status:"exception",code:"external_provider_required"}}if(input.requires_remote_operation===true){return{status:"exception",code:"remote_operation_required"}}return{status:"valid",authentication:"host",remote_provider_required:false}}async function loadHostCapabilityProfile(filesystem,path=".agents/config/models/codex-host.yaml"){return hostCapabilityProfileSchema.parse(parseYaml(await filesystem.readText(path)))}var HOST_EXECUTION_MODES,MODEL_CLASSES,CODEX_NATIVE_SURFACES,hostExecutionModeSchema,modelClassSchema,codexNativeSurfaceSchema,uniqueNativeSurfacesSchema,hostCapabilityEvidenceSchema,implementedHostCapabilityClaimSchema,nativeModeProfileSchema,subprocessModeProfileSchema,modelClassProfileSchema,hostCapabilityProfileSchema,providerSubprocessOptInSchema;var init_contracts2=__esm({"../core/src/host-capabilities/contracts.ts"(){"use strict";init_zod();init_yaml();HOST_EXECUTION_MODES=["codex_host_native","provider_subprocess"];MODEL_CLASSES=["frontier","balanced","fast_scan","review"];CODEX_NATIVE_SURFACES=["subagents","worktrees","sandbox","approvals","skills","mcp"];hostExecutionModeSchema=external_exports.enum(HOST_EXECUTION_MODES);modelClassSchema=external_exports.enum(MODEL_CLASSES);codexNativeSurfaceSchema=external_exports.enum(CODEX_NATIVE_SURFACES);uniqueNativeSurfacesSchema=external_exports.array(codexNativeSurfaceSchema).min(1).refine(surfaces=>new Set(surfaces).size===surfaces.length,{message:"native_surfaces must be unique"});hostCapabilityEvidenceSchema=external_exports.object({locator:external_exports.string().min(1),candidate_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();implementedHostCapabilityClaimSchema=external_exports.object({capability_id:external_exports.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:external_exports.literal("implemented"),previous_states:external_exports.tuple([external_exports.literal("declared")]),evidence:external_exports.array(hostCapabilityEvidenceSchema).length(0)}).strict();nativeModeProfileSchema=external_exports.object({tier:external_exports.literal(1),enabled:external_exports.literal(true),optional:external_exports.literal(false),invokes_provider_subprocess:external_exports.literal(false),authority:external_exports.literal("host"),native_surfaces:uniqueNativeSurfacesSchema,capability_bindings:external_exports.record(codexNativeSurfaceSchema,implementedHostCapabilityClaimSchema)}).strict().superRefine((mode,context2)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context2.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}});subprocessModeProfileSchema=external_exports.object({tier:external_exports.union([external_exports.literal(2),external_exports.literal(3)]),enabled:external_exports.boolean(),optional:external_exports.literal(true),invokes_provider_subprocess:external_exports.literal(true),authority:external_exports.literal("framework"),native_surfaces:external_exports.array(external_exports.never()).length(0),opt_in:external_exports.object({required:external_exports.literal(true),allowed_sources:external_exports.array(external_exports.enum(["project_config","human_decision"])).min(1).refine(sources=>new Set(sources).size===sources.length,{message:"opt-in sources must be unique"})}).strict()}).strict();modelClassProfileSchema=external_exports.object({selection:external_exports.enum(["host_available","inherit_host"]),reasoning:external_exports.enum(["low","medium","high"]),intent:external_exports.string().min(1)}).strict();hostCapabilityProfileSchema=external_exports.object({schema_version:external_exports.literal(1),host_id:external_exports.literal("codex"),candidate_sha256:external_exports.null(),default_mode:external_exports.literal("codex_host_native"),modes:external_exports.object({codex_host_native:nativeModeProfileSchema,provider_subprocess:subprocessModeProfileSchema}).strict(),model_classes:external_exports.object({frontier:modelClassProfileSchema,balanced:modelClassProfileSchema,fast_scan:modelClassProfileSchema,review:modelClassProfileSchema}).strict()}).strict();providerSubprocessOptInSchema=external_exports.object({enabled:external_exports.literal(true),source:external_exports.enum(["project_config","human_decision"]),provenance:external_exports.object({reference:external_exports.string().min(1),recorded_at:external_exports.string().datetime({offset:true})}).strict()}).strict()}});var init_host_capabilities=__esm({"../core/src/host-capabilities/index.ts"(){"use strict";init_contracts2()}});function lifecycleClaimPath(kind,digest14){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest14}.json`}var LIFECYCLE_CLAIMS_ROOT;var init_lifecycle_claims=__esm({"../core/src/lifecycle-claims.ts"(){"use strict";LIFECYCLE_CLAIMS_ROOT=".local/claims"}});function parseZaipManifest(value){return zaipManifestSchema.parse(value)}var zaipManifestSchema,zaipManifestJsonSchema,ManifestRepository;var init_manifest=__esm({"../core/src/manifest.ts"(){"use strict";init_zod();init_yaml();zaipManifestSchema=external_exports.object({schema_version:external_exports.literal(1),project:external_exports.object({id:external_exports.string().min(1),name:external_exports.string().min(1),timezone:external_exports.string().min(1).default("America/Sao_Paulo")}),framework:external_exports.object({version:external_exports.string().min(1)}),layout:external_exports.object({version:external_exports.literal(1),managed_namespace:external_exports.string().min(1).default(".agents/managed"),project_namespace:external_exports.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:external_exports.object({id:external_exports.string().min(1).default("zaip-aios-stack")}),paths:external_exports.object({specs:external_exports.string().min(1).default(".agents/specs"),changes:external_exports.string().min(1).default(".agents/changes"),tasks:external_exports.string().min(1).default(".agents/tasks"),decisions:external_exports.string().min(1).default(".agents/decisions"),runs:external_exports.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:external_exports.array(external_exports.enum(["codex","claude"])).default(["codex","claude"])}).strict();zaipManifestJsonSchema=external_exports.toJSONSchema(zaipManifestSchema);ManifestRepository=class{constructor(filesystem,path=".agents/manifest.yaml"){this.filesystem=filesystem;this.path=path}filesystem;path;async read(){return parseZaipManifest(parseYaml(await this.filesystem.readText(this.path)))}async write(manifest){await this.filesystem.writeTextAtomic(this.path,serializeYaml(zaipManifestSchema.parse(manifest)))}}}});function datedIdPartsWithDay(id){const match=id.match(/^([A-Z]+(?:-[A-Z]+)*)-(\d{4})-(\d{2})-(\d{2})-\d{2}-\d{2}-/);if(match?.[1]===void 0||match[2]===void 0||match[3]===void 0||match[4]===void 0){throw new TypeError(`ID does not contain the canonical date: ${id}`)}const[,prefix,year,month,day]=match;const date5=new Date(`${year}-${month}-${day}T00:00:00.000Z`);if(Number.isNaN(date5.getTime())||String(date5.getUTCFullYear()).padStart(4,"0")!==year||String(date5.getUTCMonth()+1).padStart(2,"0")!==month||String(date5.getUTCDate()).padStart(2,"0")!==day){throw new TypeError(`ID contains an invalid canonical date: ${id}`)}return{prefix,year,month,day}}function datedIdParts(id){const{year,month}=datedIdPartsWithDay(id);return{year,month}}function datedMarkdownPath(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}/${id}.md`}function datedMonthDirectory(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}`}function datedEntityDirectory(basePath,id){const{year,month,day}=datedIdPartsWithDay(id);return`${basePath}/${year}/${month}/${day}`}var init_paths=__esm({"../core/src/paths.ts"(){"use strict"}});function redactSensitive(value){return value.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/g,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/\bgh[opsu]_[A-Za-z0-9_]{8,}\b/g,"[REDACTED]").replace(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]")}var init_permissions=__esm({"../core/src/policy/permissions/permissions.ts"(){"use strict"}});var init_permissions2=__esm({"../core/src/policy/permissions/index.ts"(){"use strict";init_permissions()}});var init_routing=__esm({"../core/src/policy/routing/routing.ts"(){"use strict"}});var init_routing2=__esm({"../core/src/policy/routing/index.ts"(){"use strict";init_routing()}});function assertSafeRecordContent(value){const seen=new WeakSet;function visit(item,key=""){if(typeof item==="string"){if(item.length===0||placeholder.test(item))return;if(sensitiveKey.test(key)||unsafeText(item)){throw new Error("Sensitive content cannot be persisted; redact credentials and sensitive URL parameters first.")}return}if(item===null||typeof item!=="object"||seen.has(item))return;seen.add(item);for(const[childKey,child]of Object.entries(item)){visit(child,sensitiveKey.test(key)?key:childKey)}}visit(value)}function unsafeText(text){if(redactSensitive(text)!==text)return true;if(/\bbearer\s+[a-z0-9._~+/-]+=*/i.test(text))return true;for(const match of text.matchAll(/\bbasic\s+([a-z0-9+/]+={0,2})/gi)){if(Buffer.from(match[1]??"","base64").toString("utf8").includes(":"))return true}if(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text))return true;for(const match of text.matchAll(/[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+/gi)){try{const url2=new URL(match[0]);if(url2.password||/^https?:$/.test(url2.protocol)&&url2.username)return true;for(const[key,value]of url2.searchParams){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}for(const[key,value]of new URLSearchParams(url2.hash.slice(1))){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}text=text.replace(match[0],"")}catch{}}for(const match of text.matchAll(assignment)){if(!placeholder.test((match[1]??"").replace(/^(?:bearer|basic)\s+/i,"")))return true}return false}var sensitiveKeyName,sensitiveKey,placeholder,assignment;var init_record_safety=__esm({"../core/src/record-safety.ts"(){"use strict";init_permissions();sensitiveKeyName="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)";sensitiveKey=new RegExp(`^${sensitiveKeyName}$`,"i");placeholder=/^(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})$/i;assignment=new RegExp(String.raw`\b${sensitiveKeyName}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi")}});var init_result=__esm({"../core/src/result.ts"(){"use strict"}});var StateMachine,workItemStateMachine;var init_state_machine=__esm({"../core/src/state-machine.ts"(){"use strict";StateMachine=class{#transitions;constructor(transitions){const mutable=new Map;for(const transition2 of transitions){const targets=mutable.get(transition2.from)??new Set;targets.add(transition2.to);mutable.set(transition2.from,targets)}this.#transitions=mutable}canTransition(from,to){return this.#transitions.get(from)?.has(to)??false}assertTransition(from,to){if(!this.canTransition(from,to)){throw new Error(`Invalid state transition: ${from} -> ${to}`)}}nextStates(from){return[...this.#transitions.get(from)??[]]}};workItemStateMachine=new StateMachine([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}])}});var stopTranscriptProofSchema,stopReceiptSchema;var init_stop_receipt_schema=__esm({"../core/src/stop-receipt-schema.ts"(){"use strict";init_zod();stopTranscriptProofSchema=external_exports.object({offset:external_exports.number().int().nonnegative(),length:external_exports.number().int().min(1).max(4194304),sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)});stopReceiptSchema=external_exports.object({schema_version:external_exports.literal(1),session_id:external_exports.string().min(1),turn_id:external_exports.string().min(1),run_id:external_exports.string().startsWith("RUN-"),observed_at:external_exports.string().datetime(),cursor:external_exports.object({path:external_exports.string().min(1),dev:external_exports.number(),ino:external_exports.number(),birthtime_ms:external_exports.number(),size:external_exports.number().int().nonnegative(),offset:external_exports.number().int().nonnegative(),mtime_ms:external_exports.number(),ctime_ms:external_exports.number(),trusted:external_exports.literal(true),terminal_status:external_exports.enum(["completed","failed","cancelled"]),session_proof:stopTranscriptProofSchema,terminal_proof:stopTranscriptProofSchema,anchor:stopTranscriptProofSchema})})}});async function loadWorkspaceLayout(filesystem){const[hasProjectConfig,hasFrameworkLock]=await Promise.all([filesystem.exists(PROJECT_CONFIG_PATH),filesystem.exists(FRAMEWORK_LOCK_PATH)]);if(hasProjectConfig!==hasFrameworkLock){const missing=hasProjectConfig?FRAMEWORK_LOCK_PATH:PROJECT_CONFIG_PATH;throw new PartialWorkspaceConfigError(`Partial V2 configuration; missing ${missing}`)}if(hasProjectConfig&&hasFrameworkLock){const[projectConfig2,frameworkLock]=await Promise.all([new ProjectConfigRepository(filesystem).read(),new FrameworkLockRepository(filesystem).read()]);return createV2WorkspaceLayout(projectConfig2,frameworkLock)}if(await filesystem.exists(".agents/manifest.yaml")){return createLegacyWorkspaceLayout(await new ManifestRepository(filesystem).read())}throw new WorkspaceLayoutNotFoundError("Workspace has neither complete V2 config nor a legacy V1 manifest")}function createV2WorkspaceLayout(projectConfig2,frameworkLock){const version2=frameworkLock.layout.version;const activeDataRoot=version2===3?".agents/records":".agents/data";return{version:version2,source:"project-config",project:projectConfig2.project,projectConfig:projectConfig2,frameworkLock,legacyManifest:null,supports:()=>true,entityRoot:kind=>`${activeDataRoot}/${v2DirectoryNames[kind]}`,activePath(kind,id){assertDatedEntityId(kind,id);const root=this.entityRoot(kind);const directory2=version2===3?datedMonthDirectory(root,id):datedEntityDirectory(root,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`},legacyReadRoot(kind){if(version2===3)return`.agents/data/${v2DirectoryNames[kind]}`;return legacyRoot(defaultLegacyRoots,kind)},legacyReadCandidate(kind,id,options){if(version2===3){return{path:v2EntityPath(".agents/data",kind,id),readOnly:true}}return legacyCandidate(defaultLegacyRoots,kind,id,options)},legacyReadCandidates(kind,id,options){if(version2===3){return[{path:v2EntityPath(".agents/records",kind,id),readOnly:true},{path:v2EntityPath(".agents/data",kind,id),readOnly:true}]}const candidate=legacyCandidate(defaultLegacyRoots,kind,id,options);return candidate===null?[]:[candidate]}}}function v2EntityPath(root,kind,id){assertDatedEntityId(kind,id);const directory2=datedEntityDirectory(`${root}/${v2DirectoryNames[kind]}`,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`}function createLegacyWorkspaceLayout(manifest){const roots2={spec:canonicalRoot(`${manifest.paths.specs}/capabilities`),change:canonicalRoot(manifest.paths.changes),task:canonicalRoot(manifest.paths.tasks),run:canonicalRoot(manifest.paths.runs)};return{version:1,source:"legacy-manifest",project:manifest.project,projectConfig:null,frameworkLock:null,legacyManifest:manifest,supports:kind=>kind!=="prd"&&kind!=="execution",entityRoot(kind){const root=legacyRoot(roots2,kind);if(root===null)throw unsupported(kind,1);return root},activePath(kind,id,options){if(!this.supports(kind))throw unsupported(kind,1);return legacyEntityPath(roots2,kind,id,options)},legacyReadRoot:()=>null,legacyReadCandidate:()=>null,legacyReadCandidates:()=>[]}}async function inspectArtifactReadState(filesystem,layout,kind,id,options){const activePath=layout.activePath(kind,id,options);const candidates=layout.legacyReadCandidates(kind,id,options);const[hasActive,...candidateExists]=await Promise.all([filesystem.exists(activePath),...candidates.map(candidate=>filesystem.exists(candidate.path))]);const existingLegacyPaths=candidates.filter((_,index)=>candidateExists[index]).map(candidate=>candidate.path);const legacyPath=existingLegacyPaths[0]??candidates[0]?.path??null;const hasLegacy=existingLegacyPaths.length>0;if(!hasActive&&!hasLegacy)return{state:"missing",activePath,legacyPath};if(hasActive&&!hasLegacy)return{state:"active-only",activePath,legacyPath};const contents=await Promise.all([...hasActive?[filesystem.readText(activePath)]:[],...existingLegacyPaths.map(path=>filesystem.readText(path))]);if(!hasActive){const[first,...rest]=contents;return{state:rest.every(content=>content===first)?"legacy-only":"duplicate-divergent",activePath,legacyPath}}const[active,...legacyContents]=contents;return{state:legacyContents.every(content=>content===active)?"duplicate-identical":"duplicate-divergent",activePath,legacyPath}}async function resolveArtifactReadPath(filesystem,layout,kind,id,options){const inspection=await inspectArtifactReadState(filesystem,layout,kind,id,options);if(inspection.state==="duplicate-divergent"){throw new InactiveLayoutConflictError(`Divergent ${kind} ${id} exists in active and legacy layouts: ${inspection.activePath}, ${inspection.legacyPath}`)}if(inspection.state==="missing")return null;if(inspection.state==="legacy-only")return inspection.legacyPath;return inspection.activePath}function legacyCandidate(roots2,kind,id,options){if(kind==="prd"||kind==="execution")return null;if(kind==="spec"&&options?.legacyCapability===void 0)return null;return{path:legacyEntityPath(roots2,kind,id,options),readOnly:true}}function legacyEntityPath(roots2,kind,id,options){assertEntityPrefix(kind,id);if(kind==="prd"||kind==="execution")throw unsupported(kind,1);if(kind==="spec"){const capability=options?.legacyCapability;if(capability===void 0||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability)){throw new WorkspaceLayoutError("Legacy spec lookup requires a canonical legacyCapability")}return`${roots2.spec}/${capability}/spec.md`}datedIdParts(id);if(kind==="change"){const{year,month}=datedIdParts(id);return`${roots2.change}/${year}/${month}/${id}/proposal.md`}if(kind==="task")return datedMarkdownPath(roots2.task,id);return datedMarkdownPath(roots2.run,id)}function legacyRoot(roots2,kind){if(kind==="prd"||kind==="execution")return null;return roots2[kind]}function assertDatedEntityId(kind,id){assertEntityPrefix(kind,id);datedIdPartsWithDay(id)}function assertEntityPrefix(kind,id){const prefix=expectedPrefixes[kind];if(!id.startsWith(`${prefix}-`)){throw new ArtifactKindMismatchError(`Expected ${kind} id to start with ${prefix}-: ${id}`)}}function canonicalRoot(path){if(path.length===0||path.includes("\\")||path.includes("\0")||path.startsWith("/")||path.startsWith("./")||path.endsWith("/")||/^[A-Za-z]:/.test(path)||path.split("/").some(segment2=>segment2.length===0||segment2==="."||segment2==="..")){throw new WorkspaceLayoutError(`Workspace layout path is not canonical: ${path}`)}return path}function unsupported(kind,version2){return new UnsupportedLayoutEntityError(`Layout V${version2} does not support ${kind}`)}var WorkspaceLayoutError,PartialWorkspaceConfigError,WorkspaceLayoutNotFoundError,UnsupportedLayoutEntityError,ArtifactKindMismatchError,InactiveLayoutConflictError,expectedPrefixes,v2DirectoryNames,defaultLegacyRoots;var init_workspace_layout=__esm({"../core/src/workspace-layout.ts"(){"use strict";init_config();init_manifest();init_paths();WorkspaceLayoutError=class extends Error{name="WorkspaceLayoutError"};PartialWorkspaceConfigError=class extends WorkspaceLayoutError{name="PartialWorkspaceConfigError"};WorkspaceLayoutNotFoundError=class extends WorkspaceLayoutError{name="WorkspaceLayoutNotFoundError"};UnsupportedLayoutEntityError=class extends WorkspaceLayoutError{name="UnsupportedLayoutEntityError"};ArtifactKindMismatchError=class extends WorkspaceLayoutError{name="ArtifactKindMismatchError"};InactiveLayoutConflictError=class extends WorkspaceLayoutError{name="InactiveLayoutConflictError"};expectedPrefixes={prd:"PRD",spec:"SPEC",change:"CHG",task:"TASK",execution:"EXEC",run:"RUN"};v2DirectoryNames={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};defaultLegacyRoots={spec:".agents/specs/capabilities",change:".agents/changes",task:".agents/tasks",run:".agents/runs"}}});var CORE_VERSION;var init_src=__esm({"../core/src/index.ts"(){"use strict";init_agent_runtime();init_agents();init_autonomy_policy();init_autonomy_recovery();init_clock();init_config();init_filesystem();init_git();init_governance();init_host_capabilities();init_ids();init_lifecycle_claims();init_manifest();init_markdown();init_model_orchestration();init_paths();init_permissions2();init_routing2();init_record_safety();init_result();init_state_machine();init_stop_receipt_schema();init_workspace_layout();init_yaml();CORE_VERSION="6.0.0"}});function followsDispatchPolicy(agent){return agent.role==="orchestrator"||["builder","task-executor"].includes(agent.role)&&agent.execution_eligibility.includes("delivery")}function codexModelInstructions(agent){return followsDispatchPolicy(agent)?["Model and reasoning effort are controlled by the authorized dispatch policy. Catalog preferences are dispatch defaults, not permanent native locks. Before dispatch, the authorized host must select and validate the model/effort allowed by the frozen Task policy and the host's manual selection. Record the requested configuration separately from the effective model/effort observed from the host; never silently inherit a parent configuration or claim a model switch from instructions. If the host cannot select or verify the required configuration, report the capability as unavailable and return the blocked dispatch to the orchestrator."]:[]}function codexModelConfig(agent){const model=agent.model.preferred[0];if(followsDispatchPolicy(agent)||agent.model.preferred.length!==1||model===void 0||model==="policy-selected"){return""}const effort=agent.model.reasoning_effort;return`model = ${JSON.stringify(model)}
96
+ `}var import_yaml3,FRONTMATTER_BOUNDARY,MAX_SAFE_ALIAS_COUNT2,MarkdownContractError;var init_markdown=__esm({"../core/src/markdown.ts"(){"use strict";import_yaml3=__toESM(require_dist(),1);FRONTMATTER_BOUNDARY="---";MAX_SAFE_ALIAS_COUNT2=10;MarkdownContractError=class extends Error{name="MarkdownContractError"}}});function parseRuleDocument(source){return parseMarkdown(source,ruleMetadataSchema)}function parseRequirementDocument(source){const document=parseMarkdown(source,requirementMetadataSchema);if(!/^## REQ-[A-Z0-9-]+\s/m.test(document.body)){throw new Error("Requirement document must declare at least one REQ section")}if(!/`?AC-[A-Z0-9-]+`?/m.test(document.body)){throw new Error("Requirement document must declare at least one Acceptance Criterion")}return document}function buildRequirementReferenceCatalog(sources){const requirementIds=new Set;const acceptanceIds=new Set;const requirementAliases=new Map;const acceptanceAliases=new Map;for(const source of sources){const document=parseRequirementDocument(source);if(document.metadata.status==="deprecated"){collectAliases(document.body,"REQ",requirementAliases);collectAliases(document.body,"AC",acceptanceAliases);continue}for(const match of document.body.matchAll(/^##\s+(REQ-[A-Z0-9-]+)(?:\s|$)/gm)){if(match[1]!==void 0)requirementIds.add(match[1])}for(const match of document.body.matchAll(/^\s*-\s+`?(AC-[A-Z0-9-]+)`?\s*:/gm)){if(match[1]!==void 0)acceptanceIds.add(match[1])}}const resolvedRequirementAliases=resolvedAliases(requirementAliases,requirementIds);const resolvedAcceptanceAliases=resolvedAliases(acceptanceAliases,acceptanceIds);return{requirement_ids:[...requirementIds].sort(),acceptance_ids:[...acceptanceIds].sort(),requirement_aliases:Object.fromEntries(resolvedRequirementAliases),acceptance_aliases:Object.fromEntries(resolvedAcceptanceAliases)}}function validateRequirementReferences(catalog,requirementIds,acceptanceIds){const knownRequirements=new Set(catalog.requirement_ids);const knownAcceptance=new Set(catalog.acceptance_ids);const findings=[];for(const id of[...new Set(requirementIds)].sort()){if(!knownRequirements.has(id)&&catalog.requirement_aliases[id]===void 0){findings.push({kind:"requirement",id,message:`Requirement does not resolve: ${id}`})}}for(const id of[...new Set(acceptanceIds)].sort()){if(!knownAcceptance.has(id)&&catalog.acceptance_aliases[id]===void 0){findings.push({kind:"acceptance",id,message:`Acceptance Criterion does not resolve: ${id}`})}}return findings}function collectAliases(body,prefix,aliases){const expression=new RegExp(`^\\s*-\\s+\\x60(${prefix}-[A-Z0-9-]+)\\x60\\s*->\\s*\\x60(${prefix}-[A-Z0-9-]+)\\x60`,"gm");for(const match of body.matchAll(expression)){const source=match[1];const target=match[2];if(source===void 0||target===void 0)continue;const existing=aliases.get(source);if(existing!==void 0&&existing!==target){throw new Error(`Divergent ${prefix} alias: ${source}`)}aliases.set(source,target)}}function resolvedAliases(aliases,canonicalIds){const resolved=[];for(const[source,target]of aliases){if(!canonicalIds.has(target)){throw new Error(`Alias target does not resolve: ${source} -> ${target}`)}resolved.push([source,target])}return resolved.sort(([left],[right])=>left.localeCompare(right))}var ruleMetadataSchema,requirementMetadataSchema;var init_governance=__esm({"../core/src/governance.ts"(){"use strict";init_zod();init_markdown();ruleMetadataSchema=external_exports.object({id:external_exports.string().regex(/^RULE-[A-Z0-9-]+$/),load:external_exports.enum(["always","auto","file_match","manual"]),globs:external_exports.array(external_exports.string().min(1)).default([]),priority:external_exports.enum(["critical","high","medium","low"]),max_context_tokens:external_exports.number().int().positive(),requires:external_exports.array(external_exports.string().regex(/^RULE-[A-Z0-9-]+$/)),triggers:external_exports.array(external_exports.string().min(1)).default([]),phases:external_exports.array(external_exports.enum(["conversation","definition","planning","execution","verification","evidence"])).default([]),domains:external_exports.array(external_exports.string().min(1)).default([])}).strict().superRefine((metadata3,context2)=>{if(metadata3.load==="file_match"&&metadata3.globs.length===0){context2.addIssue({code:"custom",path:["globs"],message:"file_match Rules require at least one glob"})}});requirementMetadataSchema=external_exports.object({schema_version:external_exports.literal(2),id:external_exports.string().regex(/^REQUIREMENTS-[A-Z0-9-]+$/),area:external_exports.string().regex(/^[a-z][a-z0-9-]*$/),title:external_exports.string().min(1),status:external_exports.enum(["proposed","active","deprecated"]),version:external_exports.number().int().positive(),source_change:external_exports.string().min(1).nullable(),source_release:external_exports.string().regex(/^\d+\.\d+\.\d+$/).optional()}).strict().superRefine((metadata3,context2)=>{if(metadata3.source_change===null&&metadata3.source_release===void 0){context2.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata3.source_change!==null&&metadata3.source_release!==void 0){context2.addIssue({code:"custom",path:["source_release"],message:"source_release is only valid when source_change is null"})}})}});function validateCodexFirstRoute(input){const profile=hostCapabilityProfileSchema.parse(input.profile);if(profile.default_mode!=="codex_host_native"||!input.host_authentication_available){return{status:"exception",code:"host_authentication_unavailable"}}if(input.requires_external_provider===true){return{status:"exception",code:"external_provider_required"}}if(input.requires_remote_operation===true){return{status:"exception",code:"remote_operation_required"}}return{status:"valid",authentication:"host",remote_provider_required:false}}async function loadHostCapabilityProfile(filesystem,path=".agents/config/models/codex-host.yaml"){return hostCapabilityProfileSchema.parse(parseYaml(await filesystem.readText(path)))}var HOST_EXECUTION_MODES,MODEL_CLASSES,CODEX_NATIVE_SURFACES,hostExecutionModeSchema,modelClassSchema,codexNativeSurfaceSchema,uniqueNativeSurfacesSchema,hostCapabilityEvidenceSchema,implementedHostCapabilityClaimSchema,nativeModeProfileSchema,subprocessModeProfileSchema,modelClassProfileSchema,hostCapabilityProfileSchema,providerSubprocessOptInSchema;var init_contracts2=__esm({"../core/src/host-capabilities/contracts.ts"(){"use strict";init_zod();init_yaml();HOST_EXECUTION_MODES=["codex_host_native","provider_subprocess"];MODEL_CLASSES=["frontier","balanced","fast_scan","review"];CODEX_NATIVE_SURFACES=["subagents","worktrees","sandbox","approvals","skills","mcp"];hostExecutionModeSchema=external_exports.enum(HOST_EXECUTION_MODES);modelClassSchema=external_exports.enum(MODEL_CLASSES);codexNativeSurfaceSchema=external_exports.enum(CODEX_NATIVE_SURFACES);uniqueNativeSurfacesSchema=external_exports.array(codexNativeSurfaceSchema).min(1).refine(surfaces=>new Set(surfaces).size===surfaces.length,{message:"native_surfaces must be unique"});hostCapabilityEvidenceSchema=external_exports.object({locator:external_exports.string().min(1),candidate_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();implementedHostCapabilityClaimSchema=external_exports.object({capability_id:external_exports.string().regex(/^CAP-[A-Z0-9-]+$/),current_state:external_exports.literal("implemented"),previous_states:external_exports.tuple([external_exports.literal("declared")]),evidence:external_exports.array(hostCapabilityEvidenceSchema).length(0)}).strict();nativeModeProfileSchema=external_exports.object({tier:external_exports.literal(1),enabled:external_exports.literal(true),optional:external_exports.literal(false),invokes_provider_subprocess:external_exports.literal(false),authority:external_exports.literal("host"),native_surfaces:uniqueNativeSurfacesSchema,capability_bindings:external_exports.record(codexNativeSurfaceSchema,implementedHostCapabilityClaimSchema)}).strict().superRefine((mode,context2)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context2.addIssue({code:"custom",path:["capability_bindings"],message:"every native surface requires exactly one conformance/maturity binding"})}});subprocessModeProfileSchema=external_exports.object({tier:external_exports.union([external_exports.literal(2),external_exports.literal(3)]),enabled:external_exports.boolean(),optional:external_exports.literal(true),invokes_provider_subprocess:external_exports.literal(true),authority:external_exports.literal("framework"),native_surfaces:external_exports.array(external_exports.never()).length(0),opt_in:external_exports.object({required:external_exports.literal(true),allowed_sources:external_exports.array(external_exports.enum(["project_config","human_decision"])).min(1).refine(sources=>new Set(sources).size===sources.length,{message:"opt-in sources must be unique"})}).strict()}).strict();modelClassProfileSchema=external_exports.object({selection:external_exports.enum(["host_available","inherit_host"]),reasoning:external_exports.enum(["low","medium","high"]),intent:external_exports.string().min(1)}).strict();hostCapabilityProfileSchema=external_exports.object({schema_version:external_exports.literal(1),host_id:external_exports.literal("codex"),candidate_sha256:external_exports.null(),default_mode:external_exports.literal("codex_host_native"),modes:external_exports.object({codex_host_native:nativeModeProfileSchema,provider_subprocess:subprocessModeProfileSchema}).strict(),model_classes:external_exports.object({frontier:modelClassProfileSchema,balanced:modelClassProfileSchema,fast_scan:modelClassProfileSchema,review:modelClassProfileSchema}).strict()}).strict();providerSubprocessOptInSchema=external_exports.object({enabled:external_exports.literal(true),source:external_exports.enum(["project_config","human_decision"]),provenance:external_exports.object({reference:external_exports.string().min(1),recorded_at:external_exports.string().datetime({offset:true})}).strict()}).strict()}});var init_host_capabilities=__esm({"../core/src/host-capabilities/index.ts"(){"use strict";init_contracts2()}});function lifecycleClaimPath(kind,digest14){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest14}.json`}var LIFECYCLE_CLAIMS_ROOT;var init_lifecycle_claims=__esm({"../core/src/lifecycle-claims.ts"(){"use strict";LIFECYCLE_CLAIMS_ROOT=".local/claims"}});function parseZaipManifest(value){return zaipManifestSchema.parse(value)}var zaipManifestSchema,zaipManifestJsonSchema,ManifestRepository;var init_manifest=__esm({"../core/src/manifest.ts"(){"use strict";init_zod();init_yaml();zaipManifestSchema=external_exports.object({schema_version:external_exports.literal(1),project:external_exports.object({id:external_exports.string().min(1),name:external_exports.string().min(1),timezone:external_exports.string().min(1).default("America/Sao_Paulo")}),framework:external_exports.object({version:external_exports.string().min(1)}),layout:external_exports.object({version:external_exports.literal(1),managed_namespace:external_exports.string().min(1).default(".agents/managed"),project_namespace:external_exports.string().min(1).default(".agents/project")}).default({version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"}),profile:external_exports.object({id:external_exports.string().min(1).default("zaip-aios-stack")}),paths:external_exports.object({specs:external_exports.string().min(1).default(".agents/specs"),changes:external_exports.string().min(1).default(".agents/changes"),tasks:external_exports.string().min(1).default(".agents/tasks"),decisions:external_exports.string().min(1).default(".agents/decisions"),runs:external_exports.string().min(1).default(".agents/runs")}).default({specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}),agents:external_exports.array(external_exports.enum(["codex","claude"])).default(["codex","claude"])}).strict();zaipManifestJsonSchema=external_exports.toJSONSchema(zaipManifestSchema);ManifestRepository=class{constructor(filesystem,path=".agents/manifest.yaml"){this.filesystem=filesystem;this.path=path}filesystem;path;async read(){return parseZaipManifest(parseYaml(await this.filesystem.readText(this.path)))}async write(manifest){await this.filesystem.writeTextAtomic(this.path,serializeYaml(zaipManifestSchema.parse(manifest)))}}}});function datedIdPartsWithDay(id){const match=id.match(/^([A-Z]+(?:-[A-Z]+)*)-(\d{4})-(\d{2})-(\d{2})-\d{2}-\d{2}-/);if(match?.[1]===void 0||match[2]===void 0||match[3]===void 0||match[4]===void 0){throw new TypeError(`ID does not contain the canonical date: ${id}`)}const[,prefix,year,month,day]=match;const date5=new Date(`${year}-${month}-${day}T00:00:00.000Z`);if(Number.isNaN(date5.getTime())||String(date5.getUTCFullYear()).padStart(4,"0")!==year||String(date5.getUTCMonth()+1).padStart(2,"0")!==month||String(date5.getUTCDate()).padStart(2,"0")!==day){throw new TypeError(`ID contains an invalid canonical date: ${id}`)}return{prefix,year,month,day}}function datedIdParts(id){const{year,month}=datedIdPartsWithDay(id);return{year,month}}function datedMarkdownPath(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}/${id}.md`}function datedMonthDirectory(basePath,id){const{year,month}=datedIdParts(id);return`${basePath}/${year}/${month}`}function datedEntityDirectory(basePath,id){const{year,month,day}=datedIdPartsWithDay(id);return`${basePath}/${year}/${month}/${day}`}var init_paths=__esm({"../core/src/paths.ts"(){"use strict"}});function redactSensitive(value){return value.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/g,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/\bgh[opsu]_[A-Za-z0-9_]{8,}\b/g,"[REDACTED]").replace(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]")}var init_permissions=__esm({"../core/src/policy/permissions/permissions.ts"(){"use strict"}});var init_permissions2=__esm({"../core/src/policy/permissions/index.ts"(){"use strict";init_permissions()}});var init_routing=__esm({"../core/src/policy/routing/routing.ts"(){"use strict"}});var init_routing2=__esm({"../core/src/policy/routing/index.ts"(){"use strict";init_routing()}});function assertSafeRecordContent(value){const seen=new WeakSet;function visit(item,key=""){if(typeof item==="string"){if(item.length===0||placeholder.test(item))return;if(sensitiveKey.test(key)||unsafeText(item)){throw new Error("Sensitive content cannot be persisted; redact credentials and sensitive URL parameters first.")}return}if(item===null||typeof item!=="object"||seen.has(item))return;seen.add(item);for(const[childKey,child]of Object.entries(item)){visit(child,sensitiveKey.test(key)?key:childKey)}}visit(value)}function unsafeText(text){if(redactSensitive(text)!==text)return true;if(/\bbearer\s+[a-z0-9._~+/-]+=*/i.test(text))return true;for(const match of text.matchAll(/\bbasic\s+([a-z0-9+/]+={0,2})/gi)){if(Buffer.from(match[1]??"","base64").toString("utf8").includes(":"))return true}if(/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text))return true;for(const match of text.matchAll(/[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+/gi)){try{const url2=new URL(match[0]);if(url2.password||/^https?:$/.test(url2.protocol)&&url2.username)return true;for(const[key,value]of url2.searchParams){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}for(const[key,value]of new URLSearchParams(url2.hash.slice(1))){if(sensitiveKey.test(key)&&value&&!placeholder.test(value))return true}text=text.replace(match[0],"")}catch{}}for(const match of text.matchAll(assignment)){if(!placeholder.test((match[1]??"").replace(/^(?:bearer|basic)\s+/i,"")))return true}return false}var sensitiveKeyName,sensitiveKey,placeholder,assignment;var init_record_safety=__esm({"../core/src/record-safety.ts"(){"use strict";init_permissions();sensitiveKeyName="(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|api[_-]?key|password|passwd|secret|client[_-]?secret|authorization|signature|sig)";sensitiveKey=new RegExp(`^${sensitiveKeyName}$`,"i");placeholder=/^(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})$/i;assignment=new RegExp(String.raw`\b${sensitiveKeyName}["']?\s*[:=]\s*["']?((?:(?:bearer|basic)\s+)?(?:\[redacted(?: private key)?\]|<redacted>|\*{3,})|[^\s"',;]+)`,"gi")}});var init_result=__esm({"../core/src/result.ts"(){"use strict"}});var StateMachine,workItemStateMachine;var init_state_machine=__esm({"../core/src/state-machine.ts"(){"use strict";StateMachine=class{#transitions;constructor(transitions){const mutable=new Map;for(const transition2 of transitions){const targets=mutable.get(transition2.from)??new Set;targets.add(transition2.to);mutable.set(transition2.from,targets)}this.#transitions=mutable}canTransition(from,to){return this.#transitions.get(from)?.has(to)??false}assertTransition(from,to){if(!this.canTransition(from,to)){throw new Error(`Invalid state transition: ${from} -> ${to}`)}}nextStates(from){return[...this.#transitions.get(from)??[]]}};workItemStateMachine=new StateMachine([{from:"draft",to:"planned"},{from:"draft",to:"cancelled"},{from:"planned",to:"executing"},{from:"planned",to:"cancelled"},{from:"executing",to:"verifying"},{from:"executing",to:"blocked"},{from:"executing",to:"cancelled"},{from:"verifying",to:"completed"},{from:"verifying",to:"failed"},{from:"verifying",to:"blocked"},{from:"verifying",to:"cancelled"},{from:"blocked",to:"executing"},{from:"blocked",to:"cancelled"}])}});var stopTranscriptProofSchema,stopReceiptSchema;var init_stop_receipt_schema=__esm({"../core/src/stop-receipt-schema.ts"(){"use strict";init_zod();stopTranscriptProofSchema=external_exports.object({offset:external_exports.number().int().nonnegative(),length:external_exports.number().int().min(1).max(4194304),sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)});stopReceiptSchema=external_exports.object({schema_version:external_exports.literal(1),session_id:external_exports.string().min(1),turn_id:external_exports.string().min(1),run_id:external_exports.string().startsWith("RUN-"),observed_at:external_exports.string().datetime(),cursor:external_exports.object({path:external_exports.string().min(1),dev:external_exports.number(),ino:external_exports.number(),birthtime_ms:external_exports.number(),size:external_exports.number().int().nonnegative(),offset:external_exports.number().int().nonnegative(),mtime_ms:external_exports.number(),ctime_ms:external_exports.number(),trusted:external_exports.literal(true),terminal_status:external_exports.enum(["completed","failed","cancelled"]),session_proof:stopTranscriptProofSchema,terminal_proof:stopTranscriptProofSchema,anchor:stopTranscriptProofSchema})})}});async function loadWorkspaceLayout(filesystem){const[hasProjectConfig,hasFrameworkLock]=await Promise.all([filesystem.exists(PROJECT_CONFIG_PATH),filesystem.exists(FRAMEWORK_LOCK_PATH)]);if(hasProjectConfig!==hasFrameworkLock){const missing=hasProjectConfig?FRAMEWORK_LOCK_PATH:PROJECT_CONFIG_PATH;throw new PartialWorkspaceConfigError(`Partial V2 configuration; missing ${missing}`)}if(hasProjectConfig&&hasFrameworkLock){const[projectConfig2,frameworkLock]=await Promise.all([new ProjectConfigRepository(filesystem).read(),new FrameworkLockRepository(filesystem).read()]);return createV2WorkspaceLayout(projectConfig2,frameworkLock)}if(await filesystem.exists(".agents/manifest.yaml")){return createLegacyWorkspaceLayout(await new ManifestRepository(filesystem).read())}throw new WorkspaceLayoutNotFoundError("Workspace has neither complete V2 config nor a legacy V1 manifest")}function createV2WorkspaceLayout(projectConfig2,frameworkLock){const version2=frameworkLock.layout.version;const activeDataRoot=version2===3?".agents/records":".agents/data";return{version:version2,source:"project-config",project:projectConfig2.project,projectConfig:projectConfig2,frameworkLock,legacyManifest:null,supports:()=>true,entityRoot:kind=>`${activeDataRoot}/${v2DirectoryNames[kind]}`,activePath(kind,id){assertDatedEntityId(kind,id);const root=this.entityRoot(kind);const directory2=version2===3?datedMonthDirectory(root,id):datedEntityDirectory(root,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`},legacyReadRoot(kind){if(version2===3)return`.agents/data/${v2DirectoryNames[kind]}`;return legacyRoot(defaultLegacyRoots,kind)},legacyReadCandidate(kind,id,options){if(version2===3){return{path:v2EntityPath(".agents/data",kind,id),readOnly:true}}return legacyCandidate(defaultLegacyRoots,kind,id,options)},legacyReadCandidates(kind,id,options){if(version2===3){return[{path:v2EntityPath(".agents/records",kind,id),readOnly:true},{path:v2EntityPath(".agents/data",kind,id),readOnly:true}]}const candidate=legacyCandidate(defaultLegacyRoots,kind,id,options);return candidate===null?[]:[candidate]}}}function v2EntityPath(root,kind,id){assertDatedEntityId(kind,id);const directory2=datedEntityDirectory(`${root}/${v2DirectoryNames[kind]}`,id);if(kind==="change")return`${directory2}/${id}/change.md`;if(kind==="execution")return`${directory2}/${id}/execution.md`;if(kind==="run")return`${directory2}/${id}.jsonl`;return`${directory2}/${id}.md`}function createLegacyWorkspaceLayout(manifest){const roots2={spec:canonicalRoot(`${manifest.paths.specs}/capabilities`),change:canonicalRoot(manifest.paths.changes),task:canonicalRoot(manifest.paths.tasks),run:canonicalRoot(manifest.paths.runs)};return{version:1,source:"legacy-manifest",project:manifest.project,projectConfig:null,frameworkLock:null,legacyManifest:manifest,supports:kind=>kind!=="prd"&&kind!=="execution",entityRoot(kind){const root=legacyRoot(roots2,kind);if(root===null)throw unsupported(kind,1);return root},activePath(kind,id,options){if(!this.supports(kind))throw unsupported(kind,1);return legacyEntityPath(roots2,kind,id,options)},legacyReadRoot:()=>null,legacyReadCandidate:()=>null,legacyReadCandidates:()=>[]}}async function inspectArtifactReadState(filesystem,layout,kind,id,options){const activePath=layout.activePath(kind,id,options);const candidates=layout.legacyReadCandidates(kind,id,options);const[hasActive,...candidateExists]=await Promise.all([filesystem.exists(activePath),...candidates.map(candidate=>filesystem.exists(candidate.path))]);const existingLegacyPaths=candidates.filter((_,index)=>candidateExists[index]).map(candidate=>candidate.path);const legacyPath=existingLegacyPaths[0]??candidates[0]?.path??null;const hasLegacy=existingLegacyPaths.length>0;if(!hasActive&&!hasLegacy)return{state:"missing",activePath,legacyPath};if(hasActive&&!hasLegacy)return{state:"active-only",activePath,legacyPath};const contents=await Promise.all([...hasActive?[filesystem.readText(activePath)]:[],...existingLegacyPaths.map(path=>filesystem.readText(path))]);if(!hasActive){const[first,...rest]=contents;return{state:rest.every(content=>content===first)?"legacy-only":"duplicate-divergent",activePath,legacyPath}}const[active,...legacyContents]=contents;return{state:legacyContents.every(content=>content===active)?"duplicate-identical":"duplicate-divergent",activePath,legacyPath}}async function resolveArtifactReadPath(filesystem,layout,kind,id,options){const inspection=await inspectArtifactReadState(filesystem,layout,kind,id,options);if(inspection.state==="duplicate-divergent"){throw new InactiveLayoutConflictError(`Divergent ${kind} ${id} exists in active and legacy layouts: ${inspection.activePath}, ${inspection.legacyPath}`)}if(inspection.state==="missing")return null;if(inspection.state==="legacy-only")return inspection.legacyPath;return inspection.activePath}function legacyCandidate(roots2,kind,id,options){if(kind==="prd"||kind==="execution")return null;if(kind==="spec"&&options?.legacyCapability===void 0)return null;return{path:legacyEntityPath(roots2,kind,id,options),readOnly:true}}function legacyEntityPath(roots2,kind,id,options){assertEntityPrefix(kind,id);if(kind==="prd"||kind==="execution")throw unsupported(kind,1);if(kind==="spec"){const capability=options?.legacyCapability;if(capability===void 0||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability)){throw new WorkspaceLayoutError("Legacy spec lookup requires a canonical legacyCapability")}return`${roots2.spec}/${capability}/spec.md`}datedIdParts(id);if(kind==="change"){const{year,month}=datedIdParts(id);return`${roots2.change}/${year}/${month}/${id}/proposal.md`}if(kind==="task")return datedMarkdownPath(roots2.task,id);return datedMarkdownPath(roots2.run,id)}function legacyRoot(roots2,kind){if(kind==="prd"||kind==="execution")return null;return roots2[kind]}function assertDatedEntityId(kind,id){assertEntityPrefix(kind,id);datedIdPartsWithDay(id)}function assertEntityPrefix(kind,id){const prefix=expectedPrefixes[kind];if(!id.startsWith(`${prefix}-`)){throw new ArtifactKindMismatchError(`Expected ${kind} id to start with ${prefix}-: ${id}`)}}function canonicalRoot(path){if(path.length===0||path.includes("\\")||path.includes("\0")||path.startsWith("/")||path.startsWith("./")||path.endsWith("/")||/^[A-Za-z]:/.test(path)||path.split("/").some(segment2=>segment2.length===0||segment2==="."||segment2==="..")){throw new WorkspaceLayoutError(`Workspace layout path is not canonical: ${path}`)}return path}function unsupported(kind,version2){return new UnsupportedLayoutEntityError(`Layout V${version2} does not support ${kind}`)}var WorkspaceLayoutError,PartialWorkspaceConfigError,WorkspaceLayoutNotFoundError,UnsupportedLayoutEntityError,ArtifactKindMismatchError,InactiveLayoutConflictError,expectedPrefixes,v2DirectoryNames,defaultLegacyRoots;var init_workspace_layout=__esm({"../core/src/workspace-layout.ts"(){"use strict";init_config();init_manifest();init_paths();WorkspaceLayoutError=class extends Error{name="WorkspaceLayoutError"};PartialWorkspaceConfigError=class extends WorkspaceLayoutError{name="PartialWorkspaceConfigError"};WorkspaceLayoutNotFoundError=class extends WorkspaceLayoutError{name="WorkspaceLayoutNotFoundError"};UnsupportedLayoutEntityError=class extends WorkspaceLayoutError{name="UnsupportedLayoutEntityError"};ArtifactKindMismatchError=class extends WorkspaceLayoutError{name="ArtifactKindMismatchError"};InactiveLayoutConflictError=class extends WorkspaceLayoutError{name="InactiveLayoutConflictError"};expectedPrefixes={prd:"PRD",spec:"SPEC",change:"CHG",task:"TASK",execution:"EXEC",run:"RUN"};v2DirectoryNames={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};defaultLegacyRoots={spec:".agents/specs/capabilities",change:".agents/changes",task:".agents/tasks",run:".agents/runs"}}});var CORE_VERSION;var init_src=__esm({"../core/src/index.ts"(){"use strict";init_agent_runtime();init_agents();init_autonomy_policy();init_autonomy_recovery();init_clock();init_config();init_filesystem();init_git();init_governance();init_host_capabilities();init_ids();init_lifecycle_claims();init_manifest();init_markdown();init_model_orchestration();init_paths();init_permissions2();init_routing2();init_record_safety();init_result();init_state_machine();init_stop_receipt_schema();init_workspace_layout();init_yaml();CORE_VERSION="6.0.1"}});function followsDispatchPolicy(agent){return agent.role==="orchestrator"||["builder","task-executor"].includes(agent.role)&&agent.execution_eligibility.includes("delivery")}function codexModelInstructions(agent){return followsDispatchPolicy(agent)?["Model and reasoning effort are controlled by the authorized dispatch policy. Catalog preferences are dispatch defaults, not permanent native locks. Before dispatch, the authorized host must select and validate the model/effort allowed by the frozen Task policy and the host's manual selection. Record the requested configuration separately from the effective model/effort observed from the host; never silently inherit a parent configuration or claim a model switch from instructions. If the host cannot select or verify the required configuration, report the capability as unavailable and return the blocked dispatch to the orchestrator."]:[]}function codexModelConfig(agent){const model=agent.model.preferred[0];if(followsDispatchPolicy(agent)||agent.model.preferred.length!==1||model===void 0||model==="policy-selected"){return""}const effort=agent.model.reasoning_effort;return`model = ${JSON.stringify(model)}
97
97
  ${effort===void 0?"":`model_reasoning_effort = ${JSON.stringify(effort)}
98
98
  `}`}var init_codex_model_policy=__esm({"../adapters/src/guidance/codex-model-policy.ts"(){"use strict"}});import{createHash}from"node:crypto";function agentGuidanceFiles(catalog){validateGuidanceCatalog(catalog);const files=[];for(const agent of[...catalog.agents].sort(byId)){const payload=stableJson({kind:"agent",schema_version:1,definition:agent});const semanticHash=digest(payload);files.push({client:"codex",subject:agent.id,projection:"canonical",path:`.agents/config/clients/codex/agents/${agent.codex_name}.toml`,content:renderCodexAgent(agent,catalog,payload),semantic_hash:semanticHash});for(const alias of agent.compatibility?.aliases??[]){const shim=stableJson({kind:"agent-alias",schema_version:1,alias,canonical:{id:agent.id,codex_name:agent.codex_name,codex_task_name:agent.codex_task_name}});const subject2=`alias:${alias.kind}:${alias.value}`;if(alias.kind==="id"){files.push({client:"claude",subject:subject2,projection:"compatibility-shim",path:`.claude/agents/${alias.value}.md`,content:renderGuidance(alias.value,`Deprecated alias for ${agent.id}. Use ${agent.id}. Removal deadline: ${alias.remove_after}.`,shim),semantic_hash:digest(shim)})}if(alias.kind==="codex_name"){files.push({client:"codex",subject:subject2,projection:"compatibility-shim",path:`.agents/config/clients/codex/agents/${alias.value}.toml`,content:renderCodexAlias(agent,alias.value,alias.remove_after,shim),semantic_hash:digest(shim)})}}files.push({client:"claude",subject:agent.id,projection:"canonical",path:`.claude/agents/${agent.id}.md`,content:renderGuidance(agent.id,claudeAgentPurpose(agent),payload),semantic_hash:semanticHash})}for(const squad of[...catalog.squads].sort(byId)){const payload=stableJson({kind:"squad",schema_version:1,definition:squad});files.push(...clientFiles("squads",squad.id,renderGuidance(squad.id,squad.purpose,payload),digest(payload)))}return files}function compareAgentGuidance(files){const drifted=[];const paths2=new Set;const bySubject=new Map;for(const file2 of files){if(paths2.has(file2.path))drifted.push(`${file2.path}:duplicate-path`);paths2.add(file2.path);if(file2.projection!=="canonical")continue;const entry2=bySubject.get(file2.subject)??{};if(entry2[file2.client]!==void 0)drifted.push(`${file2.subject}:${file2.client}:duplicate`);entry2[file2.client]=file2;bySubject.set(file2.subject,entry2)}for(const[subject2,entry2]of[...bySubject].sort(([left],[right])=>left.localeCompare(right))){if(entry2.codex===void 0||entry2.claude===void 0){drifted.push(`${subject2}:missing-client`);continue}if(entry2.codex.semantic_hash!==entry2.claude.semantic_hash){drifted.push(`${subject2}:semantic-drift`)}}const manifest=[...files].sort((left,right)=>left.path.localeCompare(right.path)).map(({client,subject:subject2,projection,semantic_hash})=>({client,subject:subject2,projection,semantic_hash}));return{valid:drifted.length===0,drifted,semantic_hash:digest(stableJson(manifest))}}async function buildAgentGuidance(filesystem,catalog){const files=agentGuidanceFiles(catalog);const parity=compareAgentGuidance(files);if(!parity.valid)throw new Error(`Agent guidance parity failed: ${parity.drifted.join(", ")}`);for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(!isManagedGuidance(current)){throw new Error(`Refusing to overwrite user-owned agent guidance: ${file2.path}`)}}}const expectedPaths=new Set(files.map(file2=>file2.path));for(const path of await staleManagedAgentGuidancePaths(filesystem,expectedPaths)){await filesystem.removeFile(path)}for(const file2 of files)await filesystem.writeTextAtomic(file2.path,file2.content);return parity}async function checkAgentGuidance(filesystem,catalog){const files=agentGuidanceFiles(catalog);const parity=compareAgentGuidance(files);const drifted=[...parity.drifted];const findings=[];for(const file2 of files){if(!await filesystem.exists(file2.path)){drifted.push(file2.path);findings.push({classification:"missing",path:file2.path});continue}if(await filesystem.readText(file2.path)!==file2.content){drifted.push(file2.path);findings.push({classification:"content-drift",path:file2.path})}}const inventory3=await agentGuidanceInventory(filesystem,new Set(files.map(file2=>file2.path)));for(const path of inventory3.staleManaged){drifted.push(path);findings.push({classification:"stale-managed",path})}for(const path of inventory3.unknownUnmanaged){findings.push({classification:"unknown-unmanaged",path})}return{...parity,valid:drifted.length===0,drifted:[...new Set(drifted)].sort(),findings:findings.sort((left,right)=>left.classification.localeCompare(right.classification)||left.path.localeCompare(right.path))}}function validateGuidanceCatalog(catalog){const agents=new Map(catalog.agents.map(agent=>[agent.id,agent]));if(agents.size!==catalog.agents.length)throw new Error("Agent ids must be unique");const squadIds=new Set(catalog.squads.map(squad=>squad.id));if(squadIds.size!==catalog.squads.length)throw new Error("Squad ids must be unique");for(const agent of catalog.agents){if(!agent.codex_name.startsWith("zaip-agent-")){throw new Error(`${agent.id} codex_name must start with zaip-agent-`)}const expectedTaskName=agent.nickname_candidates[0];if(agent.codex_task_name!==expectedTaskName){throw new Error(`${agent.id} codex_task_name must equal ${expectedTaskName}`)}const expectedNickname=`${agent.persona.nome}_${agent.persona.cargo}_zaip_agent`;if(agent.nickname_candidates.length!==1||agent.nickname_candidates[0]!==expectedNickname){throw new Error(`${agent.id} nickname_candidates must contain only the derived persona nickname`)}}for(const squad of catalog.squads){if(!squad.review_policy.independent)throw new Error(`${squad.id} requires independent review`);const unresolvedMembers=squad.members.map(id=>agents.get(id));if(unresolvedMembers.some(agent=>agent===void 0)){throw new Error(`${squad.id} has unknown members`)}const members=unresolvedMembers.filter(isDefined);const executorIds=new Set(members.filter(agent=>agent!==void 0&&squad.review_policy.executor_roles.includes(agent.role)).map(agent=>agent.id));const reviewerIds=new Set(members.filter(agent=>agent!==void 0&&squad.review_policy.reviewer_roles.includes(agent.role)).map(agent=>agent.id));if(executorIds.size===0||reviewerIds.size===0){throw new Error(`${squad.id} must contain executor and reviewer roles`)}if([...executorIds].some(id=>reviewerIds.has(id))){throw new Error(`${squad.id} cannot assign self-review`)}}}function clientFiles(group,subject2,content,semanticHash){return["codex","claude"].map(client=>({client,subject:subject2,projection:"canonical",path:`.${client}/${group}/${subject2}.md`,content,semantic_hash:semanticHash}))}function renderCodexAgent(agent,catalog,payload){const hash6=digest(payload);const name=agent.codex_name;const finalizer=catalog.agents.find(candidate=>candidate.id==="agent-finalizer");if(agent.role==="orchestrator"&&finalizer===void 0){throw new Error("Agent catalog must define agent-finalizer")}const instructions=[`Operate as Codex agent ${name} (ZAIP catalog id ${agent.id}) with role ${agent.role}.`,agent.purpose,`Capabilities: ${agent.capabilities.join(", ")}.`,`Allowed tools: ${agent.tools.join(", ")||"none"}.`,`Available skills: ${agent.skills.join(", ")||"none"}; load matching skills only. Change/execution skills apply to persistent delivery; Meta Ads applies only to Meta work.`,"Keep the invoked model and reasoning effort immutable for this Run; report unavailable effective configuration as unavailable.",...codexModelInstructions(agent),`Write scopes: ${agent.write_scopes.join(", ")||"read-only"}.`,agent.write_scopes.length===0?"This role is read-only. Do not create, modify, move, or delete workspace files.":"The Codex host grants workspace-write at the workspace boundary, not per-path. Treat the declared write scopes as mandatory: do not modify files outside them; report any required expansion to the parent before writing.",`Inputs: ${agent.contract.inputs.join(", ")}.`,`Outputs: ${agent.contract.outputs.join(", ")}.`,`Evidence: ${agent.contract.evidence.join(", ")}.`,`Use when: ${agent.use_when.join("; ")}.`,`Do not use when: ${agent.do_not_use.join("; ")}.`,...remoteCloudBoundary(agent),...remoteAwsBoundary(agent),...specialistBoundaries(agent),...agent.role==="orchestrator"?["You are the dispatcher for your Task attempt. If the physical root already owns exactly this Task, it is the responsible orchestrator: it dispatches executors/reviewers and Gui directly, without an extra Dave child. A macro root dispatches one Task orchestrator per eligible Task and must not dispatch that Task's workers itself. Never create two responsible orchestrators or require two Guis for the same Task attempt. Never reassign your invocation to another Task.","Tool names in the catalog are capability labels, not literal host tool names. Native collaboration permits spawn_agent, send_input, wait_agent and close_agent for authorized descendants. Discover deferred native tools through the host tool registry before declaring them unavailable. Read-only filesystem permissions do not prohibit native delegation or waiting; do not use discovery to run persistence commands, bypass permissions or create independent chats.","Report child IDs and intermediate results as non-terminal progress, not a final response. Keep your native invocation open until the executor/reviewer and last Gui child have terminated. If you cannot remain active or complete that sequence, report an explicit blocked interruption; do not claim the attempt is finalized.","Identify the requested output and its domain. Under autonomy-v1, standalone Tasks prefer direct work with the user's selected principal model/effort; delegate only for a concrete specialist, isolation, review or finalization need. Before delegation disclose that ZAIP policy may select different child models/efforts. Otherwise preserve the legacy specialist routing contract. References and titles never select an executor or justify escalation.","Default to one domain executor per bounded result. Bring a secondary specialist only when its unresolved domain decision is necessary to the primary output; split independent outputs into sequential Tasks and preserve a true mixed-output conflict instead of codispatching.","Subagent lifecycle hooks are best-effort. You are read-only: relay observed session/thread/turn metadata and events to the authorized host; do not invoke CLI persistence. Canonical order is start -> actual Gui decision -> stop -> finish. The rich stop capture accepts the exact decision in task-outcome/summary/evidence/changed-files and persists it before Stop; Gui need not wait alive for a receipt. Never infer decisions from completed status. Preserve observed ancestry/model/effort; unavailable stays unavailable. UUID is not agent_path and cannot authorize path-only fallback.","Reviewer, auditor, and integrator Sub-Runs are permitted when their capabilities match the work.",`After all other descendants finish, delegate one real final direct Sub-Run to ${finalizer?.codex_name}. Use its cataloged agent_type; pass task_name ${finalizer?.codex_task_name} only when the native tool schema supports that argument. Do not finish the responsible Run or report a terminal Execution outcome before that Sub-Run has completed.`,"Give Gui the real responsible Run ID and exact candidate proof. It returns one immutable outcome, reason, evidence references and owned changed files. Do not require receipt polling or an active-turn handshake. The host persists the real decision through rich stop capture before closing the responsible Run. A terminal rich Gui with open parent is eligible; a closed parent without decision requires an authorized new attempt. Never invent approval or reuse another attempt's decision."]:[],...agent.role==="execution-finalizer"?["Evaluate closure evidence without writing product or lifecycle files. Return exactly one real terminal decision: outcome (completed, blocked, failed, cancelled), observed reason, evidence references, summary, owned changed files and responsible Run ID. Do not poll start/decision receipts or wait to stay active: the authorized host persists your actual decision with rich stop capture before closing the responsible Run. Capture latency is not a product defect or a reason to invent a blocked technical judgment. Missing proof remains blocked; cancelled requires explicit human intent. A native completed status is not persisted Task approval. Never invent metadata or convert UUID into agent_path."]:[],...agent.role==="orchestrator"?[]:["You are a worker selected by zaip-agent-orchestrator. Do not dispatch peer catalog roles; return your bounded result to the orchestrator, which exclusively controls further delegation."],`Escalate only to catalog identities: ${agent.escalation.map(id=>catalogCodexName(id)).join(", ")||"root agent"}.`,...agent.role==="orchestrator"?["Delegate only registered catalog identities: agent_type uses codex_name. Send task_name equal to codex_task_name only if the native tool schema exposes task_name; otherwise omit it. nickname_candidates belongs to the generated profile, not a substitute spawn argument. Do not require an exact nickname because the host may add a generated suffix.","Own exactly one Task attempt when Task-scoped. Dispatch executors and reviewers, then Gui as your last direct child; never ask a worker to spawn its own finalizer. Macro coordinators dispatch Task orchestrators and retain separate integration gates. Preserve actual native ancestry, depth and global budgets.",NATIVE_SUBAGENT_POLICY]:["Do not spawn children or create independent chats. Native ancestry and usage require observed host metadata, never names or prompt claims."],`When this agent is delegated, require the cataloged agent_type ${agent.codex_name}. If the native tool exposes task_name use ${agent.codex_task_name}; otherwise omit it and preserve the observed host identity.`,"Accept only concrete bounded delegated work. Preserve parent requirements and return a concise result with evidence locators.",agent.role==="execution-finalizer"?"You do not grant product approval; your sole approval-like action is the restricted terminal outcome above.":agent.review.can_approve?`You may approve only roles outside: ${agent.review.cannot_review_roles.join(", ")||"none"}.`:"You cannot approve your own work or issue final approval."].join("\n");const sandboxMode=agent.write_scopes.length===0?"read-only":"workspace-write";const modelConfig=codexModelConfig(agent);return`# zaip-managed generated-do-not-edit source=agent-catalog schema=1 sha256=${hash6}
99
99
  name = ${tomlString(name)}
@@ -3145,7 +3145,7 @@ Read \`.agents/config/project.yaml\` first. Apply ZAIP only for literal boolean
3145
3145
  - Use native \`spawn_agent\` only for Sub-Runs; the orchestrator records observed spawn and terminal events idempotently. Independent chats require an explicit user request.
3146
3146
 
3147
3147
  For delegation, use \`context agents\` to discover candidates and \`context agents --agent <id>\` for the selected canonical contract. The resolver validates the catalog and recomputes missing or stale discovery locally. A purpose never authorizes. Root starts \`zaip-agent-orchestrator\`, which selects an eligible executor; the mandatory last child is \`zaip-agent-finalizer\`. Follow core model rules.
3148
- `}});import{createHash as createHash7}from"node:crypto";import{resolve as resolve4}from"node:path";function adapterFiles(workspaceRoot,catalog,windowsWorkspaceRoot){const codexConfig=CODEX_CONFIG.replaceAll(CODEX_WORKSPACE_ROOT_PLACEHOLDER,JSON.stringify(resolve4(workspaceRoot))).replaceAll("__ZAIP_WINDOWS_PRE_TOOL_HOOK__",codexWindowsHookCommand("zaip-pre-tool-use.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_CONVERSATION_HOOK__",codexWindowsHookCommand("zaip-conversation-lifecycle.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_SUBAGENT_HOOK__",codexWindowsHookCommand("zaip-subagent-lifecycle.mjs",windowsWorkspaceRoot));return[...catalog===void 0?[]:[agentDiscoveryFile(catalog,ADAPTERS_VERSION)],managedAdapterFile(ADAPTERS_VERSION,"AGENTS.md",renderRootGuidance(catalog),"root-guidance"),managedAdapterFile(ADAPTERS_VERSION,".codex/skills/zaip-aios/SKILL.md",DISCOVERY_SKILL,"discovery-skill"),managedAdapterFile(ADAPTERS_VERSION,".claude/skills/zaip-aios/SKILL.md",DISCOVERY_SKILL,"discovery-skill"),managedAdapterFile(ADAPTERS_VERSION,".codex/skills/zaip-aios/agents/openai.yaml",DISCOVERY_SKILL_OPENAI_METADATA,"discovery-skill-openai-metadata"),managedAdapterFile(ADAPTERS_VERSION,".claude/skills/zaip-aios/agents/openai.yaml",DISCOVERY_SKILL_OPENAI_METADATA,"discovery-skill-openai-metadata"),managedAdapterFile(ADAPTERS_VERSION,".codex/config.toml",renderCodexConfig(codexConfig,catalog),"codex-config"),...codexHookAdapterFiles(ADAPTERS_VERSION),managedAdapterFile(ADAPTERS_VERSION,".codex/rules/zaip-github-deploy.rules",CODEX_GITHUB_DEPLOY_RULES,"codex-github-deploy-rules"),managedAdapterFile(ADAPTERS_VERSION,".codex/rules/zaip-security.rules",CODEX_SECURITY_RULES,"codex-security-rules"),managedAdapterFile(ADAPTERS_VERSION,".claude/settings.json",CLAUDE_SETTINGS,"claude-settings")]}async function buildAdapters(filesystem){const catalog=await filesystem.exists(AGENT_CATALOG_PATH)?await loadGuidanceCatalog(filesystem):void 0;const files=adapterFiles(filesystem.root,catalog);for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(isPreservedUserOverlay(file2.path,current)){reconcileCodexConfig(current,file2.content,catalog!==void 0);continue}if(!isManagedAdapterFile(current,file2.path)){throw new Error(`Refusing to overwrite user-owned adapter: ${file2.path}`)}}}for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(isPreservedUserOverlay(file2.path,current)){if(file2.path===".codex/config.toml"){await filesystem.writeTextAtomic(file2.path,reconcileCodexConfig(current,file2.content,catalog!==void 0))}continue}}await filesystem.writeTextAtomic(file2.path,file2.content)}for(const path of RETIRED_MANAGED_ADAPTERS){if(!await filesystem.exists(path))continue;const current=await filesystem.readText(path);if(isUnchangedManagedAdapter(path,current)){await filesystem.removeFileIfContentMatches(path,current)}}if(catalog!==void 0)await buildAgentGuidance(filesystem,catalog)}async function checkAdapters(filesystem){const catalog=await filesystem.exists(AGENT_CATALOG_PATH)?await loadGuidanceCatalog(filesystem):void 0;const codexVariants=[void 0,filesystem.root].map(hookRoot=>adapterFiles(filesystem.root,catalog,hookRoot).find(file2=>file2.path===".codex/config.toml")?.content??"");const result2=await checkAdapterFiles(filesystem,AGENT_CATALOG_PATH,loadGuidanceCatalog,catalog2=>adapterFiles(filesystem.root,catalog2),(path,content)=>path===".codex/config.toml"&&codexVariants.some(expected=>content===expected||isPreservedUserOverlay(path,content)&&isReconciledCodexConfig(content,expected,catalog!==void 0)));return result2}function isPreservedUserOverlay(path,content){return USER_OWNED_ADAPTER_OVERLAYS.has(path)&&!isUnchangedCodexConfig(content)}function isUnchangedManagedAdapter(path,content){if(!isManagedAdapterFile(content,path))return false;const marker=content.match(/^<!-- zaip-managed [^\r\n]* sha256=([a-f0-9]{64}) -->\r?\n/);if(marker?.[1]===void 0)return false;return createHash7("sha256").update(content.slice(marker[0].length)).digest("hex")===marker[1]}var ADAPTERS_VERSION,USER_OWNED_ADAPTER_OVERLAYS,RETIRED_MANAGED_ADAPTERS,CLAUDE_SETTINGS,DISCOVERY_SKILL,DISCOVERY_SKILL_OPENAI_METADATA,CODEX_WORKSPACE_ROOT_PLACEHOLDER,CODEX_CONFIG;var init_src2=__esm({"../adapters/src/index.ts"(){"use strict";init_adapter_check();init_adapter_file_rendering();init_codex_hook_adapter_files();init_codex_windows_hook_command();init_codex_hook_activation();init_codex_config_overlay();init_codex_rules();init_agent_discovery();init_catalog_guidance();init_guidance_catalog();init_agent_runtime2();init_codex_host2();init_guidance();init_mcp();init_profiles2();init_root_guidance();ADAPTERS_VERSION="6.0.0";USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);RETIRED_MANAGED_ADAPTERS=["CLAUDE.md"];CLAUDE_SETTINGS=`{
3148
+ `}});import{createHash as createHash7}from"node:crypto";import{resolve as resolve4}from"node:path";function adapterFiles(workspaceRoot,catalog,windowsWorkspaceRoot){const codexConfig=CODEX_CONFIG.replaceAll(CODEX_WORKSPACE_ROOT_PLACEHOLDER,JSON.stringify(resolve4(workspaceRoot))).replaceAll("__ZAIP_WINDOWS_PRE_TOOL_HOOK__",codexWindowsHookCommand("zaip-pre-tool-use.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_CONVERSATION_HOOK__",codexWindowsHookCommand("zaip-conversation-lifecycle.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_SUBAGENT_HOOK__",codexWindowsHookCommand("zaip-subagent-lifecycle.mjs",windowsWorkspaceRoot));return[...catalog===void 0?[]:[agentDiscoveryFile(catalog,ADAPTERS_VERSION)],managedAdapterFile(ADAPTERS_VERSION,"AGENTS.md",renderRootGuidance(catalog),"root-guidance"),managedAdapterFile(ADAPTERS_VERSION,".codex/skills/zaip-aios/SKILL.md",DISCOVERY_SKILL,"discovery-skill"),managedAdapterFile(ADAPTERS_VERSION,".claude/skills/zaip-aios/SKILL.md",DISCOVERY_SKILL,"discovery-skill"),managedAdapterFile(ADAPTERS_VERSION,".codex/skills/zaip-aios/agents/openai.yaml",DISCOVERY_SKILL_OPENAI_METADATA,"discovery-skill-openai-metadata"),managedAdapterFile(ADAPTERS_VERSION,".claude/skills/zaip-aios/agents/openai.yaml",DISCOVERY_SKILL_OPENAI_METADATA,"discovery-skill-openai-metadata"),managedAdapterFile(ADAPTERS_VERSION,".codex/config.toml",renderCodexConfig(codexConfig,catalog),"codex-config"),...codexHookAdapterFiles(ADAPTERS_VERSION),managedAdapterFile(ADAPTERS_VERSION,".codex/rules/zaip-github-deploy.rules",CODEX_GITHUB_DEPLOY_RULES,"codex-github-deploy-rules"),managedAdapterFile(ADAPTERS_VERSION,".codex/rules/zaip-security.rules",CODEX_SECURITY_RULES,"codex-security-rules"),managedAdapterFile(ADAPTERS_VERSION,".claude/settings.json",CLAUDE_SETTINGS,"claude-settings")]}async function buildAdapters(filesystem){const catalog=await filesystem.exists(AGENT_CATALOG_PATH)?await loadGuidanceCatalog(filesystem):void 0;const files=adapterFiles(filesystem.root,catalog);for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(isPreservedUserOverlay(file2.path,current)){reconcileCodexConfig(current,file2.content,catalog!==void 0);continue}if(!isManagedAdapterFile(current,file2.path)){throw new Error(`Refusing to overwrite user-owned adapter: ${file2.path}`)}}}for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(isPreservedUserOverlay(file2.path,current)){if(file2.path===".codex/config.toml"){await filesystem.writeTextAtomic(file2.path,reconcileCodexConfig(current,file2.content,catalog!==void 0))}continue}}await filesystem.writeTextAtomic(file2.path,file2.content)}for(const path of RETIRED_MANAGED_ADAPTERS){if(!await filesystem.exists(path))continue;const current=await filesystem.readText(path);if(isUnchangedManagedAdapter(path,current)){await filesystem.removeFileIfContentMatches(path,current)}}if(catalog!==void 0)await buildAgentGuidance(filesystem,catalog)}async function checkAdapters(filesystem){const catalog=await filesystem.exists(AGENT_CATALOG_PATH)?await loadGuidanceCatalog(filesystem):void 0;const codexVariants=[void 0,filesystem.root].map(hookRoot=>adapterFiles(filesystem.root,catalog,hookRoot).find(file2=>file2.path===".codex/config.toml")?.content??"");const result2=await checkAdapterFiles(filesystem,AGENT_CATALOG_PATH,loadGuidanceCatalog,catalog2=>adapterFiles(filesystem.root,catalog2),(path,content)=>path===".codex/config.toml"&&codexVariants.some(expected=>content===expected||isPreservedUserOverlay(path,content)&&isReconciledCodexConfig(content,expected,catalog!==void 0)));return result2}function isPreservedUserOverlay(path,content){return USER_OWNED_ADAPTER_OVERLAYS.has(path)&&!isUnchangedCodexConfig(content)}function isUnchangedManagedAdapter(path,content){if(!isManagedAdapterFile(content,path))return false;const marker=content.match(/^<!-- zaip-managed [^\r\n]* sha256=([a-f0-9]{64}) -->\r?\n/);if(marker?.[1]===void 0)return false;return createHash7("sha256").update(content.slice(marker[0].length)).digest("hex")===marker[1]}var ADAPTERS_VERSION,USER_OWNED_ADAPTER_OVERLAYS,RETIRED_MANAGED_ADAPTERS,CLAUDE_SETTINGS,DISCOVERY_SKILL,DISCOVERY_SKILL_OPENAI_METADATA,CODEX_WORKSPACE_ROOT_PLACEHOLDER,CODEX_CONFIG;var init_src2=__esm({"../adapters/src/index.ts"(){"use strict";init_adapter_check();init_adapter_file_rendering();init_codex_hook_adapter_files();init_codex_windows_hook_command();init_codex_hook_activation();init_codex_config_overlay();init_codex_rules();init_agent_discovery();init_catalog_guidance();init_guidance_catalog();init_agent_runtime2();init_codex_host2();init_guidance();init_mcp();init_profiles2();init_root_guidance();ADAPTERS_VERSION="6.0.1";USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);RETIRED_MANAGED_ADAPTERS=["CLAUDE.md"];CLAUDE_SETTINGS=`{
3149
3149
  "permissions": {
3150
3150
  "allow": [],
3151
3151
  "deny": []
@@ -3331,10 +3331,10 @@ ${alternatives}
3331
3331
  ## Consequ\xEAncias
3332
3332
 
3333
3333
  ${consequences}`}function isNodeError3(error51){return error51 instanceof Error&&"code"in error51}var timestamp5,decisionV2IdSchema,decisionV2CategorySchema,decisionV2Schema,DecisionV2ConflictError,DecisionV2Repository;var init_decision_v2=__esm({"../decisions/src/decision-v2.ts"(){"use strict";init_src();init_zod();timestamp5=external_exports.string().datetime({offset:true}).or(external_exports.string().datetime());decisionV2IdSchema=external_exports.string().regex(/^DEC-(?:HUMAN|AI)-/);decisionV2CategorySchema=external_exports.enum(["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation","rollback"]);decisionV2Schema=external_exports.object({schema_version:external_exports.literal(2),id:decisionV2IdSchema,title:external_exports.string().min(1),scope_type:external_exports.enum(["change","execution"]),scope_id:external_exports.string().min(1),origin:external_exports.enum(["human","agent"]),category:decisionV2CategorySchema,context:external_exports.string().min(1),decision:external_exports.string().min(1),reason:external_exports.string().min(1),alternatives:external_exports.array(external_exports.string().min(1)),consequences:external_exports.array(external_exports.string().min(1)),reversible:external_exports.boolean(),rollback:external_exports.string().min(1),confidence:external_exports.number().min(0).max(1).nullable(),created_at:timestamp5,confirmed_at:timestamp5.nullable()}).strict().superRefine((record3,context2)=>{const expectedScopePrefix=record3.scope_type==="change"?"CHG-":"EXEC-";if(!record3.scope_id.startsWith(expectedScopePrefix)){context2.addIssue({code:"custom",path:["scope_id"],message:`${record3.scope_type} decision requires ${expectedScopePrefix} scope_id`})}const expectedDecisionPrefix=record3.origin==="human"?"DEC-HUMAN-":"DEC-AI-";if(!record3.id.startsWith(expectedDecisionPrefix)){context2.addIssue({code:"custom",path:["id"],message:`${record3.origin} decision requires ${expectedDecisionPrefix} id`})}if(record3.origin==="human"&&record3.confidence!==null){context2.addIssue({code:"custom",path:["confidence"],message:"Human decisions do not use agent confidence"})}if(record3.origin==="agent"&&record3.confidence===null){context2.addIssue({code:"custom",path:["confidence"],message:"Agent decisions require confidence"})}if(record3.origin==="human"&&record3.confirmed_at===null){context2.addIssue({code:"custom",path:["confirmed_at"],message:"Human decisions require explicit confirmation provenance"})}});DecisionV2ConflictError=class extends Error{name="DecisionV2ConflictError"};DecisionV2Repository=class{constructor(filesystem,layout){this.filesystem=filesystem;this.layout=layout;if(layout.version===1)throw new Error("Decision V2 requires a modern WorkspaceLayout")}filesystem;layout;async record(input){if(input.origin==="human"&&input.confirmed!==true){throw new Error("Human decisions require confirmed: true from the caller")}const clock=input.clock??new SystemClock;const createdAt=clock.now().toISOString();const id=input.id??createId(input.origin==="human"?"DEC-HUMAN":"DEC-AI",input.shortName,{clock,...input.collisionCode===void 0?{}:{collisionCode:input.collisionCode},...input.timeZone===void 0?{}:{timeZone:input.timeZone}});const decision=decisionV2Schema.parse({schema_version:2,id,title:input.title,scope_type:input.scopeType,scope_id:input.scopeId,origin:input.origin,category:input.category,context:input.context,decision:input.decision,reason:input.reason,alternatives:[...input.alternatives],consequences:[...input.consequences],reversible:input.reversible,rollback:input.rollback,confidence:input.confidence,created_at:createdAt,confirmed_at:input.confirmed===true?createdAt:null});const path=this.path(decision.scope_type,decision.scope_id,decision.id);const source=serializeMarkdown({metadata:decision,body:decisionBody(decision)});try{await this.filesystem.writeTextExclusive(path,source);return decision}catch(error51){if(!isNodeError3(error51)||error51.code!=="EEXIST")throw error51;const existing=await this.read(decision.scope_type,decision.scope_id,decision.id);if(JSON.stringify(existing)===JSON.stringify(decision))return existing;throw new DecisionV2ConflictError(`Divergent Decision V2 already exists: ${decision.id}`)}}async read(scopeType,scopeId,id){const path=this.path(scopeType,scopeId,id);const decision=parseMarkdown(await this.filesystem.readText(path),decisionV2Schema).metadata;if(decision.scope_type!==scopeType||decision.scope_id!==scopeId||decision.id!==id){throw new DecisionV2ConflictError(`Decision V2 metadata does not match its path: ${path}`)}return decision}async list(scope){const paths2=scope?await this.filesystem.listFiles(this.decisionDirectory(scope.type,scope.id),".md"):(await Promise.all(["change","execution"].map(type=>this.filesystem.listFiles(this.layout.entityRoot(type),".md")))).flat();const decisionPaths=paths2.filter(path=>/\/decisions\/DEC-(?:HUMAN|AI)-[^/]+\.md$/.test(path)).sort();const decisions=await Promise.all(decisionPaths.map(async path=>{const decision=parseMarkdown(await this.filesystem.readText(path),decisionV2Schema).metadata;if(posix2.basename(path,".md")!==decision.id){throw new DecisionV2ConflictError(`Decision V2 id does not match filename: ${path}`)}if(this.path(decision.scope_type,decision.scope_id,decision.id)!==path){throw new DecisionV2ConflictError(`Decision V2 owner does not match path: ${path}`)}return decision}));return decisions.sort((left,right)=>left.created_at.localeCompare(right.created_at)||left.id.localeCompare(right.id))}path(scopeType,scopeId,id){decisionV2IdSchema.parse(id);return`${this.decisionDirectory(scopeType,scopeId)}/${id}.md`}decisionDirectory(scopeType,scopeId){const ownerPath=this.layout.activePath(scopeType,scopeId);return`${posix2.dirname(ownerPath)}/decisions`}}}});function createConversationId(shortName="conversation",options={}){return createId("RUN",shortName,options).replace(/^RUN-/,"CONV-")}var init_run_v2_inputs=__esm({"../decisions/src/run-v2-inputs.ts"(){"use strict";init_src()}});function effectiveRunV2Role(run){if(run.run_role==="owner")return"orchestrator";if(run.run_role==="contributor")return"subagent";if(run.run_role!==void 0)return run.run_role;if(run.phase!=="execution")return"intake";return run.parent_run_id===null?"orchestrator":"subagent"}function effectiveRunV2Kind(run){return run.parent_run_id===null?"run":"subrun"}function effectiveRunV2Purpose(run){if(run.run_purpose!==void 0)return run.run_purpose;if(run.phase!=="execution")return"intake";if(run.agent==="agent-finalizer"||run.agent==="agent-task-finalizer")return"finalization";if(run.agent==="agent-reviewer")return"review";if(run.agent==="agent-auditor")return"audit";if(run.parent_run_id===null||effectiveRunV2Role(run)==="orchestrator")return"orchestration";return"execution"}function runV2RequiresFinalizer(run){return run.requires_finalizer===true}var init_run_v2_role=__esm({"../decisions/src/source-size-decisions/run-v2-role.ts"(){"use strict"}});var timestamp6,phaseSchema,runIdSchema,conversationIdSchema,executionIdSchema,taskIdSchema,specIdSchema,prdIdSchema,changeIdSchema,relatedRunIdSchema,agentInvocationIdSchema,modelCallIdSchema,canonicalRunRoleSchema,persistedRunRoleSchema,runPurposeSchema,runV2RoleSchema,runV2PurposeSchema,agentInvocationKindV3Schema,eventFields,runIntakeDecisionV2Schema,runStartedV2Schema,usageRecordedV2Schema,modelCallObservedV3Schema,codexTelemetryCorrelationV1Schema,codexTelemetrySpoolEventInputV1Schema,codexTelemetrySpoolEnvelopeV1Schema,invocationIdSchema,modelSelectionRecordedV2Schema,providerInvocationFinishedV2Schema,runFinishedV2Schema,runFinalizationDecidedV2Schema,runV2RecordSchema;var init_run_v2_types=__esm({"../decisions/src/run-v2-types.ts"(){"use strict";init_zod();init_run_v2_handoff();init_run_v2_primitives();init_run_v2_primitives();init_run_v2_attribution_recovery();init_run_v2_guards();init_decision_v2();init_run_v2_inputs();init_run_v2_role();timestamp6=external_exports.string().datetime({offset:true}).or(external_exports.string().datetime());phaseSchema=external_exports.enum(["conversation","planning","execution"]);runIdSchema=external_exports.string().startsWith("RUN-");conversationIdSchema=external_exports.string().startsWith("CONV-");executionIdSchema=external_exports.string().startsWith("EXEC-").nullable();taskIdSchema=external_exports.string().startsWith("TASK-").nullable();specIdSchema=external_exports.string().startsWith("SPEC-").nullable();prdIdSchema=external_exports.string().startsWith("PRD-").nullable();changeIdSchema=external_exports.string().startsWith("CHG-").nullable();relatedRunIdSchema=runIdSchema.nullable();agentInvocationIdSchema=external_exports.string().regex(/^(?:AINV|INV)-/).max(200);modelCallIdSchema=external_exports.string().startsWith("MCALL-").max(200);canonicalRunRoleSchema=external_exports.enum(["intake","orchestrator","subagent"]);persistedRunRoleSchema=external_exports.enum(["intake","orchestrator","subagent","owner","contributor"]);runPurposeSchema=external_exports.enum(["observation","intake","orchestration","execution","review","audit","finalization"]);runV2RoleSchema=canonicalRunRoleSchema;runV2PurposeSchema=runPurposeSchema;agentInvocationKindV3Schema=external_exports.enum(["orchestrator","delegated"]);eventFields={schema_version:external_exports.literal(2),event_id:external_exports.string().min(1).max(200),run_id:runIdSchema,sequence:external_exports.number().int().positive(),occurred_at:timestamp6};runIntakeDecisionV2Schema=external_exports.object({intent:external_exports.enum(["conversation","continue","refine","rework","new_work"]),classification_source:external_exports.enum(["agent","explicit","fallback"]),confidence:external_exports.number().min(0).max(1),reason_codes:external_exports.array(external_exports.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(12)}).strict();runStartedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("run.started"),attribution_status:external_exports.enum(["attributed","legacy_unattributed"]),developer_identity:developerIdentityV1Schema.nullable().optional(),phase:phaseSchema,run_role:persistedRunRoleSchema.optional(),run_purpose:runPurposeSchema.optional(),requires_finalizer:external_exports.boolean().optional(),execution_kind:external_exports.enum(["interaction","delivery"]).optional(),execution_eligibility:external_exports.array(external_exports.enum(["interaction","delivery"])).optional(),direct_execution_authorization:external_exports.string().trim().min(1).max(1e3).optional(),entrypoint:external_exports.enum(["observation","conversation","task","spec","prd"]),work_type:external_exports.enum(["new","rework"]),storage_mode:external_exports.enum(["tracked_sanitized","local_only"]),client:external_exports.string().min(1).max(100),agent:external_exports.string().min(1).max(100),agent_name:external_exports.string().min(1).max(100).nullable().optional(),agent_identity_warning:external_exports.object({code:external_exports.literal("deprecated-agent-identity"),kind:external_exports.enum(["id","codex_name","codex_task_name"]),requested:external_exports.string().min(1),canonical_id:external_exports.string().min(1),deprecated_at:external_exports.iso.date(),remove_after:external_exports.iso.date()}).strict().optional(),provider:external_exports.string().min(1).max(100).nullable(),model:external_exports.string().min(1).max(200),reasoning_effort:reasoningEffortSchema.nullable().optional(),client_thread_id:external_exports.string().min(1).max(200).nullable().optional(),client_turn_id:external_exports.string().min(1).max(200).nullable().optional(),observed_agent_id:external_exports.string().min(1).max(200).nullable().optional(),observed_agent_path:external_exports.string().min(1).max(500).nullable().optional(),observed_parent_agent_id:external_exports.string().min(1).max(200).nullable().optional(),conversation_id:conversationIdSchema.nullable(),execution_id:executionIdSchema,task_id:taskIdSchema,spec_id:specIdSchema,prd_id:prdIdSchema,change_id:changeIdSchema,parent_run_id:relatedRunIdSchema,continuation_of_run_id:relatedRunIdSchema,same_turn_handoff:external_exports.union([external_exports.object({predecessor_run_id:runIdSchema,target_spec_id:external_exports.string().startsWith("SPEC-"),authorization_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict(),external_exports.object({kind:external_exports.literal("post_publication_closure"),predecessor_run_id:runIdSchema,target_spec_id:external_exports.string().startsWith("SPEC-").nullable(),target_task_id:external_exports.string().startsWith("TASK-"),authorization_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict()]).optional(),retry_of_run_id:relatedRunIdSchema,agent_invocation_id:agentInvocationIdSchema.optional(),root_agent_invocation_id:agentInvocationIdSchema.optional(),parent_agent_invocation_id:agentInvocationIdSchema.nullable().optional(),invocation_kind:agentInvocationKindV3Schema.optional(),delegation_depth:external_exports.number().int().nonnegative().optional(),intake:runIntakeDecisionV2Schema.nullable().optional()}).strict().superRefine((record3,context2)=>{if(record3.direct_execution_authorization!==void 0&&(record3.execution_kind!=="delivery"||record3.agent!=="agent-orchestrator"||record3.run_role!=="orchestrator"||record3.parent_run_id!==null||record3.task_id===null||record3.change_id===null||record3.execution_id===null||!record3.client_thread_id||!record3.client_turn_id||record3.client_turn_id.startsWith("local-")||["unknown","unavailable","manual"].includes(record3.model)))context2.addIssue({code:"custom",path:["direct_execution_authorization"],message:"Direct execution requires an observed Task-scoped delivery root and explicit authorization"});if(record3.phase==="execution"&&record3.execution_id===null&&record3.attribution_status!=="legacy_unattributed"){context2.addIssue({code:"custom",path:["execution_id"],message:"Execution phase requires execution_id"})}const requiredEntrypointId={observation:null,conversation:record3.conversation_id,task:record3.task_id,spec:record3.spec_id,prd:record3.prd_id}[record3.entrypoint];if(record3.entrypoint==="observation"){if(record3.run_purpose!=="observation"||record3.phase!=="conversation"||record3.conversation_id!==null||record3.execution_id!==null||record3.task_id!==null||record3.spec_id!==null||record3.prd_id!==null||record3.change_id!==null||record3.requires_finalizer===true||record3.execution_kind!==void 0||record3.direct_execution_authorization!==void 0){context2.addIssue({code:"custom",path:["entrypoint"],message:"Observational Run cannot claim operational authority"})}}else if(requiredEntrypointId===null){context2.addIssue({code:"custom",path:[`${record3.entrypoint}_id`],message:`${record3.entrypoint} entrypoint requires its scope id`})}if(record3.run_role==="orchestrator"&&record3.parent_run_id!==null){context2.addIssue({code:"custom",path:["parent_run_id"],message:"orchestrator Run cannot have parent_run_id"})}if(record3.run_role==="subagent"&&record3.parent_run_id===null){context2.addIssue({code:"custom",path:["parent_run_id"],message:"subagent Sub-Run requires parent_run_id"})}if(!validSameTurnSuccessor(record3)){context2.addIssue({code:"custom",path:["same_turn_handoff"],message:"Same-turn handoff requires an exact delivery successor"})}const hasInvocationIdentity=record3.agent_invocation_id!==void 0;if(hasInvocationIdentity&&(record3.root_agent_invocation_id===void 0||record3.parent_agent_invocation_id===void 0||record3.invocation_kind===void 0||record3.delegation_depth===void 0)){context2.addIssue({code:"custom",path:["agent_invocation_id"],message:"Agent Invocation identity must be complete when present"})}if(hasInvocationIdentity&&record3.invocation_kind==="orchestrator"){if(record3.parent_agent_invocation_id!==null||record3.root_agent_invocation_id!==record3.agent_invocation_id||record3.delegation_depth!==0){context2.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator Agent Invocation must be its root at depth zero"})}}if(hasInvocationIdentity&&record3.invocation_kind==="delegated"){if(record3.parent_agent_invocation_id===null||record3.delegation_depth===0){context2.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated Agent Invocation requires a parent and positive depth"})}}for(const[field,value]of[["parent_run_id",record3.parent_run_id],["continuation_of_run_id",record3.continuation_of_run_id],["retry_of_run_id",record3.retry_of_run_id]]){if(value===record3.run_id){context2.addIssue({code:"custom",path:[field],message:`${field} cannot reference itself`})}}});usageRecordedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("usage.recorded"),phase:phaseSchema,activity_kind:external_exports.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),classification_source:external_exports.enum(["explicit","current_context","default","legacy_inferred"]),tokens:runV2TokenUsageSchema,cost:runV2CostSchema,provider:external_exports.string().min(1).max(100).nullable(),model:external_exports.string().min(1).max(200).nullable(),source_segment_key:external_exports.string().min(1).max(500).nullable(),attributed_spec_id:external_exports.string().min(1).max(200).nullable().optional(),model_call_id:modelCallIdSchema.nullable().optional(),runtime:external_exports.object({reasoning_effort:external_exports.string().min(1).max(40).nullable(),service_tier:external_exports.string().min(1).max(40).nullable()}).strict().optional(),supersedes_event_id:external_exports.string().min(1).max(200).nullable(),retrospective_correction:external_exports.literal(true).optional(),source_occurred_at:timestamp6.optional(),source_started_at:timestamp6.optional(),source_finished_at:timestamp6.optional(),duration_ms:external_exports.number().int().nonnegative().nullable().optional(),duration_provenance:external_exports.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().optional(),context_stats:external_exports.object({initial_pack_tokens:external_exports.number().int().nonnegative().nullable(),tool_output_tokens:external_exports.number().int().nonnegative().nullable(),files_opened:external_exports.number().int().nonnegative().nullable(),snippets_opened:external_exports.number().int().nonnegative().nullable()}).strict().optional()}).strict();modelCallObservedV3Schema=external_exports.object({...eventFields,type:external_exports.literal("model.call.observed"),call_id:modelCallIdSchema,agent_invocation_id:agentInvocationIdSchema,coverage:external_exports.enum(["complete","partial","unavailable"]),tokens:runV2TokenUsageSchema,cost:runV2CostSchema,provider:external_exports.string().min(1).max(100).nullable(),model:external_exports.string().min(1).max(200).nullable(),source_call_key:external_exports.string().min(1).max(500).nullable(),source_occurred_at:timestamp6.optional(),source_started_at:timestamp6.optional(),source_finished_at:timestamp6.optional(),runtime:external_exports.object({reasoning_effort:external_exports.string().min(1).max(40).nullable(),service_tier:external_exports.string().min(1).max(40).nullable()}).strict().optional()}).strict();codexTelemetryCorrelationV1Schema=external_exports.object({schema_version:external_exports.literal(1),run_id:runIdSchema,execution_id:executionIdSchema.nullable().default(null),task_id:taskIdSchema.nullable().default(null),spec_id:specIdSchema.nullable().default(null),prd_id:prdIdSchema.nullable().default(null),change_id:changeIdSchema.nullable().default(null),developer_identity:developerIdentityV1Schema.nullable().optional(),zaip_agent:external_exports.string().min(1).max(100).nullable().default(null),phase:phaseSchema.nullable().default(null),purpose:runPurposeSchema.nullable().default(null),agent_invocation_id:agentInvocationIdSchema,root_agent_invocation_id:agentInvocationIdSchema,parent_agent_invocation_id:agentInvocationIdSchema.nullable(),invocation_kind:agentInvocationKindV3Schema,delegation_depth:external_exports.number().int().nonnegative(),client:external_exports.enum(["codex","codex-desktop","codex-subagent"]),thread_id:external_exports.string().min(1).max(200).nullable(),turn_id:external_exports.string().min(1).max(200).nullable(),agent_path:external_exports.string().min(1).max(500).nullable(),native_agent_id:external_exports.string().min(1).max(200).nullable().optional()}).strict().superRefine((correlation,context2)=>{if(correlation.invocation_kind==="orchestrator"&&(correlation.parent_agent_invocation_id!==null||correlation.root_agent_invocation_id!==correlation.agent_invocation_id||correlation.delegation_depth!==0)){context2.addIssue({code:"custom",path:["invocation_kind"],message:"orchestrator telemetry correlation must be its root at depth zero"})}if(correlation.invocation_kind==="delegated"&&(correlation.parent_agent_invocation_id===null||correlation.delegation_depth===0)){context2.addIssue({code:"custom",path:["parent_agent_invocation_id"],message:"delegated telemetry correlation requires a parent and positive depth"})}if(correlation.client==="codex-subagent"&&(correlation.thread_id!==null||correlation.agent_path===null&&correlation.turn_id===null)){context2.addIssue({code:"custom",path:["agent_path"],message:"Codex subagent telemetry requires agent_path or turn_id and no root thread_id"})}if(correlation.client!=="codex-subagent"&&correlation.thread_id===null&&correlation.turn_id===null){context2.addIssue({code:"custom",path:["thread_id"],message:"Codex root telemetry requires thread_id or turn_id"})}});codexTelemetrySpoolEventInputV1Schema=external_exports.object({correlation:codexTelemetryCorrelationV1Schema,event_kind:external_exports.enum(["response","usage","terminal","error"]),source:external_exports.enum(["codex_app_server","codex_session_fallback","unavailable"]),source_event_key:external_exports.string().min(1).max(500),source_method:external_exports.enum(["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"]).optional(),stream_boundary:external_exports.enum(["item_completed","response_completed","usage_updated","error","turn_completed"]).optional(),source_occurred_at:timestamp6.nullable(),captured_at:timestamp6,coverage:external_exports.enum(["complete","partial","unavailable"]),tokens:runV2TokenUsageSchema.nullable(),provider:external_exports.string().min(1).max(100).nullable(),model:external_exports.string().min(1).max(200).nullable(),runtime:external_exports.object({reasoning_effort:external_exports.string().min(1).max(40).nullable(),service_tier:external_exports.string().min(1).max(40).nullable()}).strict(),status:external_exports.enum(["completed","failed","cancelled"]).nullable(),will_retry:external_exports.boolean().nullable().optional(),latency_ms:external_exports.number().int().nonnegative().nullable(),historical_cost:external_exports.object({estimated_usd:external_exports.number().nonnegative().nullable(),estimated_brl:external_exports.number().nonnegative().nullable(),fx_rate:external_exports.number().positive().nullable(),pricing_model:external_exports.string().nullable(),pricing_source:external_exports.string().nullable(),pricing_source_url:external_exports.string().url().nullable().optional(),pricing_catalog_updated_at:timestamp6.nullable().optional(),input_usd:external_exports.number().nonnegative().nullable(),cached_input_usd:external_exports.number().nonnegative().nullable(),cache_write_input_usd:external_exports.number().nonnegative().nullable().optional(),output_usd:external_exports.number().nonnegative().nullable(),reasoning_usd:external_exports.number().nonnegative().nullable()}).strict().nullable().optional(),context_stats:external_exports.object({initial_pack_tokens:external_exports.number().int().nonnegative().nullable(),tool_output_tokens:external_exports.number().int().nonnegative().nullable(),files_opened:external_exports.number().int().nonnegative().nullable(),snippets_opened:external_exports.number().int().nonnegative().nullable()}).strict().nullable(),discarded_counts:external_exports.object({prompt:external_exports.number().int().nonnegative(),response_text:external_exports.number().int().nonnegative(),reasoning:external_exports.number().int().nonnegative(),secrets:external_exports.number().int().nonnegative()}).strict()}).strict().superRefine((event,context2)=>{if(event.source==="codex_session_fallback"&&event.coverage==="complete"){context2.addIssue({code:"custom",path:["coverage"],message:"Codex session fallback coverage must be partial or unavailable"})}if(event.source==="unavailable"&&event.coverage!=="unavailable"){context2.addIssue({code:"custom",path:["coverage"],message:"Unavailable source requires unavailable coverage"})}if(event.source==="unavailable"&&(event.provider!==null||event.model!==null||event.runtime.reasoning_effort!==null||event.runtime.service_tier!==null||event.latency_ms!==null)){context2.addIssue({code:"custom",path:["source"],message:"Unavailable source cannot contain effective runtime observations"})}if(event.coverage==="unavailable"&&event.tokens!==null&&event.tokens.source!=="unavailable"){context2.addIssue({code:"custom",path:["tokens","source"],message:"Unavailable coverage cannot contain observed tokens"})}if(event.event_kind==="terminal"&&event.status===null){context2.addIssue({code:"custom",path:["status"],message:"Terminal telemetry requires status"})}if(event.event_kind==="error"&&(event.will_retry===true&&event.status!==null||event.will_retry!==true&&event.status!=="failed")){context2.addIssue({code:"custom",path:["status"],message:"Retrying errors require null status; terminal errors require failed status"})}});codexTelemetrySpoolEnvelopeV1Schema=external_exports.object({schema_version:external_exports.literal(1),event_id:external_exports.string().startsWith("CEVT-").max(200),checksum_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/),compaction:external_exports.object({status:external_exports.enum(["pending","compacted"]),compacted_at:timestamp6.nullable()}).strict(),event:codexTelemetrySpoolEventInputV1Schema}).strict();invocationIdSchema=external_exports.string().startsWith("INV-").max(200);modelSelectionRecordedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("model.selection.recorded"),invocation_id:invocationIdSchema,requested:external_exports.object({model:external_exports.string().min(1).max(200),reasoning_effort:external_exports.enum(["low","medium","high","xhigh"]).nullable(),velocity:external_exports.literal("standard")}).strict(),selection:external_exports.object({source:external_exports.enum(["execution-override","task-override","auto-policy","project-default"]),policy_version:external_exports.number().int().positive(),reasons:external_exports.array(external_exports.string().regex(/^[a-z][a-z0-9-]{0,63}$/)).min(1).max(20)}).strict()}).strict();providerInvocationFinishedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("provider.invocation.finished"),invocation_id:invocationIdSchema,status:external_exports.enum(["completed","failed","cancelled"]),effective:external_exports.object({provider:external_exports.string().min(1).max(100).nullable(),model:external_exports.string().min(1).max(200).nullable(),reasoning_effort:reasoningEffortSchema.nullable(),service_tier:external_exports.string().min(1).max(40).nullable()}).strict(),latency_ms:external_exports.number().int().nonnegative().nullable()}).strict();runFinishedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("run.finished"),phase:phaseSchema,status:external_exports.enum(["completed","failed","cancelled"]),duration_ms:external_exports.number().int().nonnegative().nullable().default(null),duration_provenance:external_exports.enum(["observed","reconciled","legacy_inferred","estimated","unavailable"]).nullable().default(null)}).strict();runFinalizationDecidedV2Schema=external_exports.object({...eventFields,type:external_exports.literal("run.finalization.decided"),finalizer_run_id:runIdSchema,outcome:external_exports.enum(["completed","blocked","failed","cancelled"]),summary:external_exports.string().min(1).max(4e3),evidence_ids:external_exports.array(external_exports.string().min(1).max(200)).max(100),changed_files:external_exports.array(external_exports.string().min(1).max(500)).max(1e4).default([])}).strict();runV2RecordSchema=external_exports.discriminatedUnion("type",[runStartedV2Schema,usageRecordedV2Schema,modelCallObservedV3Schema,modelSelectionRecordedV2Schema,providerInvocationFinishedV2Schema,runAttributionRecoveredV2Schema,runFinalizationDecidedV2Schema,runFinishedV2Schema])}});import{createHash as createHash13}from"node:crypto";import{lstat as lstat4}from"node:fs/promises";function assertTelemetryIndexBudget(options){if(options.deadline!==void 0&&Date.now()>=options.deadline)throw new TelemetryIndexPreparationPendingError}function telemetryIndexGroups(paths2){const groups=new Map;for(const path of paths2){const prefix=/^\.local\/codex-telemetry-spool\/v1\/events\/([a-f0-9]{2})\/[a-f0-9]{64}\.json$/.exec(path)?.[1]??"uncached";const entries=groups.get(prefix)??[];entries.push(path);groups.set(prefix,entries)}return groups}async function readTelemetryIndexShard(filesystem,prefix){if(!/^[a-f0-9]{2}$/.test(prefix))return[];const path=`${INDEX_ROOT}/${prefix}.json`;try{const stat5=await lstat4(filesystem.resolve(path));if(!stat5.isFile()||stat5.isSymbolicLink()||stat5.size>MAX_TELEMETRY_INDEX_SHARD_BYTES)return[];const bytes=await filesystem.readBytes(path);if(bytes.byteLength>MAX_TELEMETRY_INDEX_SHARD_BYTES)return[];const parsed=shardSchema.parse(JSON.parse(bytes.toString("utf8")));const{checksum_sha256,...unsigned}=parsed;if(parsed.prefix!==prefix||digest3(JSON.stringify(unsigned))!==checksum_sha256)return[];if(new Set(parsed.events.map(entry2=>entry2.path)).size!==parsed.events.length||parsed.events.some(entry2=>!entry2.path.startsWith(`${EVENT_ROOT}/${prefix}/`)))return[];return parsed.events}catch{return[]}}async function writeTelemetryIndexShard(filesystem,prefix,events){if(!/^[a-f0-9]{2}$/.test(prefix))return;const unsigned={schema_version:2,prefix,events};const content=`${JSON.stringify({...unsigned,checksum_sha256:digest3(JSON.stringify(unsigned))})}
3334
- `;if(Buffer.byteLength(content,"utf8")>MAX_TELEMETRY_INDEX_SHARD_BYTES)return;try{await filesystem.writeTextAtomic(`${INDEX_ROOT}/${prefix}.json`,content)}catch(error51){if(!(error51 instanceof Error&&"code"in error51)||!["ENOSPC","EACCES","EPERM","EROFS","EBUSY"].includes(String(error51.code)))throw error51}}var EVENT_ROOT,INDEX_ROOT,MAX_TELEMETRY_INDEX_SHARD_BYTES,TelemetryIndexPreparationPendingError,digest3,entrySchema2,shardSchema;var init_codex_telemetry_spool_cache=__esm({"../decisions/src/codex-telemetry-spool-cache.ts"(){"use strict";init_zod();init_run_v2_types();EVENT_ROOT=".local/codex-telemetry-spool/v1/events";INDEX_ROOT=".local/codex-telemetry-spool/v1/events.index";MAX_TELEMETRY_INDEX_SHARD_BYTES=64*1024*1024;TelemetryIndexPreparationPendingError=class extends Error{constructor(){super("Telemetry index preparation remains pending within the capture budget");this.name="TelemetryIndexPreparationPendingError"}};digest3=value=>createHash13("sha256").update(value).digest("hex");entrySchema2=external_exports.object({path:external_exports.string().startsWith(`${EVENT_ROOT}/`).endsWith(".json"),stat:external_exports.object({dev:external_exports.string(),ino:external_exports.string(),size:external_exports.string(),mtime_ns:external_exports.string(),ctime_ns:external_exports.string()}).strict(),envelope:codexTelemetrySpoolEnvelopeV1Schema}).strict();shardSchema=external_exports.object({schema_version:external_exports.literal(2),prefix:external_exports.string().regex(/^[a-f0-9]{2}$/),events:external_exports.array(entrySchema2),checksum_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict()}});import{lstat as lstat5,realpath as realpath6}from"node:fs/promises";import{isAbsolute as isAbsolute5,relative as relative5,sep as sep3}from"node:path";function createContainment(filesystem){return{root:realpath6(filesystem.root),parents:new Map}}async function eventStat(filesystem,path,containment){const target=filesystem.resolve(path);const parentPath=filesystem.resolve(`${EVENT_ROOT2}/${path.split("/").at(-2)??""}`);const parent=containment.parents.get(parentPath)??realpath6(parentPath);containment.parents.set(parentPath,parent);const[physicalRoot,physicalParent]=await Promise.all([containment.root,parent]);const fromRoot=relative5(physicalRoot,physicalParent);if(fromRoot===".."||fromRoot.startsWith(`..${sep3}`)||isAbsolute5(fromRoot))throw new Error(`Codex telemetry spool path escapes workspace: ${path}`);const metadata3=await lstat5(target,{bigint:true});if(!metadata3.isFile()||metadata3.isSymbolicLink())throw new Error(`Invalid Codex telemetry spool event path: ${path}`);return{dev:metadata3.dev.toString(),ino:metadata3.ino.toString(),size:metadata3.size.toString(),mtime_ns:metadata3.mtimeNs.toString(),ctime_ns:metadata3.ctimeNs.toString()}}function sameStat(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.size===right.size&&left.mtime_ns===right.mtime_ns&&left.ctime_ns===right.ctime_ns}function samePaths(left,right){return left.length===right.length&&left.every((path,index)=>path===right[index])}async function mapInBatches(values,transform2){const results=[];for(let offset=0;offset<values.length;offset+=LIST_READ_CONCURRENCY){results.push(...await Promise.all(values.slice(offset,offset+LIST_READ_CONCURRENCY).map(transform2)))}return results}var EVENT_ROOT2,LIST_READ_CONCURRENCY;var init_codex_telemetry_spool_index=__esm({"../decisions/src/codex-telemetry-spool-index.ts"(){"use strict";EVENT_ROOT2=".local/codex-telemetry-spool/v1/events";LIST_READ_CONCURRENCY=32}});import{createHash as createHash14}from"node:crypto";async function prepareCodexTelemetrySpoolIndex(filesystem,options={}){assertTelemetryIndexBudget(options);const paths2=await filesystem.listFiles(EVENT_ROOT3,".json");const containment=createContainment(filesystem);const indexed=[];for(const[prefix,members]of telemetryIndexGroups(paths2)){assertTelemetryIndexBudget(options);const cached2=await readTelemetryIndexShard(filesystem,prefix);const known2=new Map(cached2.map(entry2=>[entry2.path,entry2]));const shard=await mapInBatches(members,async path=>{try{const before=await eventStat(filesystem,path,containment);const previous=known2.get(path);const envelope=previous!==void 0&&sameStat(previous.stat,before)?tryVerifiedEnvelope(previous.envelope,path):null;const event=envelope===null?await readCodexTelemetrySpoolEvent(filesystem,path):null;const after=await eventStat(filesystem,path,containment);const validated=event===null?envelope:withoutPath(event);return validated!==null&&sameStat(before,after)?{path,stat:after,envelope:validated}:null}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}});indexed.push(...shard);if(shard.every(entry2=>entry2!==null)){const unchanged2=cached2.length===shard.length&&shard.every(entry2=>{const previous=known2.get(entry2.path);return previous!==void 0&&sameStat(previous.stat,entry2.stat)&&previous.envelope.checksum_sha256===entry2.envelope.checksum_sha256});if(!unchanged2)await writeTelemetryIndexShard(filesystem,prefix,shard)}}assertTelemetryIndexBudget(options);const membershipAfter=await filesystem.listFiles(EVENT_ROOT3,".json");assertTelemetryIndexBudget(options);if(indexed.some(entry2=>entry2===null)||!samePaths(paths2,membershipAfter))return filterAndSort(await readIndexedEvents(filesystem,options));const events=indexed;return filterAndSort(events.map(entry2=>({...entry2.envelope,spool_path:entry2.path})))}function codexTelemetryCorrelationFromRun(run){if(!["codex","codex-desktop","codex-subagent"].includes(run.client)||run.agent_invocation_id===void 0||run.root_agent_invocation_id===void 0||run.parent_agent_invocation_id===void 0||run.invocation_kind===void 0||run.delegation_depth===void 0)return null;const isSubagent=run.client==="codex-subagent";const clientThreadId=run.client_thread_id??null;const observedPath=run.entrypoint==="observation"?run.observed_agent_path??null:clientThreadId;const clientTurnId=run.client_turn_id??null;if(clientThreadId===null&&clientTurnId===null)return null;return codexTelemetryCorrelationV1Schema.parse({schema_version:1,run_id:run.run_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,developer_identity:run.developer_identity??null,zaip_agent:run.agent,phase:run.phase,purpose:run.run_purpose??null,agent_invocation_id:run.agent_invocation_id,root_agent_invocation_id:run.root_agent_invocation_id,parent_agent_invocation_id:run.parent_agent_invocation_id,invocation_kind:run.invocation_kind,delegation_depth:run.delegation_depth,client:run.client,thread_id:isSubagent?null:clientThreadId,turn_id:clientTurnId,agent_path:isSubagent?observedPath:null,...isSubagent&&observedPath===null&&run.observed_agent_id?{native_agent_id:run.observed_agent_id}:{}})}async function persistCodexTelemetryCorrelation(filesystem,correlation){const validated=codexTelemetryCorrelationV1Schema.parse(correlation);const identity2=JSON.stringify([validated.client==="codex-desktop"?"codex":validated.client,validated.thread_id,validated.turn_id,validated.agent_path,validated.turn_id===null?validated.run_id:null,...validated.client==="codex-subagent"&&validated.agent_path===null&&validated.native_agent_id?[validated.native_agent_id]:[],...validated.purpose==="observation"?["observation"]:[]]);const path=`${ROOT}/correlations/${digest4(identity2)}.json`;try{await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify(validated)}
3334
+ `;if(Buffer.byteLength(content,"utf8")>MAX_TELEMETRY_INDEX_SHARD_BYTES)return;try{await filesystem.writeTextAtomic(`${INDEX_ROOT}/${prefix}.json`,content)}catch(error51){if(!(error51 instanceof Error&&"code"in error51)||!["ENOSPC","EACCES","EPERM","EROFS","EBUSY"].includes(String(error51.code)))throw error51}}var EVENT_ROOT,INDEX_ROOT,MAX_TELEMETRY_INDEX_SHARD_BYTES,TelemetryIndexPreparationPendingError,digest3,entrySchema2,shardSchema;var init_codex_telemetry_spool_cache=__esm({"../decisions/src/codex-telemetry-spool-cache.ts"(){"use strict";init_zod();init_run_v2_types();EVENT_ROOT=".local/codex-telemetry-spool/v1/events";INDEX_ROOT=".local/codex-telemetry-spool/v1/events.index";MAX_TELEMETRY_INDEX_SHARD_BYTES=64*1024*1024;TelemetryIndexPreparationPendingError=class extends Error{constructor(){super("Telemetry index preparation remains pending within the capture budget");this.name="TelemetryIndexPreparationPendingError"}};digest3=value=>createHash13("sha256").update(value).digest("hex");entrySchema2=external_exports.object({path:external_exports.string().startsWith(`${EVENT_ROOT}/`).endsWith(".json"),stat:external_exports.object({dev:external_exports.string(),ino:external_exports.string(),size:external_exports.string(),mtime_ns:external_exports.string(),ctime_ns:external_exports.string()}).strict(),envelope:codexTelemetrySpoolEnvelopeV1Schema}).strict();shardSchema=external_exports.object({schema_version:external_exports.literal(2),prefix:external_exports.string().regex(/^[a-f0-9]{2}$/),events:external_exports.array(entrySchema2),checksum_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict()}});import{lstat as lstat5,realpath as realpath6}from"node:fs/promises";import{isAbsolute as isAbsolute5,relative as relative5,sep as sep3}from"node:path";function createContainment(filesystem){return{root:realpath6(filesystem.root),parents:new Map}}async function eventStat(filesystem,path,containment){const target=filesystem.resolve(path);const parentPath=filesystem.resolve(`${EVENT_ROOT2}/${path.split("/").at(-2)??""}`);const parent=containment.parents.get(parentPath)??realpath6(parentPath);containment.parents.set(parentPath,parent);const[physicalRoot,physicalParent]=await Promise.all([containment.root,parent]);const fromRoot=relative5(physicalRoot,physicalParent);if(fromRoot===".."||fromRoot.startsWith(`..${sep3}`)||isAbsolute5(fromRoot))throw new Error(`Codex telemetry spool path escapes workspace: ${path}`);const metadata3=await lstat5(target,{bigint:true});if(!metadata3.isFile()||metadata3.isSymbolicLink())throw new Error(`Invalid Codex telemetry spool event path: ${path}`);return{dev:metadata3.dev.toString(),ino:metadata3.ino.toString(),size:metadata3.size.toString(),mtime_ns:metadata3.mtimeNs.toString(),ctime_ns:metadata3.ctimeNs.toString()}}function sameStat(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.size===right.size&&left.mtime_ns===right.mtime_ns&&left.ctime_ns===right.ctime_ns}function samePaths(left,right){return left.length===right.length&&left.every((path,index)=>path===right[index])}async function mapInBatches(values,transform2){const results=[];for(let offset=0;offset<values.length;offset+=LIST_READ_CONCURRENCY){results.push(...await Promise.all(values.slice(offset,offset+LIST_READ_CONCURRENCY).map(transform2)))}return results}var EVENT_ROOT2,LIST_READ_CONCURRENCY;var init_codex_telemetry_spool_index=__esm({"../decisions/src/codex-telemetry-spool-index.ts"(){"use strict";EVENT_ROOT2=".local/codex-telemetry-spool/v1/events";LIST_READ_CONCURRENCY=32}});function codexTelemetryCorrelationFromRun(run){if(run.same_turn_handoff!==void 0)return null;if(!["codex","codex-desktop","codex-subagent"].includes(run.client)||run.agent_invocation_id===void 0||run.root_agent_invocation_id===void 0||run.parent_agent_invocation_id===void 0||run.invocation_kind===void 0||run.delegation_depth===void 0)return null;const isSubagent=run.client==="codex-subagent";const clientThreadId=run.client_thread_id??null;const observedPath=run.entrypoint==="observation"?run.observed_agent_path??null:clientThreadId;const clientTurnId=run.client_turn_id??null;if(clientThreadId===null&&clientTurnId===null)return null;return codexTelemetryCorrelationV1Schema.parse({schema_version:1,run_id:run.run_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,developer_identity:run.developer_identity??null,zaip_agent:run.agent,phase:run.phase,purpose:run.run_purpose??null,agent_invocation_id:run.agent_invocation_id,root_agent_invocation_id:run.root_agent_invocation_id,parent_agent_invocation_id:run.parent_agent_invocation_id,invocation_kind:run.invocation_kind,delegation_depth:run.delegation_depth,client:run.client,thread_id:isSubagent?null:clientThreadId,turn_id:clientTurnId,agent_path:isSubagent?observedPath:null,...isSubagent&&observedPath===null&&run.observed_agent_id?{native_agent_id:run.observed_agent_id}:{}})}var init_codex_telemetry_correlation=__esm({"../decisions/src/codex-telemetry-correlation.ts"(){"use strict";init_run_v2_types()}});import{createHash as createHash14}from"node:crypto";async function prepareCodexTelemetrySpoolIndex(filesystem,options={}){assertTelemetryIndexBudget(options);const paths2=await filesystem.listFiles(EVENT_ROOT3,".json");const containment=createContainment(filesystem);const indexed=[];for(const[prefix,members]of telemetryIndexGroups(paths2)){assertTelemetryIndexBudget(options);const cached2=await readTelemetryIndexShard(filesystem,prefix);const known2=new Map(cached2.map(entry2=>[entry2.path,entry2]));const shard=await mapInBatches(members,async path=>{try{const before=await eventStat(filesystem,path,containment);const previous=known2.get(path);const envelope=previous!==void 0&&sameStat(previous.stat,before)?tryVerifiedEnvelope(previous.envelope,path):null;const event=envelope===null?await readCodexTelemetrySpoolEvent(filesystem,path):null;const after=await eventStat(filesystem,path,containment);const validated=event===null?envelope:withoutPath(event);return validated!==null&&sameStat(before,after)?{path,stat:after,envelope:validated}:null}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}});indexed.push(...shard);if(shard.every(entry2=>entry2!==null)){const unchanged2=cached2.length===shard.length&&shard.every(entry2=>{const previous=known2.get(entry2.path);return previous!==void 0&&sameStat(previous.stat,entry2.stat)&&previous.envelope.checksum_sha256===entry2.envelope.checksum_sha256});if(!unchanged2)await writeTelemetryIndexShard(filesystem,prefix,shard)}}assertTelemetryIndexBudget(options);const membershipAfter=await filesystem.listFiles(EVENT_ROOT3,".json");assertTelemetryIndexBudget(options);if(indexed.some(entry2=>entry2===null)||!samePaths(paths2,membershipAfter))return filterAndSort(await readIndexedEvents(filesystem,options));const events=indexed;return filterAndSort(events.map(entry2=>({...entry2.envelope,spool_path:entry2.path})))}async function persistCodexTelemetryCorrelation(filesystem,correlation){const validated=codexTelemetryCorrelationV1Schema.parse(correlation);const identity2=JSON.stringify([validated.client==="codex-desktop"?"codex":validated.client,validated.thread_id,validated.turn_id,validated.agent_path,validated.turn_id===null?validated.run_id:null,...validated.client==="codex-subagent"&&validated.agent_path===null&&validated.native_agent_id?[validated.native_agent_id]:[],...validated.purpose==="observation"?["observation"]:[]]);const path=`${ROOT}/correlations/${digest4(identity2)}.json`;try{await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify(validated)}
3335
3335
  `);return validated}catch(error51){if(!isNodeError4(error51)||error51.code!=="EEXIST")throw error51}const existing=codexTelemetryCorrelationV1Schema.parse(JSON.parse(await filesystem.readText(path)));if(isCompatibleCorrelationEnrichment(existing,validated)){await filesystem.writeTextAtomic(path,`${JSON.stringify(validated)}
3336
3336
  `);return validated}if(JSON.stringify(existing)!==JSON.stringify(validated))throw new Error(`Codex telemetry correlation is already owned by ${existing.agent_invocation_id}`);return existing}async function readCodexTelemetryCorrelationForTurn(filesystem,client,threadId,turnId,agentPath,nativeAgentId=null,observation=false){const identity2=JSON.stringify([client,threadId,turnId,agentPath,null,...client==="codex-subagent"&&agentPath===null&&nativeAgentId?[nativeAgentId]:[],...observation?["observation"]:[]]);const path=`${ROOT}/correlations/${digest4(identity2)}.json`;try{const value=codexTelemetryCorrelationV1Schema.parse(JSON.parse(await filesystem.readText(path)));return(value.client==="codex-desktop"?"codex":value.client)===client&&value.thread_id===threadId&&value.turn_id===turnId&&value.agent_path===agentPath&&(agentPath!==null||!nativeAgentId||value.native_agent_id===nativeAgentId)&&value.purpose==="observation"===observation?value:null}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}}function isCompatibleCorrelationEnrichment(existing,candidate){const stableKeys=["run_id","agent_invocation_id","root_agent_invocation_id","parent_agent_invocation_id","invocation_kind","delegation_depth","client","thread_id","turn_id","agent_path","native_agent_id"];if(stableKeys.some(key=>existing[key]!==candidate[key]))return false;const enrichableKeys=["execution_id","task_id","spec_id","prd_id","change_id","zaip_agent","phase","purpose"];return enrichableKeys.every(key=>existing[key]===null||existing[key]===candidate[key])}async function listCodexTelemetryCorrelations(filesystem){const paths2=await filesystem.listFiles(`${ROOT}/correlations`,".json");const correlations=await mapInBatches(paths2,path=>readListedJson(filesystem,path));return correlations.filter(value=>value!==null).map(value=>codexTelemetryCorrelationV1Schema.parse(value)).sort((left,right)=>left.agent_invocation_id.localeCompare(right.agent_invocation_id)||left.run_id.localeCompare(right.run_id))}async function appendCodexTelemetrySpoolEvent(filesystem,input){const event=codexTelemetrySpoolEventInputV1Schema.parse(input);await persistCodexTelemetryCorrelation(filesystem,event.correlation);const sourceDigest=digest4(event.source_event_key);const path=`${ROOT}/events/${sourceDigest.slice(0,2)}/${sourceDigest}.json`;const unsigned={schema_version:1,event_id:`CEVT-${sourceDigest}`,compaction:{status:"pending",compacted_at:null},event};const envelope=codexTelemetrySpoolEnvelopeV1Schema.parse({...unsigned,checksum_sha256:digest4(JSON.stringify(unsigned))});const serialized=`${JSON.stringify(envelope)}
3337
- `;if(Buffer.byteLength(serialized,"utf8")>MAX_ENVELOPE_BYTES)throw new Error("Codex telemetry spool envelope exceeds the 64 KiB sanitized limit");try{await filesystem.writeTextAtomicExclusive(path,serialized);return{...envelope,spool_path:path}}catch(error51){if(!isNodeError4(error51)||error51.code!=="EEXIST")throw error51}const existing=await readCodexTelemetrySpoolEvent(filesystem,path);const sameOwner=existing.event.correlation.agent_invocation_id===event.correlation.agent_invocation_id&&existing.event.correlation.run_id===event.correlation.run_id;if(sameOwner&&sameStableSpoolEvent(existing.event,event))return existing;if(!sameStableSpoolEvent(existing.event,event))throw new Error(`Codex telemetry source event is already owned by ${existing.event.correlation.agent_invocation_id}`);return existing}function sameStableSpoolEvent(left,right){const{captured_at:_leftCapturedAt,historical_cost:_leftCost,...stableLeft}=left;const{captured_at:_rightCapturedAt,historical_cost:_rightCost,...stableRight}=right;return JSON.stringify(stableLeft)===JSON.stringify(stableRight)}async function readCodexTelemetrySpoolEvent(filesystem,path){if(!path.startsWith(`${ROOT}/events/`)||!path.endsWith(".json"))throw new Error(`Invalid Codex telemetry spool event path: ${path}`);const envelope=codexTelemetrySpoolEnvelopeV1Schema.parse(JSON.parse(await filesystem.readText(path)));const{checksum_sha256:checksum,...unsigned}=envelope;if(digest4(JSON.stringify(unsigned))!==checksum)throw new Error(`Codex telemetry spool checksum mismatch: ${envelope.event_id}`);return{...envelope,spool_path:path}}async function listCodexTelemetrySpoolEvents(filesystem,status){const indexed=await readIndexedEvents(filesystem);return filterAndSort(indexed,status)}async function readIndexedEvents(filesystem,options={}){assertTelemetryIndexBudget(options);const paths2=await filesystem.listFiles(EVENT_ROOT3,".json");const containment=createContainment(filesystem);const events=[];for(const[prefix,members]of telemetryIndexGroups(paths2)){assertTelemetryIndexBudget(options);const cached2=await readTelemetryIndexShard(filesystem,prefix);const known2=new Map(cached2.map(entry2=>[entry2.path,entry2]));events.push(...await mapInBatches(members,async path=>{try{const entry2=known2.get(path);const metadata3=await eventStat(filesystem,path,containment);const cached3=entry2!==void 0&&sameStat(entry2.stat,metadata3)?tryVerifiedEnvelope(entry2.envelope,path):null;if(cached3!==null)return{...cached3,spool_path:path};return await readCodexTelemetrySpoolEvent(filesystem,path)}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}}))}assertTelemetryIndexBudget(options);return events.filter(event=>event!==null)}function filterAndSort(events,status){return events.filter(event=>status===void 0||event.compaction.status===status).sort(compareCodexTelemetrySpoolEvents)}function withoutPath(event){const{spool_path:_path,...envelope}=event;return envelope}function verifiedEnvelope(value){const envelope=codexTelemetrySpoolEnvelopeV1Schema.parse(value);const{checksum_sha256,...unsigned}=envelope;if(digest4(JSON.stringify(unsigned))!==checksum_sha256)throw new Error(`Codex telemetry spool checksum mismatch: ${envelope.event_id}`);return envelope}function tryVerifiedEnvelope(value,path){try{const envelope=verifiedEnvelope(value);const sourceDigest=digest4(envelope.event.source_event_key);const expectedPath=`${EVENT_ROOT3}/${sourceDigest.slice(0,2)}/${sourceDigest}.json`;return path===expectedPath&&envelope.event_id===`CEVT-${sourceDigest}`?envelope:null}catch{return null}}function compareCodexTelemetrySpoolEvents(left,right){const leftOccurredAt=left.event.source_occurred_at;const rightOccurredAt=right.event.source_occurred_at;if(leftOccurredAt===null&&rightOccurredAt!==null)return 1;if(leftOccurredAt!==null&&rightOccurredAt===null)return-1;if(leftOccurredAt!==null&&rightOccurredAt!==null){const order2=leftOccurredAt.localeCompare(rightOccurredAt);if(order2!==0)return order2}return left.event_id.localeCompare(right.event_id)}async function readListedJson(filesystem,path){try{return JSON.parse(await filesystem.readText(path))}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}}function isNodeError4(error51){return error51 instanceof Error&&"code"in error51}var ROOT,EVENT_ROOT3,MAX_ENVELOPE_BYTES,digest4;var init_codex_telemetry_spool=__esm({"../decisions/src/codex-telemetry-spool.ts"(){"use strict";init_codex_telemetry_spool_cache();init_codex_telemetry_spool_index();init_run_v2_types();ROOT=".local/codex-telemetry-spool/v1";EVENT_ROOT3=`${ROOT}/events`;MAX_ENVELOPE_BYTES=64*1024;digest4=value=>createHash14("sha256").update(value).digest("hex")}});var sourceStreamSchema,unsignedManifestSchema,historicalDeveloperAttributionManifestSchema;var init_historical_developer_attribution2=__esm({"../decisions/src/historical-developer-attribution.ts"(){"use strict";init_zod();init_run_v2_types();sourceStreamSchema=external_exports.object({run_id:external_exports.string().startsWith("RUN-"),path:external_exports.string().startsWith(".agents/records/runs/"),content_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();unsignedManifestSchema=external_exports.object({schema_version:external_exports.literal(1),manifest_id:external_exports.string().min(1),created_at:external_exports.string().datetime({offset:true}),kind:external_exports.literal("historical_developer_attribution"),assignment:developerIdentityV1Schema.extend({attribution_source:external_exports.literal("human_assigned")}),source_streams:external_exports.array(sourceStreamSchema).min(1)}).strict().superRefine((value,context2)=>{const ids2=new Set;const paths2=new Set;for(const[index,source]of value.source_streams.entries()){if(ids2.has(source.run_id))context2.addIssue({code:"custom",path:["source_streams",index,"run_id"],message:"Duplicate historical Run"});if(paths2.has(source.path))context2.addIssue({code:"custom",path:["source_streams",index,"path"],message:"Duplicate historical Run path"});ids2.add(source.run_id);paths2.add(source.path)}});historicalDeveloperAttributionManifestSchema=unsignedManifestSchema.extend({manifest_hash:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict()}});async function readDeveloperIdentityCache(filesystem){try{return developerIdentityV1Schema.parse(JSON.parse(await filesystem.readText(DEVELOPER_IDENTITY_CACHE_PATH)))}catch(error51){if(isMissing(error51))return null;throw new DeveloperIdentityBootstrapRequiredError("Developer identity cache is invalid; run `developer identity bootstrap`",{cause:error51})}}async function requireDeveloperIdentityCache(filesystem){const identity2=await readDeveloperIdentityCache(filesystem);if(identity2===null)throw new DeveloperIdentityBootstrapRequiredError("Developer identity is not configured; run `developer identity bootstrap`");return identity2}async function writeDeveloperIdentityCache(filesystem,identity2){const validated=developerIdentityV1Schema.parse({...identity2,expires_at:identity2.expires_at??null,last_verified_at:identity2.last_verified_at??identity2.verified_at});await filesystem.writeTextAtomic(DEVELOPER_IDENTITY_CACHE_PATH,`${JSON.stringify(validated)}
3337
+ `;if(Buffer.byteLength(serialized,"utf8")>MAX_ENVELOPE_BYTES)throw new Error("Codex telemetry spool envelope exceeds the 64 KiB sanitized limit");try{await filesystem.writeTextAtomicExclusive(path,serialized);return{...envelope,spool_path:path}}catch(error51){if(!isNodeError4(error51)||error51.code!=="EEXIST")throw error51}const existing=await readCodexTelemetrySpoolEvent(filesystem,path);const sameOwner=existing.event.correlation.agent_invocation_id===event.correlation.agent_invocation_id&&existing.event.correlation.run_id===event.correlation.run_id;if(sameOwner&&sameStableSpoolEvent(existing.event,event))return existing;if(!sameStableSpoolEvent(existing.event,event))throw new Error(`Codex telemetry source event is already owned by ${existing.event.correlation.agent_invocation_id}`);return existing}function sameStableSpoolEvent(left,right){const{captured_at:_leftCapturedAt,historical_cost:_leftCost,...stableLeft}=left;const{captured_at:_rightCapturedAt,historical_cost:_rightCost,...stableRight}=right;return JSON.stringify(stableLeft)===JSON.stringify(stableRight)}async function readCodexTelemetrySpoolEvent(filesystem,path){if(!path.startsWith(`${ROOT}/events/`)||!path.endsWith(".json"))throw new Error(`Invalid Codex telemetry spool event path: ${path}`);const envelope=codexTelemetrySpoolEnvelopeV1Schema.parse(JSON.parse(await filesystem.readText(path)));const{checksum_sha256:checksum,...unsigned}=envelope;if(digest4(JSON.stringify(unsigned))!==checksum)throw new Error(`Codex telemetry spool checksum mismatch: ${envelope.event_id}`);return{...envelope,spool_path:path}}async function listCodexTelemetrySpoolEvents(filesystem,status){const indexed=await readIndexedEvents(filesystem);return filterAndSort(indexed,status)}async function readIndexedEvents(filesystem,options={}){assertTelemetryIndexBudget(options);const paths2=await filesystem.listFiles(EVENT_ROOT3,".json");const containment=createContainment(filesystem);const events=[];for(const[prefix,members]of telemetryIndexGroups(paths2)){assertTelemetryIndexBudget(options);const cached2=await readTelemetryIndexShard(filesystem,prefix);const known2=new Map(cached2.map(entry2=>[entry2.path,entry2]));events.push(...await mapInBatches(members,async path=>{try{const entry2=known2.get(path);const metadata3=await eventStat(filesystem,path,containment);const cached3=entry2!==void 0&&sameStat(entry2.stat,metadata3)?tryVerifiedEnvelope(entry2.envelope,path):null;if(cached3!==null)return{...cached3,spool_path:path};return await readCodexTelemetrySpoolEvent(filesystem,path)}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}}))}assertTelemetryIndexBudget(options);return events.filter(event=>event!==null)}function filterAndSort(events,status){return events.filter(event=>status===void 0||event.compaction.status===status).sort(compareCodexTelemetrySpoolEvents)}function withoutPath(event){const{spool_path:_path,...envelope}=event;return envelope}function verifiedEnvelope(value){const envelope=codexTelemetrySpoolEnvelopeV1Schema.parse(value);const{checksum_sha256,...unsigned}=envelope;if(digest4(JSON.stringify(unsigned))!==checksum_sha256)throw new Error(`Codex telemetry spool checksum mismatch: ${envelope.event_id}`);return envelope}function tryVerifiedEnvelope(value,path){try{const envelope=verifiedEnvelope(value);const sourceDigest=digest4(envelope.event.source_event_key);const expectedPath=`${EVENT_ROOT3}/${sourceDigest.slice(0,2)}/${sourceDigest}.json`;return path===expectedPath&&envelope.event_id===`CEVT-${sourceDigest}`?envelope:null}catch{return null}}function compareCodexTelemetrySpoolEvents(left,right){const leftOccurredAt=left.event.source_occurred_at;const rightOccurredAt=right.event.source_occurred_at;if(leftOccurredAt===null&&rightOccurredAt!==null)return 1;if(leftOccurredAt!==null&&rightOccurredAt===null)return-1;if(leftOccurredAt!==null&&rightOccurredAt!==null){const order2=leftOccurredAt.localeCompare(rightOccurredAt);if(order2!==0)return order2}return left.event_id.localeCompare(right.event_id)}async function readListedJson(filesystem,path){try{return JSON.parse(await filesystem.readText(path))}catch(error51){if(isNodeError4(error51)&&error51.code==="ENOENT")return null;throw error51}}function isNodeError4(error51){return error51 instanceof Error&&"code"in error51}var ROOT,EVENT_ROOT3,MAX_ENVELOPE_BYTES,digest4;var init_codex_telemetry_spool=__esm({"../decisions/src/codex-telemetry-spool.ts"(){"use strict";init_codex_telemetry_spool_cache();init_codex_telemetry_spool_index();init_run_v2_types();init_codex_telemetry_correlation();ROOT=".local/codex-telemetry-spool/v1";EVENT_ROOT3=`${ROOT}/events`;MAX_ENVELOPE_BYTES=64*1024;digest4=value=>createHash14("sha256").update(value).digest("hex")}});var sourceStreamSchema,unsignedManifestSchema,historicalDeveloperAttributionManifestSchema;var init_historical_developer_attribution2=__esm({"../decisions/src/historical-developer-attribution.ts"(){"use strict";init_zod();init_run_v2_types();sourceStreamSchema=external_exports.object({run_id:external_exports.string().startsWith("RUN-"),path:external_exports.string().startsWith(".agents/records/runs/"),content_sha256:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict();unsignedManifestSchema=external_exports.object({schema_version:external_exports.literal(1),manifest_id:external_exports.string().min(1),created_at:external_exports.string().datetime({offset:true}),kind:external_exports.literal("historical_developer_attribution"),assignment:developerIdentityV1Schema.extend({attribution_source:external_exports.literal("human_assigned")}),source_streams:external_exports.array(sourceStreamSchema).min(1)}).strict().superRefine((value,context2)=>{const ids2=new Set;const paths2=new Set;for(const[index,source]of value.source_streams.entries()){if(ids2.has(source.run_id))context2.addIssue({code:"custom",path:["source_streams",index,"run_id"],message:"Duplicate historical Run"});if(paths2.has(source.path))context2.addIssue({code:"custom",path:["source_streams",index,"path"],message:"Duplicate historical Run path"});ids2.add(source.run_id);paths2.add(source.path)}});historicalDeveloperAttributionManifestSchema=unsignedManifestSchema.extend({manifest_hash:external_exports.string().regex(/^[a-f0-9]{64}$/)}).strict()}});async function readDeveloperIdentityCache(filesystem){try{return developerIdentityV1Schema.parse(JSON.parse(await filesystem.readText(DEVELOPER_IDENTITY_CACHE_PATH)))}catch(error51){if(isMissing(error51))return null;throw new DeveloperIdentityBootstrapRequiredError("Developer identity cache is invalid; run `developer identity bootstrap`",{cause:error51})}}async function requireDeveloperIdentityCache(filesystem){const identity2=await readDeveloperIdentityCache(filesystem);if(identity2===null)throw new DeveloperIdentityBootstrapRequiredError("Developer identity is not configured; run `developer identity bootstrap`");return identity2}async function writeDeveloperIdentityCache(filesystem,identity2){const validated=developerIdentityV1Schema.parse({...identity2,expires_at:identity2.expires_at??null,last_verified_at:identity2.last_verified_at??identity2.verified_at});await filesystem.writeTextAtomic(DEVELOPER_IDENTITY_CACHE_PATH,`${JSON.stringify(validated)}
3338
3338
  `);return validated}function developerIdentityNeedsRevalidation(identity2,now=new Date){if(identity2.expires_at===null||identity2.expires_at===void 0)return true;const expiresAt=Date.parse(identity2.expires_at);return!Number.isFinite(expiresAt)||expiresAt<=now.getTime()}function verifiedDeveloperIdentity(account,now=new Date){const verifiedAt=now.toISOString();return developerIdentityV1Schema.parse({schema_version:1,provider:"github",account_id:account.id,login_snapshot:account.login,attribution_source:"verified_local_account",verified_at:verifiedAt,last_verified_at:verifiedAt,expires_at:new Date(now.getTime()+DEVELOPER_IDENTITY_CACHE_TTL_MS).toISOString()})}function cachedFallbackDeveloperIdentity(identity2){return developerIdentityV1Schema.parse({...identity2,attribution_source:"cached_fallback",last_verified_at:identity2.last_verified_at??identity2.verified_at})}function isMissing(error51){return typeof error51==="object"&&error51!==null&&"code"in error51&&error51.code==="ENOENT"}var DEVELOPER_IDENTITY_CACHE_PATH,DEVELOPER_IDENTITY_CACHE_TTL_MS,DeveloperIdentityBootstrapRequiredError;var init_developer_identity_cache=__esm({"../decisions/src/developer-identity-cache.ts"(){"use strict";init_run_v2_types();DEVELOPER_IDENTITY_CACHE_PATH=".local/developer-identity.json";DEVELOPER_IDENTITY_CACHE_TTL_MS=24*60*60*1e3;DeveloperIdentityBootstrapRequiredError=class extends Error{name="DeveloperIdentityBootstrapRequiredError"}}});function isExistingLock(error51){return error51 instanceof Error&&"code"in error51&&error51.code==="EEXIST"}async function withRunAppendLock(filesystem,path,runId,recoverOrphan,append){const lockPath=`${path}.lock`;const claim=()=>filesystem.writeTextExclusive(lockPath,`${JSON.stringify({run_id:runId,pid:process.pid})}
3339
3339
  `);try{await claim()}catch(error51){if(!isExistingLock(error51))throw error51;if(!await recoverOrphan())throw new Error(`Run V2 is being updated concurrently: ${runId}`);try{await claim()}catch(retryError){if(isExistingLock(retryError))throw new Error(`Run V2 is being updated concurrently: ${runId}`);throw retryError}}try{await append()}finally{await filesystem.removeFile(lockPath)}}var init_run_v2_append_lock=__esm({"../decisions/src/run-v2-append-lock.ts"(){"use strict"}});function isTransientMissingWorkspacePath(error51){return isNodeError5(error51)&&error51.code==="ENOENT"||error51 instanceof WorkspacePathError&&isNodeError5(error51.cause)&&error51.cause.code==="ENOENT"}function isTransientAtomicWorkspacePath(error51){return isTransientMissingWorkspacePath(error51)||isNodeError5(error51)&&error51.code==="EBADF"||error51 instanceof WorkspacePathError&&(isNodeError5(error51.cause)&&error51.cause.code==="EBADF"||error51.message.startsWith("Physical path escapes workspace root:"))}function isNodeError5(error51){return error51 instanceof Error&&"code"in error51}async function delay2(milliseconds){await new Promise(resolveDelay=>setTimeout(resolveDelay,milliseconds))}function invocationClaim(identity2,ownerNonce){const now=Date.now();return{schema_version:2,identity:identity2,run_id:null,owner_pid:process.pid,owner_nonce:ownerNonce,claimed_at:new Date(now).toISOString(),lease_expires_at:new Date(now+3e4).toISOString()}}async function readInvocationClaim(filesystem,path,identity2,digest14){let text=null;const maxAttempts=5;for(let attempt=0;attempt<maxAttempts;attempt+=1){try{text=await filesystem.readText(path);break}catch(error51){if(!isTransientAtomicWorkspacePath(error51)||attempt===maxAttempts-1)throw error51;await delay2(5*(attempt+1))}}if(text===null)throw new Error(`Subagent invocation claim disappeared: ${digest14}`);const claim=JSON.parse(text);if(claim.identity!==identity2){throw new Error(`Subagent invocation claim is incompatible: ${digest14}`)}return claim}function claimIsStale(claim){const expiry=Date.parse(claim.lease_expires_at);return!Number.isFinite(expiry)||expiry<=Date.now()}async function acquireRecoveryLease(filesystem,claimPath2,staleOwnerNonce,ownerNonce){let recoveryPath=`${claimPath2}.recovery-${staleOwnerNonce}.json`;for(let generation=0;generation<8;generation+=1){const lease=invocationClaim(`recovery:${staleOwnerNonce}`,ownerNonce);try{await filesystem.writeTextExclusive(recoveryPath,`${JSON.stringify(lease)}
3340
3340
  `);return recoveryPath}catch(error51){if(!isNodeError5(error51)||error51.code!=="EEXIST")throw error51;let existing;try{existing=JSON.parse(await filesystem.readText(recoveryPath))}catch(readError){if(isTransientMissingWorkspacePath(readError))continue;throw readError}if(!claimIsStale(existing))return null;recoveryPath=`${recoveryPath}.${existing.owner_nonce}.json`}}throw new Error("Subagent invocation recovery lease chain exceeded")}async function commitInvocationClaim(filesystem,claimPath2,identity2,digest14,ownerNonce,runId){const claim=await readInvocationClaim(filesystem,claimPath2,identity2,digest14);if(claim.owner_nonce!==ownerNonce){if(claim.run_id===runId)return;throw new Error(`Subagent invocation claim ownership changed: ${digest14}`)}await filesystem.writeTextAtomic(claimPath2,`${JSON.stringify({...claim,run_id:runId,lease_expires_at:new Date().toISOString()})}
@@ -3578,8 +3578,8 @@ A preencher.
3578
3578
  ## Resumo final
3579
3579
 
3580
3580
  A preencher.`}var timestamp10,taskSchema2,TaskRepository;var init_src7=__esm({"../tasks/src/index.ts"(){"use strict";init_src();init_zod();init_scheduler2();init_qa();init_state_machine2();init_worktrees();init_autonomous();init_host_native();init_v24();init_v2_assurance();init_v2_transition();timestamp10=external_exports.string().datetime({offset:true});taskSchema2=external_exports.object({id:external_exports.string().startsWith("TASK-"),title:external_exports.string().min(1),short_name:external_exports.string().min(1),status:external_exports.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:external_exports.enum(["lite","standard","critical"]),priority:external_exports.enum(["low","medium","high","urgent"]),owner:external_exports.string().min(1).nullable().default(null),progress:external_exports.number().int().min(0).max(100),spec:external_exports.string().startsWith("SPEC-"),change:external_exports.string().startsWith("CHG-"),requirements:external_exports.array(external_exports.string().startsWith("REQ-")),depends_on:external_exports.array(external_exports.string().startsWith("TASK-")),human_decisions:external_exports.array(external_exports.string().startsWith("DEC-HUMAN-")),agent_decisions:external_exports.array(external_exports.string().startsWith("DEC-AI-")),created_at:timestamp10,started_at:timestamp10.nullable(),finished_at:timestamp10.nullable()}).strict();TaskRepository=class{constructor(filesystem,basePath=".agents/tasks"){this.filesystem=filesystem;this.basePath=basePath}filesystem;basePath;async create(input){const clock=input.clock??new SystemClock;const task={id:createId("TASK",input.shortName,{clock}),title:input.title,short_name:input.shortName,status:"planned",risk:input.risk,priority:input.priority??"medium",owner:input.owner??null,progress:0,spec:input.spec,change:input.change,requirements:[...input.requirements],depends_on:[...input.dependsOn??[]],human_decisions:[],agent_decisions:[],created_at:clock.now().toISOString(),started_at:null,finished_at:null};await this.filesystem.writeTextAtomic(this.path(task.id),serializeMarkdown({metadata:task,body:taskBody(task.title)}));return task}async read(id){const source=await this.filesystem.readText(this.path(id));const document=parseMarkdown(source,taskSchema2);return{task:document.metadata,body:document.body}}async transition(id,status,clock=new SystemClock){const current=await this.read(id);workItemStateMachine.assertTransition(current.task.status,status);const task={...current.task,status,progress:status==="completed"?100:current.task.progress,started_at:status==="executing"&&current.task.started_at===null?clock.now().toISOString():current.task.started_at,finished_at:["completed","failed","cancelled"].includes(status)?clock.now().toISOString():current.task.finished_at};if(status==="completed"){assertTaskCompletion(task,current.body)}await this.filesystem.writeTextAtomic(this.path(id),serializeMarkdown({metadata:task,body:current.body}));return task}async update(id,patch,body){const current=await this.read(id);const task=taskSchema2.parse({...current.task,...patch});await this.filesystem.writeTextAtomic(this.path(id),serializeMarkdown({metadata:task,body:body??current.body}));return task}async list(){const paths2=await this.filesystem.listFiles(this.basePath,".md");return Promise.all(paths2.map(async path=>parseMarkdown(await this.filesystem.readText(path),taskSchema2).metadata))}path(id){return datedMarkdownPath(this.basePath,id)}}}});function parseArguments(arguments_){const positionals=[];const flags=new Set;const options={};for(let index=0;index<arguments_.length;index+=1){const value=arguments_[index];if(!value.startsWith("--")){positionals.push(value);continue}const[name,inline]=value.slice(2).split("=",2);if(name===void 0)continue;const next=arguments_[index+1];if(inline!==void 0)options[name]=inline;else if(next!==void 0&&!next.startsWith("--")){options[name]=next;index+=1}else flags.add(name)}return{positionals,flags,options}}function listLifecyclePage(entities,parsed){const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);const ordered=entities.filter(entity=>statuses.size===0||statuses.has(entity.status)).filter(entity=>from===null||Date.parse(entity.created_at)>=from).filter(entity=>to===null||Date.parse(entity.created_at)<=to).sort((left,right)=>right.created_at.localeCompare(left.created_at)||right.id.localeCompare(left.id));const after=parsed.options.after;const start=after===void 0?0:ordered.findIndex(entity=>entity.id===after)+1;if(after!==void 0&&start===0)throw new UsageError(`--after id not found: ${after}`);if(parsed.flags.has("all"))return ordered.slice(start);const rawLimit=parsed.options.limit;const limit=rawLimit===void 0?20:Number(rawLimit);if(!Number.isInteger(limit)||limit<1||limit>200){throw new UsageError("--limit must be an integer from 1 to 200; use --all explicitly")}return ordered.slice(start,start+limit)}function compactPreparedEntity(entity){const{prepared_plan:plan,...summary}=entity;return{...summary,preparation:plan===void 0||plan===null?null:{revision:plan.revision,hash:plan.hash,execution_id:plan.execution_id,change_count:plan.blueprints.changes.length,task_count:plan.blueprints.tasks.length}}}function dateBoundary(value,endOfDay){if(value===void 0)return null;const normalized=/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T${endOfDay?"23:59:59.999":"00:00:00.000"}Z`:value;const timestamp13=Date.parse(normalized);if(!Number.isFinite(timestamp13))throw new UsageError(`Invalid date boundary: ${value}`);return timestamp13}function requireOptions(options,names){const missing=names.filter(name=>options[name]===void 0);if(missing.length>0){throw new UsageError(`Missing options: ${missing.map(name=>`--${name}`).join(", ")}`)}}function requiredPosition(values,index,label){const value=values[index];if(value===void 0)throw new UsageError(`Missing ${label}`);return value}function requiredEntityId(parsed,index,label,optionName="id"){return parsed.options[optionName]??requiredPosition(parsed.positionals,index,label)}function numberOption(value,fallback){const result2=value===void 0?fallback:Number(value);if(!Number.isFinite(result2)||result2<=0)throw new UsageError("Expected a positive number");return result2}function nullableNumberOption(value){if(value===void 0)return null;const result2=Number(value);if(!Number.isSafeInteger(result2)||result2<0){throw new UsageError("Token counts must be non-negative integers")}return result2}function runUsageMetadataOptions(options,defaultSourceOccurredAt){const names=["initial-pack-tokens","tool-output-tokens","files-opened","snippets-opened"];const contextStats=names.some(name=>options[name]!==void 0)?{initial_pack_tokens:nullableNumberOption(options["initial-pack-tokens"]),tool_output_tokens:nullableNumberOption(options["tool-output-tokens"]),files_opened:nullableNumberOption(options["files-opened"]),snippets_opened:nullableNumberOption(options["snippets-opened"])}:void 0;return{...(options["source-occurred-at"]??defaultSourceOccurredAt)===void 0?{}:{source_occurred_at:options["source-occurred-at"]??defaultSourceOccurredAt},...contextStats===void 0?{}:{context_stats:contextStats}}}function nullableCurrencyOption(value){if(value===void 0)return null;const result2=Number(value);if(!Number.isFinite(result2)||result2<0){throw new UsageError("Costs must be non-negative numbers")}return result2}function runV2PhaseOption(value){if(value==="conversation"||value==="planning"||value==="execution")return value;throw new UsageError("--phase must be conversation, planning, or execution")}function runV2EntrypointOption(value){if(value==="conversation"||value==="task"||value==="spec"||value==="prd"){return value}throw new UsageError("--entrypoint must be conversation, task, spec, or prd")}function runV2WorkTypeOption(value){if(value==="new"||value==="rework")return value;throw new UsageError("--work-type must be new or rework")}function runV2ClassificationOption(value){if(value===void 0)return"explicit";if(value==="explicit"||value==="current_context"||value==="default")return value;throw new UsageError("--classification must be explicit, current_context, or default")}function runV2FinishStatusOption(value){if(value===void 0)return"completed";if(value==="completed"||value==="failed"||value==="cancelled")return value;throw new UsageError("--status must be completed, failed, or cancelled")}function tokenSourceOption(value){if(value===void 0)return"unavailable";if(value==="client"||value==="provider_reported")return"provider_reported";if(value==="estimated"||value==="unavailable")return value;throw new UsageError("--token-source must be provider_reported, estimated, unavailable or legacy client")}function riskOption(value){if(value===void 0)return"standard";if(value==="lite"||value==="standard"||value==="critical")return value;throw new UsageError("--risk must be lite, standard, or critical")}function priorityOption(value){if(value===void 0)return"medium";if(["low","medium","high","urgent"].includes(value)){return value}throw new UsageError("--priority must be low, medium, high, or urgent")}function originOption(value){if(value==="human"||value==="agent")return value;throw new UsageError("--origin must be human or agent")}function decisionV2ScopeOption(parsed){const changeId=parsed.options.change;const executionId=parsed.options.execution;if(changeId!==void 0&&executionId!==void 0){throw new UsageError("Use only one Decision scope: --change or --execution")}if(changeId!==void 0)return{type:"change",id:changeId};if(executionId!==void 0)return{type:"execution",id:executionId};return void 0}function confidenceOption(value){const confidence=value===void 0?.8:Number(value);if(!Number.isFinite(confidence)||confidence<0||confidence>1){throw new UsageError("--confidence must be between 0 and 1")}return confidence}function categoryV2Option(value){if(value==="rollback")return value;return categoryOption(value)}function categoryOption(value){const values=["architecture","contract","database","security","dependency","network","infrastructure","cost","implementation"];const match=values.find(candidate=>candidate===value);if(match===void 0)throw new UsageError(`--category must be one of: ${values.join(", ")}`);return match}function csvOption(value){return value?.split(",").map(item=>item.trim()).filter(Boolean)??[]}var UsageError;var init_cli_arguments=__esm({"src/cli-arguments.ts"(){"use strict";UsageError=class extends Error{}}});function allocateInvocationBudget(input,children){if(input.policy.autonomy)return new Map(children.map(child=>[child.id,null]));const total=input.policy.max_total_invocations;const explicit=new Map(children.flatMap(child=>{const max=input.spec_execution_policies[child.spec_id]?.max_total_invocations;return max===void 0?[]:[[child.id,max]]}));if(total===null){return new Map(children.map(child=>[child.id,explicit.get(child.id)??null]))}const taskCountByChild=new Map;for(const task of input.tasks){if(task.child_execution_id===void 0)continue;taskCountByChild.set(task.child_execution_id,(taskCountByChild.get(task.child_execution_id)??0)+1)}const parentWeight=1+input.tasks.filter(task=>task.child_execution_id===void 0).length;const weights=children.filter(child=>!explicit.has(child.id)).map(child=>({id:child.id,weight:1+(taskCountByChild.get(child.id)??0)}));const reserved=[...explicit.values()].reduce((sum,value)=>sum+(value??0),0);if(total<parentWeight+children.length+reserved){throw new UsageError(`Global invocation budget ${total} cannot fund isolated SPEC budgets and the parent finalizer`)}const distributable=total-parentWeight-children.length-reserved;const totalWeight=parentWeight+weights.reduce((sum,item)=>sum+item.weight,0);return new Map([...children.filter(child=>explicit.has(child.id)).map(child=>[child.id,explicit.get(child.id)??null]),...weights.map(item=>[item.id,1+Math.floor(distributable*item.weight/totalWeight)])])}var init_autonomous_invocation_budget=__esm({"src/autonomous-invocation-budget.ts"(){"use strict";init_cli_arguments()}});function materializedExecution(runtime,execution,artifactPath){return{mode:runtime==="codex_native"?"host-native":"manual",status:"materialized",execution,provider_started:false,side_effects:false,artifact_path:artifactPath}}function resolveExecutionRuntime(config2,limits={plan:1,provider:1,squad:1},source="task"){if(config2.execution?.runtime==="codex_native")return{runtime:"codex_native"};if(!config2.execution||config2.execution.runtime==="manual"||source==="interaction"||config2.execution.runtime==="managed"&&source==="task")return{runtime:"manual"};const autonomous=config2.execution.autonomous;if(config2.autonomy?.version===1&&autonomous.provider!=="codex"){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires Codex for managed execution. Select Codex; direct conversations remain available with the selected provider.")}const effectiveParallelism=Math.min(autonomous.max_parallelism,positiveLimit(limits.plan,"plan"),positiveLimit(limits.provider,"provider"),positiveLimit(limits.squad,"squad"));return{runtime:"autonomous",provider:autonomous.provider,model:autonomous.model,lease_ms:autonomous.lease_ms,effective_parallelism:effectiveParallelism,max_phase_attempts:autonomous.max_phase_attempts,max_total_invocations:autonomous.max_total_invocations}}function positiveLimit(value,label){if(!Number.isInteger(value)||value<1){throw new TypeError(`${label} parallelism must be a positive integer`)}return value}var init_execution_runtime_config=__esm({"src/execution-runtime-config.ts"(){"use strict"}});import{isDeepStrictEqual}from"node:util";async function validatePublisherRecoveryBoundary(git8,row,candidate,published){const repair=row.publisher_recovery_sha;const inventory3=row.publisher_recovery_paths;if(repair!==candidate||repair===published||!Array.isArray(inventory3)||inventory3.length===0||inventory3.some(path=>typeof path!=="string"||!allowed(path))||new Set(inventory3).size!==inventory3.length||!Number.isSafeInteger(row.publisher_recovery_ci_run_id)||Number(row.publisher_recovery_ci_run_id)<=0)return false;try{if((await git8("merge-base",published,candidate)).trim()!==published||(await git8("rev-parse","--verify",`refs/tags/v${row.from}^{commit}`)).trim()!==published)return false;if(!isDeepStrictEqual(JSON.parse(await git8("show",`${published}:${cyclePath}`)),JSON.parse(await git8("show",`${candidate}:${cyclePath}`))))return false;const revisions=(await git8("rev-list","--reverse",`${published}..${candidate}`)).split(/\r?\n/).filter(Boolean);if(revisions.length===0)return false;for(const revision of revisions){if((await git8("rev-list","--parents","-n","1",revision)).trim().split(/\s+/).length!==2)return false;const changed=paths(await git8("diff-tree","--no-commit-id","--no-renames","-r","--name-only","-z",revision));if(changed.some(path=>!allowed(path)))return false}const actual=paths(await git8("diff","--no-renames","--name-only","-z",published,candidate));return actual.includes(".github/workflows/publish-cli.yml")&&actual.includes("scripts/resolve-npm-release.mjs")&&isDeepStrictEqual(actual,[...inventory3].sort())}catch{return false}}var cyclePath,controlPaths,allowed,paths;var init_candidate_publisher_recovery=__esm({"src/candidate-publisher-recovery.ts"(){"use strict";cyclePath=".agents/config/release-cycle.json";controlPaths=new Set([".github/workflows/publish-cli.yml","scripts/resolve-npm-release.mjs","scripts/resolve-npm-release.test.mjs","scripts/simple-release-workflow.test.mjs","scripts/npm-publication-contract.test.mjs","scripts/release-publisher-recovery.mjs","scripts/release-publisher-recovery.test.mjs","scripts/release-publisher-recovery-integration.test.mjs","scripts/release-cycle-gate.mjs","scripts/release-cycle-gate.test.mjs","scripts/release-cycle-cli.mjs","scripts/local-release-closure.mjs","scripts/local-release-closure.test.mjs","scripts/local-release-closure.test-fixture.mjs","scripts/local-release-deploy.mjs"]);allowed=path=>controlPaths.has(path)||/^docs\/quality\/v\d+-[a-z0-9-]+\.md$/.test(path);paths=output2=>output2.split("\0").filter(Boolean).sort()}});import{readFile as readFile7}from"node:fs/promises";import{resolve as resolve10}from"node:path";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";async function isPublishedCycleAdvance(git8,root,candidate,taskId,historicalBoundary){let before;let after;try{before=JSON.parse(await git8("show",`${candidate}:${releaseCyclePath}`));after=JSON.parse(await readFile7(resolve10(root,releaseCyclePath),"utf8"))}catch{return null}if(before===null||after===null||Array.isArray(before)||Array.isArray(after)||before.schema_version!==1||before.state!=="frozen"||typeof before.current_release!=="string"||!/^\d+\.\d+$/.test(before.current_release)||typeof before.release_task_id!=="string"||!before.release_task_id.startsWith("TASK-")||taskId!==void 0&&taskId!==before.release_task_id||typeof before.release_run_id!=="string"||!before.release_run_id.startsWith("RUN-")||typeof before.frozen_at!=="string"||!Number.isFinite(Date.parse(before.frozen_at))||new Date(before.frozen_at).toISOString()!==before.frozen_at||!Array.isArray(before.history))return null;const from=before.current_release;const history=after.history;if(!Array.isArray(history))return null;const appendedRow=history[before.history.length];const to=historicalBoundary?appendedRow?.to:after.current_release;if(typeof to!=="string"||!/^\d+\.\d+$/.test(to))return null;const[fromMajor=NaN,fromMinor=NaN]=from.split(".").map(Number);const[toMajor=NaN,toMinor=NaN]=to.split(".").map(Number);if(!Number.isSafeInteger(toMajor)||!Number.isSafeInteger(toMinor)||!(toMajor>fromMajor||toMajor===fromMajor&&toMinor>fromMinor))return null;if(history.length<before.history.length+1||!historicalBoundary&&history.length!==before.history.length+1||!isDeepStrictEqual2(history.slice(0,before.history.length),before.history))return null;const append=history[before.history.length];if(append===null||typeof append!=="object"||Array.isArray(append))return null;const row=append;const timestamp13=row.advanced_at;if(typeof timestamp13!=="string"||!Number.isFinite(Date.parse(timestamp13))||new Date(timestamp13).toISOString()!==timestamp13||Date.parse(timestamp13)<Date.parse(before.frozen_at)||!Number.isSafeInteger(row.ci_run_id)||Number(row.ci_run_id)<=0)return null;const published=row.sha;if(typeof published!=="string"||!/^[0-9a-f]{40}$/.test(published))return null;const candidateSha=await git8("rev-parse",candidate);try{await git8("cat-file","-e",`${published}^{commit}`)}catch{return null}const recoveryDeclared=Object.keys(row).some(key=>key.startsWith("publisher_recovery_"));const recoveredPublisher=recoveryDeclared&&await validatePublisherRecoveryBoundary(git8,row,candidateSha,published);if(recoveryDeclared&&!recoveredPublisher)return null;if(!recoveredPublisher&&await git8("merge-base",candidateSha,published)!==candidateSha)return null;if(await git8("merge-base",published,"HEAD")!==published)return null;const publicationCommits=(await git8("rev-list","--reverse",`${candidateSha}..${published}`)).split(/\r?\n/).filter(Boolean);for(const successor of publicationCommits){if((await git8("rev-list","--parents","-n","1",successor)).split(/\s+/).length!==2)return null;const changed=splitZero(await git8("diff-tree","--root","-m","--no-commit-id","-r","--name-only","-z",successor));if(changed.some(path=>!path.startsWith(".agents/records/")))return null}if(!isDeepStrictEqual2(row,{from,to,sha:published,ci_run_id:row.ci_run_id,release_url:`https://github.com/zaip-ai/zaip-aios/releases/tag/v${from}`,advanced_at:timestamp13,...recoveredPublisher?{publisher_recovery_sha:candidateSha,publisher_recovery_ci_run_id:row.publisher_recovery_ci_run_id,publisher_recovery_paths:row.publisher_recovery_paths}:{}}))return null;if(!historicalBoundary&&!isDeepStrictEqual2(after,{...before,current_release:to,state:"open",release_task_id:null,release_run_id:null,release_mode:null,history:[...before.history,row]}))return null;const staged=await git8("diff","--cached","--name-only","--",releaseCyclePath);if(!historicalBoundary&&staged!==""){let index;try{index=JSON.parse(await git8("show",`:${releaseCyclePath}`))}catch{return null}if(!isDeepStrictEqual2(index,after))return null}const revisions=(await git8("rev-list","--reverse",`${candidate}..HEAD`,"--",releaseCyclePath)).split(/\r?\n/).filter(Boolean);if(!historicalBoundary&&revisions.length>1)return null;if(!historicalBoundary&&revisions.length===1){const changedInCommit=splitZero(await git8("diff-tree","--no-commit-id","-r","--name-only","-z",revisions[0]??""));if(changedInCommit.some(path=>path!==releaseCyclePath&&!metadata(path)))return null;const workingChanges=await git8("diff","--name-only","HEAD","--",releaseCyclePath);if(workingChanges!=="")return null}return{publishedSha:published,releaseTaskId:before.release_task_id}}function metadata(path){return path.startsWith(".agents/records/")||path===".agents/config/framework.lock.yaml"}function splitZero(value){return value.split("\0").filter(Boolean).map(path=>path.replaceAll("\\","/"))}var releaseCyclePath;var init_candidate_publication_boundary=__esm({"src/candidate-publication-boundary.ts"(){"use strict";init_candidate_publisher_recovery();releaseCyclePath=".agents/config/release-cycle.json"}});function changedFilesOutsideTaskScopes(writeScopes,changedFiles){if(writeScopes.length===0)return[];return changedFiles.filter(path=>!writeScopes.some(scope=>workspaceScopeMatches(scope,path)))}function containsIdentifier(content,identifier){const escaped=identifier.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|[^A-Z0-9-])${escaped}(?:$|[^A-Z0-9-])`,"m").test(content)}function containsIsoTimestamp(content){return/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})\b/.test(content)}function assertRiskScaledArtifactCounts(taskId,risk2,verificationCount,evidenceCount){if(risk2!=="lite")return;if(verificationCount<1)throw new LifecycleGateError(`Lite Task ${taskId} requires at least one verification artifact; found ${verificationCount}`);if(evidenceCount<1)throw new LifecycleGateError(`Lite Task ${taskId} requires at least one Evidence; found ${evidenceCount}`)}function workspaceScopeMatches(scope,path){const normalizedScope=scope.replaceAll("\\","/").replace(/\/+$/,"");const normalizedPath=path.replaceAll("\\","/");if(!normalizedScope.includes("*"))return normalizedPath===normalizedScope||normalizedPath.startsWith(`${normalizedScope}/`);const pattern=normalizedScope.split("**").map(segment2=>segment2.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")).join(".*");return new RegExp(`^${pattern}$`).test(normalizedPath)}function formatLifecycleState(entity){return`${entity.id} (${entity.status})`}function isTerminalLifecycleStatus(status){return new Set(["completed","failed","cancelled"]).has(status)}var init_lifecycle_gate_helpers=__esm({"src/lifecycle-gate-helpers.ts"(){"use strict";init_lifecycle_assurance_v2()}});import{execFile as execFile5}from"node:child_process";import{promisify as promisify5}from"node:util";async function inspectFinalProductCandidate(root,validations,evidences,scopes,taskId,ownedFiles,publishedBoundary){const commits=[...new Set([...validations,...evidences].map(item=>item.commit_sha).filter(sha5=>sha5!==null))];const accepted=[];const findings=[];const git8=async(...args)=>{try{return(await exec("git",["--literal-pathspecs",...args],{cwd:root,encoding:"utf8",windowsHide:true,maxBuffer:8*1024*1024})).stdout.trim()}catch(error51){throw new CandidateGitFailure(args[0]??"unknown",error51)}};for(const commit of commits){try{await git8("cat-file","-e",`${commit}^{commit}`);await git8("merge-base","--is-ancestor",commit,"HEAD");const tree=await git8("rev-parse",`${commit}^{tree}`);const cycleAdvance=await isPublishedCycleAdvance(git8,root,commit,taskId,publishedBoundary);const validCycleAdvance=cycleAdvance!==null;const sealedPublishedBoundary=cycleAdvance!==null&&publishedBoundary!==void 0&&publishedBoundary.candidate_sha===commit&&publishedBoundary.published_sha===cycleAdvance.publishedSha&&publishedBoundary.target_task_id===cycleAdvance.releaseTaskId&&publishedBoundary.evidence_ids.length>0&&publishedBoundary.evidence_ids.every(id=>evidences.some(item=>item.id===id&&item.task_id===publishedBoundary.target_task_id&&item.commit_sha===commit));if(publishedBoundary!==void 0&&!sealedPublishedBoundary){findings.push({code:"changed-product",commit,files:[releaseCyclePath2],remedy:"Historical relay receipt, Evidence and published cycle must name one candidate boundary."});continue}const executableValidations=validations.filter(validation=>!["review","quality_review","spec_review"].includes(validation.kind));const isolated=taskId!==void 0&&executableValidations.length>0&&validations.every(validation=>validation.task_id===taskId&&validation.commit_sha===commit&&validation.status==="passed")&&executableValidations.every(validation=>{const proof=validation.candidate_execution;return validation.task_id===taskId&&validation.commit_sha===commit&&validation.status==="passed"&&proof?.kind==="isolated_git_worktree"&&proof.protocol==="committed_node_harness_v1"&&proof.commit_sha===commit&&proof.tree_sha===tree&&proof.exit_code===0&&Number.isFinite(Date.parse(proof.started_at))&&Date.parse(proof.finished_at)>=Date.parse(proof.started_at)})&&evidences.length>0&&evidences.every(item=>item.task_id===taskId&&item.commit_sha===commit);const deliveryFiles=isolated?[...new Set([...ownedFiles??[],...splitZero2(await git8("diff-tree","--root","--no-commit-id","--name-only","-r","-z",commit))])].filter(path=>!metadata2(path)):[];if(isolated&&deliveryFiles.length>0){if(deliveryFiles.some(path=>!safePath(path)||outside(path,scopes))){findings.push({code:"changed-product",commit,files:deliveryFiles,remedy:"Use normalized delivery files inside the Task scopes."});continue}const changed=splitZero2(await git8("diff","--name-only","-z",commit,"--",...deliveryFiles));const untracked=splitZero2(await git8("ls-files","--others","--exclude-standard","-z","--",...deliveryFiles));const missing=[];const committedChanges=splitZero2(await git8("diff-tree","--root","--no-commit-id","--name-only","-r","-z",commit));for(const path of deliveryFiles){if(await git8("ls-tree","--name-only",commit,"--",path)===""&&!committedChanges.includes(path)&&!await deletedByTaskInCandidateAncestry(git8,commit,path,taskId))missing.push(path)}const drift=[...new Set([...changed,...untracked,...missing])].filter(path=>path!==releaseCyclePath2||!validCycleAdvance);if(drift.length>0){findings.push({code:"changed-product",commit,files:drift,remedy:"Commit and validate the changed delivery again; isolated proof cannot approve different delivery bytes."});continue}accepted.push(commit);continue}const uncommitted=sealedPublishedBoundary?[]:(await Promise.all([git8("diff","--name-only","-z"),git8("diff","--cached","--name-only","-z"),git8("ls-files","--others","--exclude-standard","-z")])).flatMap(splitZero2).filter(path=>!metadata2(path)&&!outside(path,scopes)).filter(path=>path!==releaseCyclePath2||!validCycleAdvance);if(uncommitted.length>0){findings.push({code:"uncommitted-product",commit,files:[...new Set(uncommitted)],remedy:"Use task commit for owned files, then validation execute on that commit in an isolated worktree; preserve unrelated changes."});continue}let invalid=false;for(const successor of(await git8("rev-list","--reverse",`${commit}..HEAD`)).split(/\r?\n/).filter(Boolean)){if(sealedPublishedBoundary&&cycleAdvance!==null&&successor!==cycleAdvance.publishedSha&&await git8("merge-base",cycleAdvance.publishedSha,successor)===cycleAdvance.publishedSha)continue;const paths2=splitZero2(await git8("diff-tree","--no-commit-id","-r","--name-only","-z",successor)).filter(path=>!metadata2(path)&&!outside(path,scopes)).filter(path=>path!==releaseCyclePath2||!validCycleAdvance);if(paths2.length===0)continue;const identities=taskCommitIdentities(await git8("show","-s","--format=%B",successor));const unattributed=identities.length===0||taskId!==void 0&&!isLegacyFourCharacterTask(taskId)&&!identities.some(id=>id.startsWith("TASK-"));if(taskId===void 0||identities.some(id=>matchesTaskIdentity(id,taskId))||unattributed){findings.push({code:unattributed?"unattributed-successor":"changed-product",commit,files:paths2,remedy:"Validate the current product candidate or provide its real Task attribution."});invalid=true;break}}if(!invalid)accepted.push(commit)}catch(error51){findings.push({code:"git-unavailable",commit,files:[],remedy:`Verify Git access, the candidate commit and its ancestry before retrying.${error51 instanceof CandidateGitFailure?` ${error51.diagnostic}`:""}`})}}if(accepted.length===1)return{commit:accepted[0]??null,findings:[]};if(accepted.length>1)findings.push({code:"ambiguous-candidate",commit:null,files:[],remedy:"Select Evidence and validations from one final candidate."});if(commits.length===0)findings.push({code:"missing-candidate",commit:null,files:[],remedy:"Create a local task commit before executing validations and recording Evidence."});return{commit:null,findings}}function taskCommitIdentities(message2){const trailers2=[...message2.matchAll(/^ZAIP-Task:\s*(\S+)\s*$/gim)].map(match=>match[1]).filter(value=>value!==void 0);const subject2=message2.match(/^(?:\[(?:CODEX|CLAUDE)\]\s+)?\[Task-first:([A-Z0-9]{4})\]/m)?.[1];return subject2===void 0?trailers2:[...trailers2,subject2]}function matchesTaskIdentity(identity2,taskId){if(identity2===taskId)return true;const legacySuffix=isLegacyFourCharacterTask(taskId)?taskId.slice(-4):void 0;return legacySuffix!==void 0&&identity2===legacySuffix}function isLegacyFourCharacterTask(taskId){return/-([A-Z0-9]{4})$/.test(taskId)}async function deletedByTaskInCandidateAncestry(git8,candidate,path,taskId){if(taskId===void 0)return false;const commits=splitZero2(await git8("log","--format=%H%x00",candidate,"--",path)).map(value=>value.trim()).filter(Boolean);const deletions=[];for(const ancestor of commits){const deleted=splitZero2(await git8("diff-tree","--root","--no-commit-id","-r","--diff-filter=D","--name-only","-z",ancestor,"--",path));if(deleted.includes(path))deletions.push(ancestor)}return deletions.length===1&&taskCommitIdentities(await git8("show","-s","--format=%B",deletions[0]??"")).some(identity2=>matchesTaskIdentity(identity2,taskId))}function metadata2(path){return path.startsWith(".agents/records/")||path===".agents/config/framework.lock.yaml"}function outside(path,scopes){return scopes!==void 0&&scopes.length>0&&!scopes.some(scope=>workspaceScopeMatches(scope,path))}function safePath(path){return path.length>0&&!path.startsWith("/")&&!path.includes("\\")&&!path.includes(":")&&!path.split("/").includes("..")}function splitZero2(value){return value.split("\0").filter(Boolean).map(path=>path.replaceAll("\\","/"))}var exec,releaseCyclePath2,CandidateGitFailure;var init_candidate_resolution=__esm({"src/candidate-resolution.ts"(){"use strict";init_src();init_candidate_publication_boundary();init_lifecycle_gate_helpers();exec=promisify5(execFile5);releaseCyclePath2=".agents/config/release-cycle.json";CandidateGitFailure=class extends Error{diagnostic;constructor(operation,cause){super(`Git ${operation} failed`,{cause});const failure=cause;const detail=typeof failure?.stderr==="string"?redactSensitive(failure.stderr).replace(/\bnpm_[A-Za-z0-9]+\b/g,"[REDACTED]").trim().slice(0,400):"";this.diagnostic=`operation=${operation}; code=${failure?.code??"unavailable"}; signal=${failure?.signal??"none"}${detail?`; ${detail}`:""}`}}}});var LifecycleGateError;var init_lifecycle_gate_error=__esm({"src/lifecycle-gate-error.ts"(){"use strict";LifecycleGateError=class extends Error{name="LifecycleGateError"}}});import{execFile as execFile6}from"node:child_process";import{promisify as promisify6}from"node:util";function assertEditorialDeliveryEligibility(task,signals){if(signals?.editorial_delivery!==true)return false;if(task.assurance_risk_signals_source!=="explicit"||task.assurance_risk_signals?.editorial_delivery!==true)throw new LifecycleGateError(`Editorial delivery requires an explicit persisted risk signal: ${task.id}`);if(task.risk!=="lite"||signals.verification_scope!=="scoped")throw new LifecycleGateError(`Editorial delivery requires lite risk and scoped verification: ${task.id}`);if(signals.production_impact||signals.external_action||signals.irreversible_change||signals.security_or_critical_data||signals.data_migration||signals.broad_audit||signals.rollback!==void 0&&signals.rollback!=="trivial")throw new LifecycleGateError(`Editorial delivery cannot include sensitive or critical signals: ${task.id}`);if(task.write_scopes.length===0||task.write_scopes.some(scope=>!isSafeEditorialScope(scope)))throw new LifecycleGateError(`Editorial delivery requires only narrow editorial write scopes: ${task.id}`);return true}async function assertEditorialCandidateDiff(input){if(!assertEditorialDeliveryEligibility(input.task,input.signals))return;const paths2=splitNul(await gitBytes(input.root,["diff-tree","--root","--no-commit-id","--no-renames","--name-only","-z","-r",input.commit])).filter(path=>!path.startsWith(".agents/records/"));if(paths2.length===0)throw new LifecycleGateError(`Editorial candidate has no changed files: ${input.task.id}`);if(!samePaths2(paths2,input.changedFiles))throw new LifecycleGateError(`Editorial candidate diff does not match Task changed files: ${input.task.id}`);for(const path of paths2){assertEditorialCandidatePath(path);const entry2=(await gitBytes(input.root,["ls-tree","-z",input.commit,"--",path])).toString("utf8");if(!entry2.startsWith("100644 "))throw new LifecycleGateError(`Editorial candidate requires a regular non-executable file: ${path}`);const content=await gitBytes(input.root,["show",`${input.commit}:${path}`]);let textual=true;try{new TextDecoder("utf-8",{fatal:true}).decode(content)}catch{textual=false}if(!textual||content.some(byte=>byte<32&&![9,10,13].includes(byte)||byte===127))throw new LifecycleGateError(`Editorial candidate cannot contain binary content: ${path}`)}}function assertEditorialCandidatePath(path){if(path.length===0||path.includes("\\")||path.startsWith("/")||/^[a-z]:/i.test(path)||path.split("/").some(part=>part===""||part==="."||part===".."))throw new LifecycleGateError(`Editorial candidate has an unsafe path: ${path}`);if(readmes.has(path))return;const root=roots.find(candidate=>path.startsWith(candidate));if(root===void 0)throw new LifecycleGateError(`Editorial candidate is outside editorial roots: ${path}`);const relative19=path.slice(root.length);if(root==="docs/"&&!path.endsWith(".md"))throw new LifecycleGateError(`Editorial candidate under docs/ must be Markdown: ${path}`);if(/(?:^|\/)(?:AGENTS|CLAUDE|SKILL)\.md$/i.test(relative19)||/(?:^|\/)(?:\.agents|\.codex|\.claude|config|configs|rules|skills|runtime|tools)(?:\/|$)/i.test(relative19)||/\.(?:[cm]?[jt]sx?|py|go|rs|java|cs|sh|ps1|mjs|cjs|json|ya?ml|toml|ini)$/i.test(path))throw new LifecycleGateError(`Editorial candidate cannot alter code, configuration, or agent control: ${path}`);if(!/\.(?:md|txt|csv)$/i.test(path))throw new LifecycleGateError(`Editorial candidate must contain a textual artifact: ${path}`)}function isSafeEditorialScope(scope){if(scope.includes("\\")||scope.startsWith("/")||/^[a-z]:/i.test(scope))return false;if(readmes.has(scope))return true;const root=roots.find(candidate=>scope.startsWith(candidate));if(root===void 0)return false;const relative19=scope.slice(root.length);if(root==="docs/"&&!relative19.includes("*")&&!relative19.endsWith(".md"))return false;if(relative19.length===0||relative19.split("/").some(part=>part===""||part==="."||part===".."))return false;if(/(?:^|\/)(?:\.agents|\.codex|\.claude|config|configs|rules|skills|runtime|tools)(?:\/|$)/i.test(relative19))return false;if(relative19.includes("*"))return/^[-a-z0-9_]+(?:\/[-a-z0-9_]+)*\/\*\*$/i.test(relative19);return/\.(?:md|txt|csv)$/i.test(relative19)}function splitNul(value){const text=value.toString("utf8");if(!text.endsWith("\0"))throw new LifecycleGateError("Editorial candidate returned malformed Git paths");return text.slice(0,-1).split("\0")}function samePaths2(actual,changed){return actual.length===changed.length&&actual.every(path=>changed.includes(path))}async function gitBytes(root,args){try{const{stdout}=await execFileAsync5("git",args,{cwd:root,encoding:"buffer",windowsHide:true});return Buffer.from(stdout)}catch{throw new LifecycleGateError("Editorial candidate commit cannot be inspected")}}var execFileAsync5,readmes,roots;var init_editorial_delivery_assurance=__esm({"src/editorial-delivery-assurance.ts"(){"use strict";init_lifecycle_gate_error();execFileAsync5=promisify6(execFile6);readmes=new Set(["README.md","README-ENG.md"]);roots=[".agents/marketing/",".agents/growth/",".agents/branding/",".agents/sales/",".agents/ops/","docs/"]}});import{posix as posix3}from"node:path";async function readAssuranceBundle(filesystem,layout,tasks,selectedEvidenceIds){const taskIds=new Set(tasks.map(task=>task.id));const evidenceIds=selectedEvidenceIds===void 0?null:new Set(selectedEvidenceIds);const directories=[...new Set(tasks.map(task=>posix3.dirname(layout.activePath("change",task.change_id))))];const validations=[];const evidences=[];const metadata3=[];for(const directory2 of directories){const verificationPaths=(await Promise.all(["tests","evals","checks"].map(kind=>filesystem.listFiles(`${directory2}/artifacts/${kind}`)))).flat();for(const path of verificationPaths){const source=await filesystem.readText(path);const raw=frontmatterMetadata(source);if(raw!==null)metadata3.push(raw);try{const artifact=parseMarkdown(source,validationArtifactV2Schema).metadata;if(taskIds.has(artifact.task_id))validations.push(artifact)}catch{}}for(const path of await filesystem.listFiles(`${directory2}/artifacts/evidence`)){let artifact;try{artifact=parseMarkdown(await filesystem.readText(path),evidenceArtifactV2Schema).metadata}catch{continue}if(taskIds.has(artifact.task_id)&&(evidenceIds===null||evidenceIds.has(artifact.id))){await assertReferencedObservations(filesystem,directory2,artifact);evidences.push(artifact)}}}const selectedValidationIds=evidenceIds===null?null:new Set(evidences.flatMap(evidence=>evidence.validation_artifact_ids));return{validations:uniqueById(selectedValidationIds===null?validations:validations.filter(validation=>selectedValidationIds.has(validation.id))),evidences:uniqueById(evidences),metadata:metadata3}}async function assertReferencedObservations(filesystem,directory2,evidence){const prefix=`${directory2}/artifacts/observations/`;for(const locator of evidence.locators){const slashPath=locator.replaceAll("\\","/");const looksLikeObservation=/(?:^|\/)artifacts\/observations(?:\/|$)/.test(slashPath);if(!looksLikeObservation)continue;if(slashPath!==locator||posix3.normalize(slashPath)!==slashPath){throw new Error(`Referenced observation path is not normalized: ${locator}`)}const match=new RegExp(`^${escapeRegExp5(prefix)}(OBS-[A-Z0-9]+(?:-[A-Z0-9]+)*)\\.md$`).exec(slashPath);if(match===null){throw new Error(`Referenced observation is outside its Change directory: ${locator}`)}const path=slashPath;let observation;try{observation=parseMarkdown(await filesystem.readText(path),evidenceObservationV1Schema).metadata}catch{throw new Error(`Referenced observation is unreadable or has an unknown schema: ${path}`)}if(observation.id!==match[1]||observation.state!=="confirmed"||observation.task_id!==evidence.task_id||observation.change_id!==evidence.change_id||observation.execution_id!==evidence.execution_id||observation.run_id!==evidence.run_id||observation.commit_sha!==evidence.commit_sha||observation.acceptance_ids.some(id=>!evidence.acceptance_ids.includes(id))){throw new Error(`Referenced observation does not confirm Evidence ${evidence.id}: ${path}`)}}}function escapeRegExp5(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function frontmatterMetadata(source){const normalized=source.replace(/^\uFEFF/,"").replace(/\r\n/g,"\n");if(!normalized.startsWith("---\n"))return null;const end=normalized.indexOf("\n---\n",4);if(end===-1)return null;try{const metadata3=parseYaml(normalized.slice(4,end));return isRecord6(metadata3)?metadata3:null}catch{return null}}function uniqueById(items){return[...new Map(items.map(item=>[item.id,item])).values()]}function isRecord6(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}var init_lifecycle_assurance_bundle=__esm({"src/lifecycle-assurance-bundle.ts"(){"use strict";init_src();init_assurance()}});function resolveTaskExecutionIdV2(task,executions,explicitExecutionId){if(explicitExecutionId!==void 0){const explicit=executions.find(execution=>execution.id===explicitExecutionId);if(explicit===void 0)throw new UsageError(`Explicit Execution does not resolve: ${explicitExecutionId}`);if(!explicit.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){throw new UsageError(`Explicit Execution does not contain Task and Change DAG node: ${explicitExecutionId}`)}return explicit.id}const linkedExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id;if(linkedExecutionId!==void 0){const linked=executions.find(execution=>execution.id===linkedExecutionId);if(linked===void 0){throw new UsageError(`Task linked Execution does not resolve: ${linkedExecutionId}`)}if(linked.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){return linkedExecutionId}}const candidates=executions.filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id));if(candidates.length!==1){throw new UsageError(`Task Execution resolution requires exactly one matching DAG node: ${task.id} (${candidates.length} found)`)}const candidate=candidates[0];if(candidate===void 0)throw new UsageError(`Task Execution does not resolve: ${task.id}`);return candidate.id}var init_task_execution_resolution_v2=__esm({"src/task-execution-resolution-v2.ts"(){"use strict";init_cli_arguments()}});import{execFile as execFile7}from"node:child_process";import{createHash as createHash35}from"node:crypto";import{promisify as promisify7}from"node:util";function effectiveTaskRiskSignals(task){const profile=task.model_profile?.risk_signals;if(task.assurance_risk_signals===void 0)return profile;if(task.assurance_risk_signals_source==="risk_default"&&profile!==void 0)return profile;return Object.fromEntries(Object.entries({...profile,...task.assurance_risk_signals}).filter(([,value])=>value!==void 0))}async function readTaskMutationApplicabilityV1(filesystem,task,executionId){if(task.attempt_count===void 0||task.attempt_count===0)return void 0;const path=taskMutationApplicabilityPath(task.id,task.attempt_count);if(!await filesystem.exists(path))return void 0;const map2=taskMutationApplicabilityV1Schema.parse(JSON.parse(await filesystem.readText(path)));return validateTaskMutationApplicabilityV1(filesystem,task,executionId,map2)}function taskMutationApplicabilityPath(taskId,attemptCount){if(!/^TASK-[A-Z0-9-]+$/.test(taskId)||!Number.isInteger(attemptCount)||attemptCount<1)throw new LifecycleGateError("Invalid Task mutation applicability identity");return`.agents/records/assurance/task-mutation-applicability/${taskId}/attempt-${attemptCount}.json`}async function validateTaskMutationApplicabilityV1(filesystem,task,executionId,map2){const mutationIds=mutationAcceptanceIdsFromApplicability(map2,task,executionId);const date5=/^CHG-(\d{4})-(\d{2})-/.exec(task.change_id);if(!date5)throw new LifecycleGateError("Mutation applicability has an invalid Change identity");const decisionDirectory=`.agents/records/changes/${date5[1]}/${date5[2]}/${task.change_id}/decisions`;for(const decision of[{id:map2.authorization.human_decision_id,sha256:map2.authorization.human_decision_sha256,origin:"human"},{id:map2.authorization.classification_decision_id,sha256:map2.authorization.classification_decision_sha256,origin:"agent"}]){const source=await filesystem.readText(`${decisionDirectory}/${decision.id}.md`);const metadata3=frontmatterMetadata(source);if(metadata3?.id!==decision.id||metadata3.origin!==decision.origin||metadata3.scope_id!==task.change_id||stableDecisionHash(source)!==decision.sha256)throw new LifecycleGateError(`Mutation applicability decision is not the attributed record: ${decision.id}`)}return mutationIds}function stableDecisionHash(source){const normalized=source.replace(/\r\n/g,"\n");if(normalized.includes("\r"))throw new LifecycleGateError("Decision contains bare CR");return createHash35("sha256").update(normalized,"utf8").digest("hex")}function effectiveTaskAssurance(task,config2){const signals=effectiveTaskRiskSignals(task);assertEditorialDeliveryEligibility(task,signals);const standard_depth=resolveStandardDepth(config2,signals,task.write_scopes);const requireFinalCommit=config2.require_final_commit||taskSignalsRequireFinalCommitEvidence(task.risk,signals);return{contract:{...resolveTaskAssuranceContract({risk:task.risk,standard_depth,controls:{risk_signals:signals}}),requires_final_commit_evidence:requireFinalCommit},standard_depth,require_final_commit:requireFinalCommit}}function taskAssurancePreflightResult(evidenceIds){return{summary:"Typed assurance preflight",changed_files:[],evidence_ids:[...evidenceIds],completed_run_id:null}}async function assertTaskAssurancePreflightV1(input){const bundle=await readAssuranceBundle(input.filesystem,input.layout,[input.task],input.evidence_ids);assertTaskAssuranceV1({config:input.config,task:input.task,risk:input.task.risk,write_scopes:input.task.write_scopes,acceptance_ids:input.task.acceptance_ids,validations:bundle.validations,evidences:bundle.evidences,verifier:preflightVerifierFrom(bundle.validations),mutation:mutationFrom(bundle.metadata,input.task.id),mutation_acceptance_ids:await readTaskMutationApplicabilityV1(input.filesystem,input.task,resolveTaskExecutionIdV2(input.task,await new ExecutionV2Repository(input.filesystem,input.layout).list())),rollback_evidence_id:bundle.evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:null,risk_signals:effectiveTaskRiskSignals(input.task),enforce_final_commit:false})}function assertHostAssuranceV1(assessment){if(assessment.valid)return;throw new LifecycleGateError(`Host assurance ${assessment.status}: ${assessment.findings.map(finding3=>`${finding3.code}:${finding3.subject}`).join("; ")}`)}function assertTaskAssuranceV1(input){const effective=input.task===void 0?{contract:resolveTaskAssuranceContract({risk:input.risk,standard_depth:resolveStandardDepth(input.config,input.risk_signals,input.write_scopes),controls:{risk_signals:input.risk_signals}}),require_final_commit:input.config.require_final_commit}:effectiveTaskAssurance(input.task,input.config);const contract=effective.contract;const assessment=assessTaskAssurance({...input,contract:{...contract,requires_final_commit_evidence:input.enforce_final_commit!==false&&(effective.require_final_commit||taskSignalsRequireFinalCommitEvidence(input.risk,input.risk_signals))}});assertAssessment(`Task ${contract.profile}`,assessment);if(input.host_assurance!==void 0)assertHostAssuranceV1(input.host_assurance)}function resolveStandardDepth(config2,signals,historicalWriteScopes){if(config2.standard_depth!=="auto")return config2.standard_depth;if(signals===void 0)return historicalWriteScopes.length>1?"elevated":"base";return signals.verification_scope==="scoped"?"base":"elevated"}function assertDeliveryAssuranceV1(input){if(input.acceptance_ids.length===0){throw new LifecycleGateError(`${input.origin.toUpperCase()} assurance requires an AC matrix`)}if(input.origin==="prd"&&input.outcome_ids.length===0){throw new LifecycleGateError("PRD assurance requires outcome Evidence ids")}const contract=resolveDeliveryAssuranceContract(input.origin);const assessment=assessDeliveryAssurance({...input,contract:input.config.require_final_commit?contract:{...contract,requires_final_commit_evidence:false}});assertAssessment(`${input.origin.toUpperCase()} delivery`,assessment)}function mutationFrom(metadata3,taskId){const item=metadata3.find(value=>value.kind==="mutation_discrimination"&&value.task_id===taskId);if(item===void 0||!Array.isArray(item.acceptance_ids))return null;if(item.baseline_passed!==true||typeof item.total_mutants!=="number"||typeof item.killed_mutants!=="number"||typeof item.kill_ratio!=="number"||!item.acceptance_ids.every(value=>typeof value==="string")){return null}return{baseline_passed:true,total_mutants:item.total_mutants,killed_mutants:item.killed_mutants,kill_ratio:item.kill_ratio,acceptance_ids:item.acceptance_ids}}function deliveryMutationFrom(metadata3,taskIds){const mutations=[...new Set(taskIds)].map(taskId=>mutationFrom(metadata3,taskId)).filter(item=>item!==null);if(mutations.length===0||mutations.some(item=>!item.baseline_passed))return null;const total_mutants=mutations.reduce((total,item)=>total+item.total_mutants,0);const killed_mutants=mutations.reduce((total,item)=>total+item.killed_mutants,0);return{baseline_passed:true,total_mutants,killed_mutants,kill_ratio:Math.min(...mutations.map(item=>item.kill_ratio)),acceptance_ids:[...new Set(mutations.flatMap(item=>item.acceptance_ids))]}}function verifierFrom(validations,authorId,authorRunId){const review=validations.find(item=>isReviewKind(item.kind)&&item.status==="passed"&&item.author_id!==authorId&&item.run_id!==authorRunId);return review===void 0?null:{author_id:authorId,reviewer_id:review.author_id,status:"approved"}}function preflightVerifierFrom(validations){const review=validations.find(item=>isReviewKind(item.kind)&&item.status==="passed");if(review===void 0)return null;const implementation=validations.find(item=>!isReviewKind(item.kind)&&item.status==="passed"&&item.author_id!==review.author_id&&item.run_id!==review.run_id);return implementation===void 0?null:{author_id:implementation.author_id,reviewer_id:review.author_id,status:"approved"}}function isReviewKind(kind){return kind==="review"||kind==="spec_review"||kind==="quality_review"}async function currentCommitSha(root){try{const{stdout}=await execFileAsync6("git",["rev-parse","HEAD"],{cwd:root,encoding:"utf8",windowsHide:true});const sha5=stdout.trim().toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha5)?sha5:null}catch{return null}}async function resolveFinalProductCandidate(root,validations,evidences,writeScopes,taskId,ownedFiles){return(await inspectFinalProductCandidate(root,validations,evidences,writeScopes,taskId,ownedFiles)).commit}async function requireFinalProductCandidate(root,validations,evidences,writeScopes,taskId,ownedFiles,publishedBoundary){const result2=await inspectFinalProductCandidate(root,validations,evidences,writeScopes,taskId,ownedFiles,publishedBoundary);if(result2.commit!==null)return result2.commit;throw new LifecycleGateError(`final-commit-evidence: ${result2.findings.map(finding3=>`${finding3.code}${finding3.files.length?` [${finding3.files.join(", ")}]`:""}: ${finding3.remedy}`).join("; ")}`)}function assertAssessment(label,assessment){if(assessment.valid)return;throw new LifecycleGateError(`${label} assurance failed: ${assessment.findings.map(finding3=>`${finding3.code}: ${finding3.message}`).join("; ")}`)}var execFileAsync6;var init_lifecycle_assurance_v2=__esm({"src/lifecycle-assurance-v2.ts"(){"use strict";init_src();init_src6();init_assurance();init_candidate_resolution();init_editorial_delivery_assurance();init_lifecycle_assurance_bundle();init_lifecycle_gate_error();init_task_execution_resolution_v2();init_lifecycle_assurance_bundle();init_lifecycle_gate_error();execFileAsync6=promisify7(execFile7)}});import{posix as posix4}from"node:path";async function assertTaskEvidenceCoverage(context2,task,result2){if(result2.evidence_ids.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Evidence`)}const changeDirectory=posix4.dirname(context2.layout.activePath("change",task.change_id));const mainDocuments=[await context2.filesystem.readText(context2.layout.activePath("change",task.change_id))];const executions=(await context2.repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id));for(const execution of executions){mainDocuments.push(await context2.filesystem.readText(context2.layout.activePath("execution",execution.id)))}const documents=[];for(const evidenceId2 of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId2}.md`;const candidates=mainDocuments.filter(document=>containsIdentifier(document,evidenceId2)&&containsIdentifier(document,task.id));if(await context2.filesystem.exists(path)){candidates.push(`${evidenceId2}
3581
- ${await context2.filesystem.readText(path)}`)}const resolved=candidates.find(document=>containsIdentifier(document,task.id));if(resolved===void 0){throw new LifecycleGateError(`Evidence does not resolve for Task ${task.id}: ${evidenceId2}`)}documents.push(resolved)}const evidence=documents.join("\n");const missing=task.acceptance_ids.filter(id=>!containsIdentifier(evidence,id));if(missing.length>0){throw new LifecycleGateError(`Task ${task.id} Evidence does not cover Acceptance Criteria: ${missing.join(", ")}`)}}async function assertTaskSixStageCoverage(context2,task,result2,executionId,enforceLegacyRiskCounts=true,requireDecision=true){const decisions=[...await context2.repositories.decisions.list({type:"change",id:task.change_id}),...await context2.repositories.decisions.list({type:"execution",id:executionId})];if(requireDecision&&decisions.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Decision for six-stage coverage`)}const changeDirectory=posix4.dirname(context2.layout.activePath("change",task.change_id));const verificationPaths=(await Promise.all(["tests","evals","checks"].map(kind=>context2.filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat();const relatedVerificationPaths=[];for(const path of verificationPaths){const content=await context2.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){relatedVerificationPaths.push(path)}}if(relatedVerificationPaths.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Test, Eval, or Check for six-stage coverage`)}const timestampedEvidence=[];for(const evidenceId2 of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId2}.md`;if(!await context2.filesystem.exists(path))continue;const content=await context2.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){timestampedEvidence.push(path)}}if(timestampedEvidence.length===0){throw new LifecycleGateError(`Task ${task.id} requires an Evidence file with the Task id and an ISO date-time for six-stage coverage`)}if(enforceLegacyRiskCounts){assertRiskScaledArtifactCounts(task.id,task.risk,relatedVerificationPaths.length,result2.evidence_ids.length)}}var init_lifecycle_evidence_v2=__esm({"src/lifecycle-evidence-v2.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function validateRunV2Attribution(input,repositories,options={}){const entrypointId={observation:null,conversation:input.conversationId,task:input.taskId,spec:input.specId,prd:input.prdId}[input.entrypoint];if(entrypointId===void 0||entrypointId===null){throw new RunAttributionV2Error(`${input.entrypoint} entrypoint requires its scope id`)}if(input.entrypoint==="conversation"&&[input.taskId,input.specId,input.prdId,input.changeId].some(value=>value!==void 0&&value!==null)){throw new RunAttributionV2Error("Conversation entrypoint cannot claim a delivery lifecycle ancestor")}const execution=await optionalRead(input.executionId,"Execution",id=>repositories.executions.read(id));const task=await optionalRead(input.taskId,"Task",id=>repositories.tasks.read(id));const change=await optionalRead(input.changeId,"Change",id=>repositories.changes.read(id));const spec=await optionalRead(input.specId,"SPEC",id=>repositories.specs.read(id));await optionalRead(input.prdId,"PRD",id=>repositories.prds.read(id));if(input.phase==="execution"&&execution===null){throw new RunAttributionV2Error("Execution phase requires an existing Execution")}const macroTerminalSubRun=input.phase==="execution"&&execution?.execution.status==="completed"&&input.taskId==null&&input.parentRunId!=null&&["execution","review","finalization"].includes(input.runPurpose??"")&&await isDirectRunningMacroParent(input,repositories);if(input.phase==="execution"&&execution!==null&&!new Set(["running","verifying"]).has(execution.execution.status)&&!macroTerminalSubRun&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Execution ${execution.execution.id} is not running or verifying`)}if(task!==null){if(change!==null&&task.task.change_id!==change.change.id){throw new RunAttributionV2Error(`Task ${task.task.id} does not resolve to the attributed Change`)}if(input.phase==="execution"&&change===null){throw new RunAttributionV2Error(`Execution Run for Task ${task.task.id} requires its materialized Change`)}if(input.phase==="execution"&&execution===null){throw new RunAttributionV2Error(`Task ${task.task.id} attribution requires an Execution`)}if(input.phase==="execution"&&!new Set(["executing","verifying"]).has(task.task.status)&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Task ${task.task.id} is not executing or verifying`)}if(execution!==null&&execution.execution.origin.type!=="interaction"&&execution.execution.plan_hash!==null){const node=execution.execution.dag.nodes.find(candidate=>candidate.task_id===task.task.id);if(node===void 0||node.change_id!==task.task.change_id){throw new RunAttributionV2Error(`Execution ${execution.execution.id} does not own Task ${task.task.id} and Change ${task.task.change_id}`)}}}if(change!==null&&task===null&&execution!==null&&execution.execution.origin.type!=="interaction"&&execution.execution.plan_hash!==null){const ownsChange=execution.execution.dag.nodes.some(candidate=>candidate.change_id===change.change.id);if(!ownsChange){throw new RunAttributionV2Error(`Execution ${execution.execution.id} does not contain Change ${change.change.id}`)}}if(spec!==null&&input.prdId!==void 0&&input.prdId!==null&&spec.spec.prd_id!==input.prdId){throw new RunAttributionV2Error(`SPEC ${spec.spec.id} does not belong to PRD ${input.prdId}`)}if(execution!==null){const origin=execution.execution.origin;if(origin.type==="interaction"&&origin.conversation_id!==input.conversationId){throw new RunAttributionV2Error(`Interaction Execution ${execution.execution.id} belongs to another Conversation`)}if(origin.type==="spec"&&origin.spec_id!==input.specId){throw new RunAttributionV2Error(`Execution ${execution.execution.id} requires SPEC ${origin.spec_id}, not ${input.specId??"none"}`)}if(origin.type==="prd"&&origin.prd_id!==input.prdId){throw new RunAttributionV2Error(`Execution ${execution.execution.id} requires PRD ${origin.prd_id}, not ${input.prdId??"none"}`)}if(origin.type==="task"&&origin.task_id!==input.taskId){throw new RunAttributionV2Error(`Task-first Execution ${execution.execution.id} requires Task ${origin.task_id}, not ${input.taskId??"none"}`)}}if(change!==null){if(input.phase==="execution"&&!new Set(["executing","verifying"]).has(change.change.status)&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Change ${change.change.id} is not executing or verifying`)}const source=change.change.source;if(source.type==="spec"&&input.specId!==source.spec_id){throw new RunAttributionV2Error(`Change ${change.change.id} belongs to SPEC ${source.spec_id}, not ${input.specId??"none"}`)}if(source.type==="prd"&&input.prdId!==source.prd_id){throw new RunAttributionV2Error(`Change ${change.change.id} belongs to PRD ${source.prd_id}, not ${input.prdId??"none"}`)}if(source.type==="task"&&task!==null&&source.task_id!==task.task.id){throw new RunAttributionV2Error(`Task-first Change ${change.change.id} belongs to ${source.task_id}, not ${task.task.id}`)}}for(const[relationship,relatedId]of[["parent",input.parentRunId],["continuation",input.continuationOfRunId],["retry",input.retryOfRunId]]){if(relatedId===void 0||relatedId===null)continue;const related=await requiredRead(relatedId,`${relationship} Run`,id=>repositories.runs.read(id));if(related.run.conversation_id!==input.conversationId){throw new RunAttributionV2Error(`${relationship} Run ${relatedId} belongs to another Conversation`)}if(relationship==="retry"&&related.run.task_id!==(input.taskId??null)){throw new RunAttributionV2Error(`Retry Run ${relatedId} belongs to another Task`)}}}async function isDirectRunningMacroParent(input,repositories){const parentId=input.parentRunId;if(parentId===null||parentId===void 0||input.executionId==null)return false;const parent=await requiredRead(parentId,"parent Run",id=>repositories.runs.read(id));const macroScopeMatches=input.specId!=null&&parent.run.spec_id===input.specId||input.prdId!=null&&parent.run.prd_id===input.prdId;return parent.status==="running"&&parent.run.parent_run_id===null&&parent.run.task_id===null&&parent.run.execution_id===input.executionId&&parent.run.conversation_id===input.conversationId&&macroScopeMatches}async function optionalRead(id,label,read){return id===void 0||id===null?null:requiredRead(id,label,read)}async function requiredRead(id,label,read){try{return await read(id)}catch(error51){throw new RunAttributionV2Error(`${label} does not resolve: ${id} (${error51 instanceof Error?error51.message:String(error51)})`)}}var RunAttributionV2Error;var init_attribution_v2=__esm({"src/attribution-v2.ts"(){"use strict";RunAttributionV2Error=class extends Error{name="RunAttributionV2Error"}}});import{createHash as createHash36}from"node:crypto";async function checkedImplementationProposal(filesystem,composition,current,inputPath){if(!inputPath.startsWith(".local/")||inputPath.includes("\\")||inputPath.split("/").some(part=>part===".."||part==="."||part===""))throw new UsageError("Implementation proposal must be a canonical .local/ path");const proposal=specImplementationV2Schema.parse(JSON.parse(await filesystem.readText(inputPath)));return checkedImplementationValue(filesystem,composition,current,proposal)}async function checkedImplementationValue(filesystem,composition,current,proposal){if(current.implementation===null)throw new UsageError("SPEC has no implementation snapshot");const original=current.implementation;if(proposal.stack_profile!==original.stack_profile||JSON.stringify(proposal.stack_overrides)!==JSON.stringify(original.stack_overrides)||proposal.stack_components.length!==original.stack_components.length)throw new UsageError("Implementation proposal changes profile, overrides or component count");let changes=0;let expectedDescription=original.stack_description;for(let index=0;index<original.stack_components.length;index+=1){const before=original.stack_components[index];const after=proposal.stack_components[index];if(before.name!==after.name||before.kind!==after.kind||before.version_source!==after.version_source)throw new UsageError("Implementation proposal changes component identity or version source");if(before.version===after.version)continue;changes++;const source=JSON.parse(await filesystem.readText(before.version_source));if(before.name!=="pnpm"||before.version_source!=="package.json"||source.packageManager!==`pnpm@${after.version}`)throw new UsageError("Changed version is not the exact packageManager from package.json");const label=`${before.name} ${before.version}`;if(expectedDescription.split(label).length!==2)throw new UsageError("Old version must occur exactly once in stack description");expectedDescription=expectedDescription.replace(label,`${after.name} ${after.version}`)}if(changes!==1||proposal.stack_description!==expectedDescription)throw new UsageError("Only one sourced version and its exact description may change");await assertSpecImplementationMatchesProject(proposal,filesystem,composition.layout);return{implementation:proposal,deltaSha256:digest6(JSON.stringify({spec_id:current.id,previous_revision:current.revision,previous_implementation:original,next_implementation:proposal}))}}function revisedSpecSource(current,originalSource,implementation,attribution2){if(current.implementation===null||current.plan_ref===null||!["ready","blocked","active"].includes(current.status))throw new UsageError("SPEC has no recoverable materialized implementation");const next=deliverySpecV2Schema.parse({...current,revision:current.revision+1,implementation,implementation_revisions:[...current.implementation_revisions??[],{previous_revision:current.revision,previous_implementation:current.implementation,actor_task_id:attribution2.actorTaskId||null,actor_execution_id:attribution2.actorExecutionId,actor_run_id:attribution2.actorRunId,decision_id:attribution2.decisionId,delta_sha256:attribution2.deltaSha256,revised_at:attribution2.revisedAt}],updated_at:attribution2.revisedAt});const oldHeader=/^---\r?\n[\s\S]*?\r?\n---(?=\r?\n)/.exec(originalSource)?.[0];const newHeader=/^---\n[\s\S]*?\n---/.exec(serializeMarkdown({metadata:next,body:""}))?.[0];if(!oldHeader||!newHeader)throw new UsageError("SPEC frontmatter cannot be revised safely");return`${newHeader}${originalSource.slice(oldHeader.length)}`}function parseRevisedSpec(source){return parseMarkdown(source,deliverySpecV2Schema).metadata}var digest6;var init_controlled_recovery_snapshot=__esm({"src/controlled-recovery-snapshot.ts"(){"use strict";init_src();init_src6();init_cli_arguments();digest6=value=>createHash36("sha256").update(value).digest("hex")}});async function readRequiredRun(repositories,id){try{return await repositories.runs.read(id)}catch(error51){throw new LifecycleGateError(`Run ${id} does not resolve: ${error51 instanceof Error?error51.message:String(error51)}`)}}async function executionForTask(task,repositories){const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(canonicalExecutionId!==null){const{execution}=await repositories.executions.read(canonicalExecutionId);if(!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){throw new LifecycleGateError(`Execution ${canonicalExecutionId} does not contain Task/Change ${task.id}/${task.change_id}`)}return execution}const executions=(await repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id));if(executions.length!==1){throw new LifecycleGateError(`Task ${task.id} must resolve to exactly one Execution; found ${executions.length}`)}return executions[0]}async function executionForCompletionRun(task,canonicalExecution,run,repositories){if(run.run.execution_id===canonicalExecution.id)return canonicalExecution;if(run.run.continuation_of_run_id===null||run.run.execution_id===null){return canonicalExecution}const{execution}=await repositories.executions.read(run.run.execution_id);const ownsTask=execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id);if(execution.kind!=="delivery"||execution.origin.type!=="task"||execution.origin.task_id!==task.id||!ownsTask){throw new LifecycleGateError(`Continuation Run ${run.run.run_id} Execution ${execution.id} does not own Task/Change ${task.id}/${task.change_id}`)}return execution}function assertCompletedRunAttribution(run,task,executionId){if(run.finished?.status!=="completed"){throw new LifecycleGateError(`Run ${run.run.run_id} must be completed`)}assertRunAttribution(run,task,executionId)}function assertRunAttribution(run,task,executionId){const mismatches=[(run.records?.findLast(record3=>"phase"in record3)?.phase??run.run.phase)==="execution"||run.run.phase==="planning"&&run.run.work_type==="rework"?null:"phase",run.run.execution_id===executionId?null:"execution_id",run.run.task_id===task.id?null:"task_id",run.run.change_id===task.change_id?null:"change_id"].filter(value=>value!==null);if(mismatches.length>0){throw new LifecycleGateError(`Run ${run.run.run_id} attribution mismatch: ${mismatches.join(", ")}`)}}var init_lifecycle_run_attribution=__esm({"src/lifecycle-run-attribution.ts"(){"use strict";init_lifecycle_assurance_v2()}});import{createHash as createHash37}from"node:crypto";async function readReleaseCycle(filesystem){if(!await filesystem.exists(RELEASE_CYCLE_PATH))return null;let value;try{value=JSON.parse(await filesystem.readText(RELEASE_CYCLE_PATH))}catch{throw new UsageError("Release cycle configuration is invalid")}if(value.schema_version!==1||!releaseId.test(value.current_release??"")||!["open","frozen"].includes(value.state??""))throw new UsageError("Release cycle configuration must define schema 1, current_release and state");if(value.recovery_grant!==void 0){const grant=value.recovery_grant;if(grant===null||typeof grant!=="object"||value.state!=="open"||grant.schema_version!==1||!grant.target_task_id?.startsWith("TASK-")||!grant.target_spec_id?.startsWith("SPEC-")||!grant.target_execution_id?.startsWith("EXEC-")||grant.target_release!==value.current_release||!Number.isSafeInteger(grant.expected_task_revision)||grant.expected_task_revision<1||!grant.actor_run_id?.startsWith("RUN-")||!grant.decision_id?.startsWith("DEC-HUMAN-")||!Number.isFinite(Date.parse(grant.prepared_at)))throw new UsageError("Release recovery grant is invalid")}return value}async function assertCurrentReleaseForExecution(filesystem,targetRelease,label){const cycle=await readReleaseCycle(filesystem);if(cycle===null){if(targetRelease)throw new UsageError("Named release requires configured current release");return}if(cycle.state!=="open")throw new UsageError(`Current release ${cycle.current_release} is frozen; ${label} cannot start`);if(cycle.recovery_grant!==void 0)throw new UsageError(`Release ${cycle.current_release} is reserved for recovery of ${cycle.recovery_grant.target_task_id}`);if(targetRelease===null||targetRelease===void 0)throw new UsageError(`${label} has no target release; assign the current release before execution`);if(targetRelease!==cycle.current_release)throw new UsageError(`${label} targets release ${targetRelease}; only current release ${cycle.current_release} may become ready or execute`)}async function releaseTargetForDraft(filesystem,requested){const cycle=await readReleaseCycle(filesystem);if(requested!==void 0&&!releaseId.test(requested))throw new UsageError("Target release must use major.minor, for example 4.6");if(requested!==void 0&&cycle!==null){const[major=0,minor=0]=requested.split(".").map(Number);const[currentMajor=0,currentMinor=0]=cycle.current_release.split(".").map(Number);if(major<currentMajor||major===currentMajor&&minor<currentMinor)throw new UsageError("A new draft cannot target a release older than the current release")}return requested??cycle?.current_release??null}async function taskFirstRelease(filesystem,requested){const target=await releaseTargetForDraft(filesystem,requested);await assertCurrentReleaseForExecution(filesystem,target,"Task-first work");return target}async function assertTaskStartRelease(filesystem,repositories,id){const{task}=await repositories.tasks.read(id);if(["executing","verifying"].includes(task.status))return;const cycle=await readReleaseCycle(filesystem);if(cycle?.recovery_grant!==void 0){const grant=cycle.recovery_grant;if(id!==grant.target_task_id)throw new UsageError("Only the exact blocked recovery Task may resume while grant is active");const execution=await executionForTask(task,repositories);const specTarget=execution.origin.type==="spec"?(await repositories.specs.read(execution.origin.spec_id)).spec.target_release:null;if(task.status!=="blocked"||task.revision!==grant.expected_task_revision||specTarget!==grant.target_release||(task.target_release??specTarget)!==grant.target_release||execution.id!==grant.target_execution_id||execution.origin.type!=="spec"||execution.origin.spec_id!==grant.target_spec_id)throw new UsageError("Only the exact blocked recovery Task may resume while grant is active");return}const target=await effectiveTaskRelease(task,repositories);await assertCurrentReleaseForExecution(filesystem,target,"Task")}async function effectiveTaskRelease(task,repositories){if(task.target_release!=null)return task.target_release;const execution=await executionForTask(task,repositories);return execution.origin.type==="prd"?(await repositories.prds.read(execution.origin.prd_id)).prd.target_release:execution.origin.type==="spec"?(await repositories.specs.read(execution.origin.spec_id)).spec.target_release:null}async function assertPostPublicationTaskStartRelease(filesystem,repositories,id,authorization){const{task}=await repositories.tasks.read(id);if(task.status!=="blocked"||id!==authorization.targetTaskId||await effectiveTaskRelease(task,repositories)!==authorization.targetRelease)throw new UsageError("Post-publication closure authorizes only the exact blocked Task");const source=await filesystem.readText(RELEASE_CYCLE_PATH);const cycle=await readReleaseCycle(filesystem);const raw=JSON.parse(source);const publishedRows=raw.history?.filter(row=>row.from===authorization.targetRelease)??[];if(cycle?.state!=="open"||cycle.recovery_grant!==void 0||publishedRows.length!==1||publishedRows[0]?.sha!==authorization.publishedSha||createHash37("sha256").update(source).digest("hex")!==authorization.cycleSha256)throw new UsageError("Post-publication cycle authorization changed")}var RELEASE_CYCLE_PATH,releaseId;var init_release_cycle=__esm({"src/release-cycle.ts"(){"use strict";init_cli_arguments();init_lifecycle_run_attribution();RELEASE_CYCLE_PATH=".agents/config/release-cycle.json";releaseId=/^(?:[1-9]\d*)\.(?:0|[1-9]\d*)$/}});import{createHash as createHash38,randomUUID as randomUUID5}from"node:crypto";import{lstat as lstat7,readFile as readFile8,realpath as realpath7,rename as rename5,unlink as unlink2}from"node:fs/promises";import{homedir as homedir3}from"node:os";import{resolve as resolve11}from"node:path";async function resolveRunClientInvocation(filesystem,client,options={}){if(!new Set(["codex","codex-desktop"]).has(client)){return{clientThreadId:null,clientTurnId:null,userMessage:null,observedModel:null,observedReasoningEffort:null,observedServiceTier:null}}const argv=options.argv??process.argv.slice(2);const hookFlags=argv.filter(value=>value.startsWith("--codex-hook-"));const hooked=hookFlags.length>0;const hookThreads=hookFlags.filter(value=>value.startsWith("--codex-hook-thread="));const hookThread=hookThreads[0]?.slice("--codex-hook-thread=".length);const explicitThread=normalizedId(options.threadId??process.env.CODEX_THREAD_ID);if(hooked&&(hookFlags.length!==2||hookThreads.length!==1||!hookThread||!/^[A-Za-z0-9_-]{1,256}$/.test(hookThread)||explicitThread!==null&&explicitThread!==hookThread)){throw new Error("Codex hook identity is incomplete or conflicts with the active thread.")}const threadId=explicitThread??hookThread??null;const explicitTurn=normalizedId(options.turnId??process.env.CODEX_TURN_ID);const hookTurn=hooked&&threadId!==null?await observedHookTurn(filesystem.root,threadId,argv,options.now??new Date):null;if(hooked&&(hookTurn===null||explicitTurn!==null&&explicitTurn!==hookTurn)){throw new Error("Codex hook turn receipt is missing, consumed, expired or conflicts with the active turn.")}const turnId=hooked?hookTurn:explicitTurn;const transcriptPath=transcriptPathFromEnvironment();const active=await findActiveCodexInvocation(filesystem.root,{threadId,...transcriptPath===null?{}:{transcriptPath},...options.sessionsRoot===void 0?{}:{sessionsRoot:options.sessionsRoot},...options.now===void 0?{}:{now:options.now}});const matchingActive=turnId===null||active?.turnId===turnId?active:null;return{clientThreadId:threadId??matchingActive?.sessionId??null,clientTurnId:turnId??active?.turnId??null,userMessage:matchingActive?.userMessage??null,observedModel:matchingActive?.model??null,observedReasoningEffort:matchingActive?.reasoningEffort??null,observedServiceTier:matchingActive?.serviceTier??null,transcriptPath:transcriptPath??(matchingActive?resolve11(options.sessionsRoot??resolve11(homedir3(),".codex"),matchingActive.sessionPath):null)}}async function observedHookTurn(root,threadId,argv,now){const hookIds=argv.filter(value=>value.startsWith("--codex-hook-id="));if(hookIds.length!==1)return null;const hookId=hookIds[0]?.slice("--codex-hook-id=".length);if(!hookId||!/^[a-f0-9]{64}$/.test(hookId))return null;const originalArgv=argv.filter(value=>!value.startsWith("--codex-hook-"));const argvSha256=createHash38("sha256").update(JSON.stringify(originalArgv)).digest("hex");const path=resolve11(root,".local/codex-hook-turn/v1",`${hookId}.json`);const claimed=`${path}.${randomUUID5()}.consumed`;try{await rename5(path,claimed);const info=await lstat7(claimed);if(!info.isFile()||info.isSymbolicLink()||info.size>2048)return null;if((await realpath7(claimed)).toLowerCase()!==claimed.toLowerCase())return null;const receipt=JSON.parse(await readFile8(claimed,"utf8"));const age=now.getTime()-Number(receipt.observed_at_ms);if(receipt.schema_version!==1||receipt.thread_id!==threadId||typeof receipt.turn_id!=="string"||!receipt.turn_id||receipt.turn_id.length>256||receipt.tool_use_sha256!==hookId||receipt.argv_sha256!==argvSha256||!Number.isFinite(age)||age<-5e3||age>6e4)return null;return receipt.turn_id}catch{return null}finally{await unlink2(claimed).catch(()=>void 0)}}function transcriptPathFromEnvironment(){const value=process.env.CODEX_TRANSCRIPT_PATH?.trim();return value===void 0||value.length===0||value.length>4096?null:value}function normalizedId(value){const normalized=value?.trim();return normalized===void 0||normalized.length===0?null:normalized}var init_run_client_invocation=__esm({"src/run-client-invocation.ts"(){"use strict";init_src4()}});function activeDescendantRuns(rootRunId,candidates){return descendantRuns(rootRunId,candidates).filter(candidate=>candidate.finished===null)}function descendantRuns(rootRunId,candidates){const descendants=[];const parentIds=new Set([rootRunId]);let discovered=true;while(discovered){discovered=false;for(const candidate of candidates){if(candidate.run.parent_run_id!==null&&parentIds.has(candidate.run.parent_run_id)&&!parentIds.has(candidate.run.run_id)){parentIds.add(candidate.run.run_id);descendants.push(candidate);discovered=true}}}return descendants}var init_run_hierarchy=__esm({"src/run-hierarchy.ts"(){"use strict"}});async function recoveryContext(filesystem,composition,actorTaskId,actorRunId,targetTaskId,actorExecutionId,observe=resolveRunClientInvocation,mode="current-release"){const[actorRecord,actorRun,{task:target},cycle]=await Promise.all([actorTaskId?composition.tasks.read(actorTaskId):Promise.resolve(null),composition.runs.read(actorRunId),composition.tasks.read(targetTaskId),readReleaseCycle(filesystem)]);const actor=actorRecord?.task??null;if((mode==="post-publication-consume"||mode==="post-publication-consume-partial"?actorRun.finished?.status!=="completed"||actorRun.finalization_decision?.outcome!=="completed":actorRun.status!=="running"||actorRun.finalization_decision!==null)||actorRun.run.agent!=="agent-orchestrator"||actorRun.run.run_role!=="orchestrator"||actorRun.run.parent_run_id!==null)throw new UsageError("Recovery requires an active observed root orchestrator");if(mode!=="post-publication-consume"&&mode!=="post-publication-consume-partial"){const invocation2=await observe(filesystem,actorRun.run.client);if(!invocation2.clientThreadId||!invocation2.clientTurnId||invocation2.clientThreadId!==actorRun.run.client_thread_id||invocation2.clientTurnId!==actorRun.run.client_turn_id)throw new UsageError("Recovery Run does not match the observed client turn")}if(actor!==null){if(actor.id===target.id||actor.status!==(mode==="post-publication-consume"||mode==="post-publication-consume-partial"?"completed":"executing")||actorRun.run.task_id!==actor.id||actorRun.run.change_id!==actor.change_id||actorRun.run.execution_kind!=="delivery")throw new UsageError("Recovery maintenance Task has wrong owner or state");const actorExecution=await executionForTask(actor,composition);if(actorRun.run.execution_id!==actorExecution.id||actorExecution.id!==actorExecutionId)throw new UsageError("Maintenance Run is not attributed to its Execution")}else{const{execution:interaction}=await composition.executions.read(actorExecutionId);if(actorRun.run.task_id!==null||actorRun.run.change_id!==null||actorRun.run.execution_id!==interaction.id||actorRun.run.execution_kind!=="interaction"||actorRun.run.entrypoint!=="conversation"||interaction.kind!=="interaction"||interaction.status!=="running")throw new UsageError("Taskless recovery requires the exact active interaction Execution root")}if(target.status!=="blocked"&&!(mode==="post-publication-consume-partial"&&target.status==="executing"))throw new UsageError("Recovery target must remain blocked");const execution=await executionForTask(target,composition);const{change}=await composition.changes.read(target.change_id);const taskFirst=mode!=="current-release"&&execution.origin.type==="task"&&execution.origin.task_id===target.id&&change.source.type==="task"&&change.source.task_id===target.id&&execution.dag.nodes.length===1&&execution.dag.nodes[0]?.task_id===target.id&&execution.dag.nodes[0]?.change_id===change.id;const specOrigin=execution.origin.type==="spec"&&change.source.type==="spec"&&change.source.spec_id===execution.origin.spec_id;if(!taskFirst&&!specOrigin||!["blocked","executing"].includes(change.status)||!["blocked","running"].includes(execution.status))throw new UsageError("Recovery target is not an exact blocked delivery DAG");const spec=execution.origin.type==="spec"?(await composition.specs.read(execution.origin.spec_id)).spec:null;const effectiveTargetRelease=target.target_release??spec?.target_release??null;const history=JSON.parse(await filesystem.readText(".agents/config/release-cycle.json"));const lastAdvance=history.history?.at(-1);const actorReleaseMatches=actor!==null&&(actor.target_release===cycle?.current_release||mode!=="current-release"&&lastAdvance?.from===actor.target_release&&lastAdvance?.to===cycle?.current_release);if(spec!==null&&(spec.plan_ref===null||spec.plan_ref.execution_id!==execution.id||!["blocked","ready","active"].includes(spec.status)||effectiveTargetRelease!==spec.target_release)||effectiveTargetRelease===null||mode==="current-release"&&cycle?.current_release!==effectiveTargetRelease||mode==="current-release"&&actor!==null&&actor.target_release!==effectiveTargetRelease||mode!=="current-release"&&(actor===null||cycle?.state!=="open"||!actorReleaseMatches))throw new UsageError("Recovery ancestry or current release does not match exactly");const allRuns=await composition.runs.list();if(allRuns.some(run=>run.run.task_id===target.id&&run.status==="running"))throw new UsageError("Recovery target still has an active owner Run");if(activeDescendantRuns(actorRun.run.run_id,allRuns).some(run=>run.run.task_id===target.id))throw new UsageError("Recovery target is an active descendant of maintenance");for(const dependencyId of target.depends_on){if((await composition.tasks.read(dependencyId)).task.status!=="completed")throw new UsageError(`Recovery dependency is not completed: ${dependencyId}`)}return{actorTaskId:actor?.id??"",actorExecutionId,actorRunId,decisionScopeType:actor===null?"execution":"change",decisionScopeId:actor===null?actorExecutionId:actor.change_id,targetTaskId:target.id,targetSpecId:spec?.id??null,targetExecutionId:execution.id,targetRelease:effectiveTargetRelease,targetTaskRevision:target.revision,targetChangeId:change.id,targetChangeRevision:change.revision,targetChangeStatus:change.status,targetSpecRevision:spec?.revision??null,targetSpecStatus:spec?.status??null,targetExecutionRevision:execution.revision,targetExecutionStatus:execution.status,stateSha256:digest6(JSON.stringify({task:[target.id,target.revision,target.status,target.plan_hash],change:[change.id,change.revision,change.status],execution:[execution.id,execution.revision,execution.status,execution.plan_hash],spec:spec===null?null:[spec.id,spec.revision,spec.status,spec.plan_ref?.hash],cycle}))}}async function assertRecoveryDecision(composition,scopeType,scopeId,decisionId,payload){const decision=await composition.decisions.read(scopeType,scopeId,decisionId);if(decision.origin!=="human"||decision.confirmed_at===null||Date.parse(decision.confirmed_at)>Date.now()||decision.category!=="contract")throw new UsageError("Recovery requires a confirmed human contract Decision");let actual;try{actual=JSON.parse(decision.decision)}catch{throw new UsageError("Recovery Decision must contain the exact JSON authorization payload")}if(actual===null||typeof actual!=="object"||Array.isArray(actual))throw new UsageError("Recovery Decision payload is not an object");const values=actual;const expectedKeys=Object.keys(payload).sort();if(JSON.stringify(Object.keys(values).sort())!==JSON.stringify(expectedKeys)||expectedKeys.some(key=>values[key]!==payload[key]))throw new UsageError("Recovery Decision does not authorize this exact actor, target, revision and digest")}var init_controlled_recovery_authority=__esm({"src/controlled-recovery-authority.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_snapshot();init_lifecycle_run_attribution();init_release_cycle();init_run_client_invocation();init_run_hierarchy()}});function publishedHistoryRow(cycle,release){if(cycle.schema_version!==1||cycle.state!=="open"||!Array.isArray(cycle.history))return null;const history=cycle.history;const matches=history.map((row,index2)=>row?.from===release?index2:-1).filter(index2=>index2>=0);if(matches.length!==1)return null;const index=matches[0];if(index===void 0)return null;if(history[index]?.kind==="planned-major-retarget")return null;let current=release;const seen=new Set;for(const row of history.slice(index)){if(!row||row.from!==current||seen.has(current)||typeof row.to!=="string"||!/^\d+\.\d+$/.test(row.to))return null;const[major=NaN,minor=NaN]=current.split(".").map(Number);const[nextMajor=NaN,nextMinor=NaN]=row.to.split(".").map(Number);if(!(nextMajor>major||nextMajor===major&&nextMinor>minor))return null;if(row.kind==="planned-major-retarget"){if(nextMajor!==major+1||nextMinor!==0||typeof row.task_id!=="string"||!row.task_id.startsWith("TASK-")||typeof row.run_id!=="string"||!row.run_id.startsWith("RUN-")||typeof row.decision_id!=="string"||!row.decision_id.startsWith("DEC-HUMAN-")||typeof row.authorization_sha256!=="string"||!/^[a-f0-9]{64}$/.test(row.authorization_sha256)||typeof row.occurred_at!=="string"||!Number.isFinite(Date.parse(row.occurred_at))||!Number.isSafeInteger(row.expected_revision)||Number(row.expected_revision)<1||row.sha!==void 0||row.ci_run_id!==void 0||row.release_url!==void 0)return null}else if(row.kind!==void 0||typeof row.sha!=="string"||!/^[a-f0-9]{40}$/.test(row.sha)||!Number.isSafeInteger(row.ci_run_id)||Number(row.ci_run_id)<1||row.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${current}`)return null;seen.add(current);current=row.to}return current===cycle.current_release?history[index]??null:null}var init_post_publication_cycle=__esm({"src/post-publication-cycle.ts"(){"use strict"}});function successfulRun(run,id,sha5,path){return run.id===id&&run.head_sha===sha5&&run.conclusion==="success"&&run.status==="completed"&&run.path===path&&run.repository?.full_name==="zaip-ai/zaip-aios"}function verifiedPublicationRun(input){const{row,candidate,published,publication,publishRunId,recoveryCi}=input;const repaired=Object.keys(row).some(key=>key.startsWith("publisher_recovery_"));if(!repaired)return successfulRun(publication,publishRunId,published,".github/workflows/publish-cli.yml")&&publication.event==="release"&&publication.head_branch===`v${row.from}`;return row.publisher_recovery_sha===candidate&&candidate!==published&&recoveryCi!==void 0&&Number.isSafeInteger(row.publisher_recovery_ci_run_id)&&Number(row.publisher_recovery_ci_run_id)>0&&[".github/workflows/pre-main-candidate.yml",".github/workflows/pre-main-candidate.yml@refs/heads/main"].some(path=>successfulRun(recoveryCi,row.publisher_recovery_ci_run_id,candidate,path))&&recoveryCi.event==="push"&&recoveryCi.head_branch==="main"&&successfulRun(publication,publishRunId,candidate,".github/workflows/publish-cli.yml")&&publication.event==="workflow_dispatch"&&publication.head_branch==="main"}var init_post_publication_publisher=__esm({"src/post-publication-publisher.ts"(){"use strict"}});import{execFile as execFile8}from"node:child_process";import{createHash as createHash39}from"node:crypto";import{posix as posix5}from"node:path";import{promisify as promisify8}from"node:util";async function publishedClosureProof(filesystem,composition,task,evidenceIds,run=query,snapshot){if(evidenceIds.length===0||new Set(evidenceIds).size!==evidenceIds.length)throw new UsageError("Post-publication closure requires exact, unique Evidence IDs");const cycleSource=await filesystem.readText(cyclePath2);let cycle;try{cycle=JSON.parse(cycleSource)}catch{throw new UsageError("Post-publication release cycle is invalid")}const from=await effectiveTaskRelease(task,composition);const row=typeof from==="string"?publishedHistoryRow(cycle,from):null;if(cycle.schema_version!==1||cycle.state!=="open"||typeof cycle.current_release!=="string"||typeof from!=="string"||row===null||row.from!==from||typeof row.to!=="string"||typeof row.sha!=="string"||!/^[a-f0-9]{40}$/.test(row.sha)||!Number.isSafeInteger(row.ci_run_id)||Number(row.ci_run_id)<=0||row.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${from}`)throw new UsageError("Post-publication cycle does not have the exact published Task advance");const bundle=await readAssuranceBundle(filesystem,composition.layout,[task],evidenceIds);if(bundle.evidences.length!==evidenceIds.length)throw new UsageError("Post-publication Evidence selection is incomplete");const changeDirectory=posix5.dirname(composition.layout.activePath("change",task.change_id));const proofPaths=Array.isArray(snapshot)?snapshot.map(([path])=>path):(await Promise.all(["tests","evals","checks","evidence","observations"].map(kind=>filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat().sort();const proofContents=await Promise.all(proofPaths.map(async path=>[path,createHash39("sha256").update(await filesystem.readText(path)).digest("hex")]));const proofContentSha256=createHash39("sha256").update(JSON.stringify(proofContents)).digest("hex");const candidates=[...new Set([...bundle.validations,...bundle.evidences].map(item=>item.commit_sha))];const historicalCandidate=candidates.length===1&&typeof candidates[0]==="string"?candidates[0]:null;if(!historicalCandidate)throw new UsageError("Historical proof requires one exact candidate");const candidate=await requireFinalProductCandidate(filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,[cyclePath2],{target_task_id:task.id,target_spec_id:null,candidate_sha:historicalCandidate,published_sha:row.sha,evidence_ids:evidenceIds});const git8=args=>run("git",args,filesystem.root);let frozen;try{frozen=JSON.parse(await git8(["show",`${candidate}:${cyclePath2}`]))}catch{throw new UsageError("Validated candidate has no frozen release cycle")}if(frozen.state!=="frozen"||frozen.current_release!==from||frozen.release_task_id!==task.id)throw new UsageError("Validated candidate is not frozen for the exact release Task");const published=row.sha;const ci=Number(row.ci_run_id);const version2=`${from}.0`;let publishRunId=null;for(const path of proofPaths.filter(item=>item.includes("/artifacts/observations/"))){try{const observation=parseMarkdown(await filesystem.readText(path),evidenceObservationV1Schema).metadata;const match=/^github-actions-(\d+)-attempt-\d+\/npm-registry$/.exec(observation.environment.id??"");if(observation.task_id===task.id&&observation.change_id===task.change_id&&observation.state==="confirmed"&&observation.environment.class==="published-package"&&observation.environment.version===`@zaip-ai/cli@${version2}`&&observation.candidate_version===version2&&observation.commit_sha===candidate&&observation.correlation_ids.includes(published)&&match&&observation.correlation_ids.includes(match[1]??"")&&observation.locators.includes(`https://github.com/zaip-ai/zaip-aios/actions/runs/${match[1]}`)){publishRunId=Number(match[1]);break}}catch{}}if(publishRunId===null)throw new UsageError("Canonical published-package observation is unavailable");let npmIntegrity="";let releaseAssetDigest="";let releaseAssetsSha256="";try{const remote=await git8(["remote","get-url","origin"]);if(!/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)zaip-ai\/zaip-aios(?:\.git)?\/?$/.test(remote))throw new Error("origin identity differs");const refs=await git8(["ls-remote","origin","refs/heads/main",`refs/tags/v${from}`,`refs/tags/v${from}^{}`]);const lines2=new Map(refs.split(/\r?\n/).filter(Boolean).map(line=>{const[sha5,ref]=line.split(/\s+/);return[ref,sha5]}));if(!/^[a-f0-9]{40}$/.test(lines2.get("refs/heads/main")??"")||(lines2.get(`refs/tags/v${from}^{}`)??lines2.get(`refs/tags/v${from}`))!==published)throw new Error("remote refs differ");await git8(["merge-base","--is-ancestor",published,lines2.get("refs/heads/main")]);const release=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/releases/tags/v${from}`],filesystem.root));const workflow=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${ci}`],filesystem.root));const publication=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${publishRunId}`],filesystem.root));const recoveryCi=row.publisher_recovery_sha===candidate?JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${row.publisher_recovery_ci_run_id}`],filesystem.root)):void 0;const registry2=JSON.parse(await run("registry-metadata",[`https://registry.npmjs.org/@zaip-ai%2fcli/${version2}`],filesystem.root));const dist=registry2.dist;const assets=release.assets;const requiredNames=["local-release-receipt.json","release-manifest.json","sbom.cdx.json",`zaip-ai-cli-${version2}.tgz`].sort();if(!Array.isArray(assets))throw new Error("Release assets unavailable");const inventory3=requiredNames.map(name=>{const matches=assets.filter(item2=>item2.name===name);const item=matches[0];if(matches.length!==1||!item||!Number.isSafeInteger(item.id)||Number(item.id)<1||!Number.isSafeInteger(item.size)||Number(item.size)<1||typeof item.digest!=="string"||!/^sha256:[a-f0-9]{64}$/.test(item.digest))throw new Error("Required release asset missing or invalid");return{name,id:item.id,size:item.size,digest:item.digest}});releaseAssetsSha256=createHash39("sha256").update(JSON.stringify(inventory3)).digest("hex");const asset=assets.find(item=>item.name===`zaip-ai-cli-${version2}.tgz`);const tarball=JSON.parse(await run("registry-tarball",[`https://registry.npmjs.org/@zaip-ai/cli/-/cli-${version2}.tgz`],filesystem.root));if(release.draft!==false||typeof release.published_at!=="string"||release.target_commitish!==published||workflow.id!==ci||workflow.head_sha!==published||workflow.conclusion!=="success"||workflow.status!=="completed"||workflow.event!=="push"||workflow.head_branch!=="main"||workflow.path!==".github/workflows/pre-main-candidate.yml"||workflow.repository?.full_name!=="zaip-ai/zaip-aios"||!verifiedPublicationRun({row,candidate,published,publication,publishRunId,recoveryCi})||registry2.version!==version2||dist?.tarball!==`https://registry.npmjs.org/@zaip-ai/cli/-/cli-${version2}.tgz`||typeof dist.integrity!=="string"||!/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(dist.integrity)||!asset||typeof asset.digest!=="string"||!/^sha256:[a-f0-9]{64}$/.test(asset.digest)||!Number.isSafeInteger(asset.size)||Number(asset.size)<1||tarball.sha256!==asset.digest||tarball.integrity!==dist.integrity||tarball.size!==asset.size)throw new Error("remote publication proof differs");npmIntegrity=dist.integrity;releaseAssetDigest=asset.digest}catch{throw new UsageError("Exact remote main, tag, Release, CI, npm and publication Actions proof is unavailable or mismatched")}return{candidate_sha:candidate,published_sha:published,ci_run_id:ci,release_url:row.release_url,cycle_sha256:createHash39("sha256").update(cycleSource).digest("hex"),proof_content_sha256:proofContentSha256,...snapshot!==void 0?{proof_inventory:proofContents}:{},npm_integrity:npmIntegrity,publish_run_id:publishRunId,release_asset_digest:releaseAssetDigest,release_assets_sha256:releaseAssetsSha256,evidence_ids:[...evidenceIds]}}var exec2,cyclePath2,query;var init_post_publication_proof=__esm({"src/post-publication-proof.ts"(){"use strict";init_src();init_assurance();init_cli_arguments();init_lifecycle_assurance_v2();init_post_publication_cycle();init_post_publication_publisher();init_release_cycle();exec2=promisify8(execFile8);cyclePath2=".agents/config/release-cycle.json";query=async(command2,args,root)=>{if(command2==="registry-metadata"){const url2=args[0];if(!url2||!/^https:\/\/registry\.npmjs\.org\/(?:@zaip-ai%2[fF]cli\/\d+\.\d+\.\d+|-\/package\/@zaip-ai%2[fF]cli\/dist-tags)$/.test(url2))throw new Error("Registry metadata URL is not exact");const response=await fetch(url2,{redirect:"error",signal:AbortSignal.timeout(3e4)});if(!response.ok||!response.body||!response.headers.get("content-type")?.includes("json"))throw new Error("Registry metadata is unavailable");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.byteLength;if(size>2*1024*1024)throw new Error("Registry metadata exceeds proof limit");chunks.push(chunk)}return Buffer.concat(chunks).toString("utf8")}if(command2==="registry-tarball"){const url2=args[0];if(!url2||!/^https:\/\/registry\.npmjs\.org\/@zaip-ai\/cli\/-\/cli-\d+\.\d+\.\d+\.tgz$/.test(url2))throw new Error("Registry tarball URL is not exact");const response=await fetch(url2,{redirect:"error",signal:AbortSignal.timeout(3e4)});if(!response.ok||!response.body)throw new Error("Registry tarball is unavailable");const sha2568=createHash39("sha256");const sha512=createHash39("sha512");let size=0;for await(const chunk of response.body){size+=chunk.byteLength;if(size>16*1024*1024)throw new Error("Registry tarball exceeds proof limit");sha2568.update(chunk);sha512.update(chunk)}return JSON.stringify({sha256:`sha256:${sha2568.digest("hex")}`,integrity:`sha512-${sha512.digest("base64")}`,size})}return(await exec2(command2,args,{cwd:root,encoding:"utf8",windowsHide:true,timeout:3e4,maxBuffer:4*1024*1024})).stdout.trim()}}});import{createHash as createHash40}from"node:crypto";function authorizationPayload(receipt){return{...receipt.maintenance_direct_authorization_sha256===void 0?{}:{maintenance_direct_authorization_sha256:receipt.maintenance_direct_authorization_sha256},actor_task_id:receipt.actor_task_id,actor_execution_id:receipt.actor_execution_id,actor_run_id:receipt.actor_run_id,client_thread_id:receipt.client_thread_id,client_turn_id:receipt.client_turn_id,human_authorization_sha256:receipt.human_authorization_sha256,target_task_id:receipt.target_task_id,target_spec_id:receipt.target_spec_id,target_execution_id:receipt.target_execution_id,target_release:receipt.target_release,expected_task_revision:receipt.expected_task_revision,target_change_id:receipt.target_change_id,expected_change_revision:receipt.expected_change_revision,expected_change_status:receipt.expected_change_status,expected_spec_revision:receipt.expected_spec_revision,...receipt.expected_spec_status===void 0?{}:{expected_spec_status:receipt.expected_spec_status},expected_execution_revision:receipt.expected_execution_revision,...receipt.expected_execution_status===void 0?{}:{expected_execution_status:receipt.expected_execution_status},state_sha256:receipt.state_sha256,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,cycle_sha256:receipt.proof.cycle_sha256,proof_content_sha256:receipt.proof.proof_content_sha256,...receipt.proof.proof_inventory!==void 0?{proof_inventory_sha256:sha(JSON.stringify(receipt.proof.proof_inventory))}:{},npm_integrity:receipt.proof.npm_integrity,publish_run_id:receipt.proof.publish_run_id,release_asset_digest:receipt.proof.release_asset_digest,release_assets_sha256:receipt.proof.release_assets_sha256,evidence_selection_sha256:sha(JSON.stringify([...receipt.proof.evidence_ids].sort()))}}function requiredValue(value,name){if(!value)throw new UsageError(`Post-publication ${name} is required`);return value}function expectedRevision(parsed){const value=Number(parsed.options["expected-revision"]);if(!Number.isSafeInteger(value)||value<1)throw new UsageError("Post-publication expected revision must be positive");return value}function exactId(parsed){const id=parsed.positionals[2];if(!id?.startsWith("TASK-"))throw new UsageError("Exact blocked Task ID is required");return id}async function preparePostPublicationRecovery(parsed,filesystem,composition,publicationQuery){requireOptions(parsed.options,["actor-task","actor-execution","run","expected-revision","evidence"]);const taskId=exactId(parsed);const actorTaskId=requiredValue(parsed.options["actor-task"],"actor-task");const actorExecutionId=requiredValue(parsed.options["actor-execution"],"actor-execution");const actorRunId=requiredValue(parsed.options.run,"run");const context2=await recoveryContext(filesystem,composition,actorTaskId,actorRunId,taskId,actorExecutionId,resolveRunClientInvocation,"post-publication");if(context2.targetTaskRevision!==expectedRevision(parsed))throw new UsageError("Blocked Task revision changed; preview again");const actor=await composition.runs.read(actorRunId);const observed=await resolveRunClientInvocation(filesystem,actor.run.client);const direct=actor.run.direct_execution_authorization;const directObserved=typeof direct==="string"&&direct.trim().length>0&&observed.clientThreadId===actor.run.client_thread_id&&observed.clientTurnId===actor.run.client_turn_id&&!!observed.userMessage&&observed.observedModel===actor.run.model&&observed.observedReasoningEffort===actor.run.reasoning_effort;if(!(actor.run.intake?.classification_source==="explicit"&&actor.run.intake.intent==="new_work")&&!directObserved)throw new UsageError("Post-publication repair requires its explicit human-authorized maintenance root");if(!observed.userMessage||!observed.clientThreadId||!observed.clientTurnId)throw new UsageError("Observed human repair request and client turn are required");const target=(await composition.tasks.read(taskId)).task;if(context2.targetSpecId!==null&&!["blocked","active"].includes(context2.targetSpecStatus??""))throw new UsageError("Post-publication receipt requires a blocked or active historical SPEC");const evidenceIds=csvOption(parsed.options.evidence);const proof=await publishedClosureProof(filesystem,composition,target,evidenceIds,publicationQuery,context2.targetSpecId===null?true:void 0);const base={schema_version:3,...directObserved?{maintenance_direct_authorization_sha256:sha(direct)}:{},kind:"post_publication_closure",actor_task_id:actorTaskId,actor_execution_id:actorExecutionId,actor_run_id:actorRunId,client_thread_id:observed.clientThreadId,client_turn_id:observed.clientTurnId,human_authorization_sha256:sha(observed.userMessage),target_task_id:context2.targetTaskId,target_spec_id:context2.targetSpecId,target_execution_id:context2.targetExecutionId,target_release:context2.targetRelease,expected_task_revision:context2.targetTaskRevision,target_change_id:context2.targetChangeId,expected_change_revision:context2.targetChangeRevision,expected_change_status:context2.targetChangeStatus,expected_spec_revision:context2.targetSpecRevision,expected_spec_status:context2.targetSpecStatus,expected_execution_revision:context2.targetExecutionRevision,expected_execution_status:context2.targetExecutionStatus,state_sha256:context2.stateSha256,proof};const payload=authorizationPayload({...base,human_decision_id:""});if(!parsed.flags.has("apply"))return{receipt_path:null,authorization_payload:payload,applied:false,authorization_status:"pending-human-decision"};const decisionId=requiredValue(parsed.options.decision,"confirmed human Decision");await assertRecoveryDecision(composition,"change",requiredValue(actor.run.change_id,"maintenance Change"),decisionId,payload);const receipt={...base,human_decision_id:decisionId,issuance_decision_id:issuanceId({...base,human_decision_id:decisionId})};const path=receiptPath(receipt);const source=`${JSON.stringify(receipt)}
3582
- `;let reused=false;if(await filesystem.exists(path)){if(await filesystem.readText(path)!==source)throw new UsageError("Post-publication receipt path contains different bytes");reused=true;try{const issued=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),receipt.issuance_decision_id);if(issued.origin!=="agent"||issued.decision!==issuancePayload(receipt))throw new UsageError("Post-publication receipt conflicts with its canonical issuance Decision");return{receipt_path:path,authorization_payload:payload,applied:true,reused:true}}catch(error51){if(!(error51 instanceof Error)||!("code"in error51)||error51.code!=="ENOENT")throw error51}}if(!reused)await filesystem.writeTextAtomicExclusive(path,source);await composition.decisions.record({id:receipt.issuance_decision_id,shortName:"post-publication-closure",title:"Emitir recibo de fechamento pos-publicacao",scopeType:"change",scopeId:requiredValue(actor.run.change_id,"maintenance Change"),origin:"agent",category:"contract",context:`Observed maintenance Run ${actorRunId} and human request hash ${receipt.human_authorization_sha256}`,decision:issuancePayload(receipt),reason:"Narrow receipt for the exact published release Task after maintenance finalization",alternatives:[],consequences:["Resume only metadata closure with a new finalizer"],reversible:true,rollback:"Leave old Task blocked and preserve publication; receipt grants no product writer",confidence:1,confirmed:false,timeZone:composition.layout.project.timezone});return{receipt_path:path,authorization_payload:payload,applied:true,reused}}async function readPostPublicationReceipt(filesystem,path){if(!/^\.local\/recovery\/post-publication\/[a-f0-9]{64}\.json$/.test(path))throw new UsageError("Post-publication receipt must use its canonical local path");let receipt;try{receipt=JSON.parse(await filesystem.readText(path))}catch{throw new UsageError("Post-publication receipt is unreadable")}if(receipt?.schema_version!==1&&receipt?.schema_version!==2&&receipt?.schema_version!==3||receipt.kind!=="post_publication_closure"||receiptPath(receipt)!==path||!receipt.actor_task_id?.startsWith("TASK-")||!receipt.actor_execution_id?.startsWith("EXEC-")||!receipt.actor_run_id?.startsWith("RUN-")||!receipt.issuance_decision_id?.startsWith("DEC-AI-POSTPUB-")||!receipt.human_decision_id?.startsWith("DEC-HUMAN-")||receipt.issuance_decision_id!==issuanceId((({issuance_decision_id:_ignored,...base})=>base)(receipt))||!receipt.target_task_id?.startsWith("TASK-")||!receipt.target_change_id?.startsWith("CHG-")||!Number.isSafeInteger(receipt.expected_change_revision)||receipt.expected_change_revision<1||!["blocked","executing"].includes(receipt.expected_change_status)||!(receipt.target_spec_id?.startsWith("SPEC-")?Number.isSafeInteger(receipt.expected_spec_revision)&&Number(receipt.expected_spec_revision)>0:(receipt.schema_version===2||receipt.schema_version===3)&&receipt.target_spec_id===null&&receipt.expected_spec_revision===null)||receipt.schema_version===3&&(!(["blocked","active"].includes(receipt.expected_spec_status??"")||receipt.target_spec_id===null&&receipt.expected_spec_status===null)||!["blocked","running"].includes(receipt.expected_execution_status??""))||receipt.maintenance_direct_authorization_sha256!==void 0&&(receipt.schema_version!==2&&receipt.schema_version!==3||!/^[a-f0-9]{64}$/.test(receipt.maintenance_direct_authorization_sha256))||!receipt.target_execution_id?.startsWith("EXEC-")||!/^[a-f0-9]{64}$/.test(receipt.human_authorization_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.state_sha256??"")||!/^[a-f0-9]{40}$/.test(receipt.proof?.candidate_sha??"")||!/^[a-f0-9]{40}$/.test(receipt.proof?.published_sha??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.cycle_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.proof_content_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.release_assets_sha256??"")||!/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(receipt.proof?.npm_integrity??"")||!Number.isSafeInteger(receipt.proof?.publish_run_id)||!/^sha256:[a-f0-9]{64}$/.test(receipt.proof?.release_asset_digest??""))throw new UsageError("Post-publication receipt identity is invalid");return receipt}var sha,issuanceId,receiptPath,issuancePayload;var init_post_publication_receipt=__esm({"src/post-publication-receipt.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_authority();init_post_publication_proof();init_run_client_invocation();sha=value=>createHash40("sha256").update(value).digest("hex");issuanceId=receipt=>`DEC-AI-POSTPUB-${sha(JSON.stringify(receipt)).slice(0,24).toUpperCase()}`;receiptPath=receipt=>`.local/recovery/post-publication/${sha(JSON.stringify(receipt))}.json`;issuancePayload=receipt=>JSON.stringify({kind:receipt.kind,actor_run_id:receipt.actor_run_id,target_task_id:receipt.target_task_id,target_spec_id:receipt.target_spec_id,target_execution_id:receipt.target_execution_id,receipt_sha256:sha(JSON.stringify(receipt)),human_authorization_sha256:receipt.human_authorization_sha256})}});async function validatePostPublicationSequence(filesystem,composition,receipt,actor,sequence,clientThreadId,clientTurnId,sameTurn){const handoffHash2=sha(JSON.stringify(receipt));if(sequence!==null&&(sequence.schema_version!==(sameTurn?7:8)||sequence.maintenance_run_id!==receipt.actor_run_id||sequence.maintenance_execution_id!==""&&sequence.maintenance_execution_id!==receipt.actor_execution_id))throw new UsageError("Post-publication sequence has another turn or maintenance authority");const steps=sequence?.steps??[];const currentStep=steps.find(step=>step.target_task_id===receipt.target_task_id);if(currentStep!==void 0&&(currentStep.execution_id!==receipt.target_execution_id||!claimOriginMatches(currentStep.origin,receipt.target_spec_id,receipt.target_task_id)||currentStep.authorization_sha256!==handoffHash2))throw new UsageError("Post-publication step has another target or authority");const precedingStep=currentStep===void 0?steps.at(-1):steps[steps.indexOf(currentStep)-1];for(const step of steps.filter(item=>item!==currentStep)){const priorReceipt=await readPostPublicationReceipt(filesystem,`.local/recovery/post-publication/${step.authorization_sha256}.json`);if(sha(JSON.stringify(priorReceipt))!==step.authorization_sha256||priorReceipt.actor_run_id!==receipt.actor_run_id||priorReceipt.actor_execution_id!==receipt.actor_execution_id||priorReceipt.client_thread_id!==receipt.client_thread_id||priorReceipt.human_authorization_sha256!==receipt.human_authorization_sha256||priorReceipt.target_task_id!==step.target_task_id||priorReceipt.target_execution_id!==step.execution_id||!claimOriginMatches(step.origin,priorReceipt.target_spec_id,step.target_task_id))throw new UsageError("Earlier post-publication receipt has another authority or target");await assertRecoveryDecision(composition,"change",requiredValue(actor.run.change_id,"maintenance Change"),priorReceipt.human_decision_id,authorizationPayload(priorReceipt));const priorIssuance=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),priorReceipt.issuance_decision_id);if(priorIssuance.origin!=="agent"||priorIssuance.decision!==issuancePayload(priorReceipt))throw new UsageError("Earlier post-publication receipt lacks canonical issuance")}const predecessorRunId=precedingStep?.successor_run_id??receipt.actor_run_id;const predecessor=predecessorRunId===receipt.actor_run_id?actor:await composition.runs.read(predecessorRunId);if(precedingStep!==void 0&&(predecessor.finished?.status!=="completed"||predecessor.finalization_decision?.outcome!=="completed"||(precedingStep.origin.type==="spec"?predecessor.run.spec_id!==precedingStep.origin.spec_id:predecessor.run.task_id!==precedingStep.target_task_id)||predecessor.run.execution_id!==precedingStep.execution_id||(await composition.tasks.read(precedingStep.target_task_id)).task.status!=="completed"))throw new UsageError("Previous post-publication successor and Gui must finish first");const allRuns=await composition.runs.list();const roots2=allRuns.filter(run=>run.run.parent_run_id===null&&run.run.client_thread_id===clientThreadId&&run.run.client_turn_id===clientTurnId);const expectedRootIds=new Set([...sameTurn?[receipt.actor_run_id]:[],...steps.map(step=>step.successor_run_id)]);if(sameTurn&&!roots2.some(run=>run.run.run_id===actor.run.run_id)||roots2.some(run=>!expectedRootIds.has(run.run.run_id)))throw new UsageError("Observed turn already has another root owner");for(const[index,step]of steps.entries()){const root=roots2.find(run=>run.run.run_id===step.successor_run_id);if(root===void 0){if(index!==steps.length-1||currentStep!==step)throw new UsageError("Post-publication sequence has an unfinished earlier claim");continue}if(root.run.continuation_of_run_id!==step.predecessor_run_id||root.run.execution_id!==step.execution_id||root.run.spec_id!==(step.origin.type==="spec"?step.origin.spec_id:null)||step.origin.type==="task"&&root.run.task_id!==step.target_task_id||(root.run.same_turn_handoff===void 0?index!==0||sameTurn||!root.run.intake?.reason_codes.includes(`post-publication-${step.authorization_sha256.slice(0,16)}`):index===0&&!sameTurn||root.run.same_turn_handoff.authorization_sha256!==step.authorization_sha256||root.run.same_turn_handoff.predecessor_run_id!==step.predecessor_run_id))throw new UsageError("Post-publication sequence root differs from its claim")}const successor=currentStep===void 0?null:roots2.find(run=>run.run.run_id===currentStep.successor_run_id)??null;if(currentStep===void 0&&steps.some(step=>roots2.find(run=>run.run.run_id===step.successor_run_id)?.status==="running"))throw new UsageError("Previous post-publication root is still active");return{handoffHash:handoffHash2,currentStep,precedingStep,predecessorRunId,successor,allRuns}}function claimOriginMatches(origin,spec,task){return spec===null?origin.type==="task"&&origin.task_id===task:origin.type==="spec"&&origin.spec_id===spec}var init_post_publication_recovery_sequence=__esm({"src/post-publication-recovery-sequence.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_authority();init_post_publication_receipt()}});import{posix as posix6}from"node:path";async function assertHistoricalProofSnapshot(receipt,composition,successor){const directory2=posix6.dirname(composition.layout.activePath("change",receipt.target_change_id));const paths2=(await Promise.all(["tests","evals","checks","evidence","observations"].map(kind=>composition.filesystem.listFiles(`${directory2}/artifacts/${kind}`)))).flat().sort();const inventory3=receipt.proof.proof_inventory;if(inventory3!==void 0&&(!Array.isArray(inventory3)||inventory3.some(entry2=>!Array.isArray(entry2)||entry2.length!==2)))throw new UsageError("Task-first historical proof inventory is malformed");const originalPaths=inventory3?.map(([path])=>path)??paths2;if(inventory3!==void 0&&(!Array.isArray(inventory3)||new Set(originalPaths).size!==originalPaths.length||JSON.stringify([...originalPaths].sort())!==JSON.stringify(originalPaths)||inventory3.some(([path,hash6])=>typeof path!=="string"||typeof hash6!=="string"||!/^[a-f0-9]{64}$/.test(hash6)||!path.startsWith(`${directory2}/artifacts/`)||posix6.normalize(path)!==path||!paths2.includes(path))||sha(JSON.stringify(inventory3))!==receipt.proof.proof_content_sha256))throw new UsageError("Task-first historical proof inventory changed or lost original paths");const contents=await Promise.all(originalPaths.map(async path=>[path,sha(await composition.filesystem.readText(path))]));if(sha(JSON.stringify(contents))!==receipt.proof.proof_content_sha256)throw new UsageError("Task-first historical proof bytes changed after receipt issuance");for(const path of paths2.filter(path2=>!originalPaths.includes(path2))){if(successor===null)throw new UsageError("Historical proof additions require the exact recovery root");let artifact;try{const source=await composition.filesystem.readText(path);artifact=path.includes("/artifacts/evidence/")?parseMarkdown(source,evidenceArtifactV2Schema).metadata:parseMarkdown(source,validationArtifactV2Schema).metadata}catch{throw new UsageError("Historical proof addition is not a typed recovery validation")}if(path.includes("/artifacts/observations/")||posix6.basename(path)!==`${artifact.id}.md`||artifact.run_id!==successor.run.run_id||artifact.task_id!==receipt.target_task_id||artifact.change_id!==receipt.target_change_id||artifact.execution_id!==receipt.target_execution_id||artifact.commit_sha!==receipt.proof.candidate_sha)throw new UsageError("Historical proof addition differs from the recovery root or original candidate")}}var init_post_publication_snapshot=__esm({"src/post-publication-snapshot.ts"(){"use strict";init_src();init_assurance();init_cli_arguments();init_post_publication_receipt()}});async function resumePostPublicationClosure(parsed,filesystem,composition,lifecycle,publicationQuery){requireOptions(parsed.options,["receipt"]);const receipt=await readPostPublicationReceipt(filesystem,requiredValue(parsed.options.receipt,"receipt"));if(exactId(parsed)!==receipt.target_task_id)throw new UsageError("Post-publication receipt targets another Task");const actor=await composition.runs.read(receipt.actor_run_id);const invocation2=await resolveRunClientInvocation(filesystem,actor.run.client);if(!invocation2.clientThreadId||!invocation2.clientTurnId||invocation2.clientThreadId!==receipt.client_thread_id)throw new UsageError("Post-publication continuation needs its observed client thread and turn");const sameTurn=invocation2.clientTurnId===receipt.client_turn_id;if(!sameTurn&&(!invocation2.observedModel||!invocation2.observedReasoningEffort))throw new UsageError("New post-publication turn requires observed model and reasoning effort");if(sameTurn&&(!invocation2.userMessage||sha(invocation2.userMessage)!==receipt.human_authorization_sha256))throw new UsageError("Same-turn human authorization differs from the receipt");const sequence=await composition.executions.readPostPublicationSequence(invocation2.clientTurnId);if(actor.finished?.status!=="completed"||actor.finalization_decision?.outcome!=="completed"||actor.run.execution_id!==receipt.actor_execution_id||actor.run.task_id!==receipt.actor_task_id||actor.run.client_thread_id!==receipt.client_thread_id||actor.run.client_turn_id!==receipt.client_turn_id||(await composition.tasks.read(receipt.actor_task_id)).task.status!=="completed")throw new UsageError("Maintenance Task and Gui must finish before the historical delivery resumes");if(receipt.maintenance_direct_authorization_sha256!==void 0&&sha(actor.run.direct_execution_authorization??"")!==receipt.maintenance_direct_authorization_sha256)throw new UsageError("Maintenance direct authorization differs from its issued receipt");const issuance=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),receipt.issuance_decision_id);const decisionScope=requiredValue(actor.run.change_id,"maintenance Change");await assertRecoveryDecision(composition,"change",decisionScope,receipt.human_decision_id,authorizationPayload(receipt));const humanDecision=await composition.decisions.read("change",decisionScope,receipt.human_decision_id);if(issuance.origin!=="agent"||issuance.category!=="contract"||issuance.decision!==issuancePayload(receipt)||!issuance.created_at||!humanDecision.confirmed_at||Date.parse(humanDecision.confirmed_at)>Date.parse(issuance.created_at)||Date.parse(issuance.created_at)>Date.parse(actor.finished.occurred_at))throw new UsageError("Canonical receipt issuance was not recorded before maintenance finalization");if(sameTurn&&(invocation2.observedModel!==actor.run.model||invocation2.observedReasoningEffort!==actor.run.reasoning_effort))throw new UsageError("Same-turn handoff model or effort differs from its observed root");const{handoffHash:handoffHash2,currentStep,precedingStep,predecessorRunId,successor,allRuns}=await validatePostPublicationSequence(filesystem,composition,receipt,actor,sequence,invocation2.clientThreadId,invocation2.clientTurnId,sameTurn);const target=(await composition.tasks.read(receipt.target_task_id)).task;if(allRuns.some(run2=>run2.status==="running"&&run2.run.task_id===receipt.target_task_id&&run2.run.run_id!==successor?.run.run_id))throw new UsageError("Post-publication target has another active root owner");if(receipt.proof.proof_inventory!==void 0)await assertHistoricalProofSnapshot(receipt,composition,successor);const proof=await publishedClosureProof(filesystem,composition,target,receipt.proof.evidence_ids,publicationQuery,receipt.proof.proof_inventory);if(JSON.stringify(proof)!==JSON.stringify(receipt.proof))throw new UsageError("Post-publication candidate, publication, Evidence or cycle changed");if(target.status==="executing"){if(successor!==null){if(successor.status!=="running")throw new UsageError("Executing target has no exact active closure owner");const change=(await composition.changes.read(receipt.target_change_id)).change;const execution2=(await composition.executions.read(receipt.target_execution_id)).execution;const expectedExecutionStatus2=receipt.schema_version===3?receipt.expected_execution_status:"blocked";if(target.revision!==receipt.expected_task_revision+1||change.status!=="executing"||change.revision!==receipt.expected_change_revision+(receipt.expected_change_status==="blocked"?1:0)||execution2.status!=="running"||execution2.revision!==receipt.expected_execution_revision+(expectedExecutionStatus2==="blocked"?1:0))throw new UsageError("Active post-publication owner has changed target revisions");return{run:successor.run,receipt_path:parsed.options.receipt,reused:true}}if(receipt.target_spec_id!==null||currentStep===void 0)throw new UsageError("Executing target has no exact pending Task-first claim")}if(target.status!=="blocked"&&target.status!=="executing")throw new UsageError("Post-publication target is no longer blocked");const context2=await recoveryContext(filesystem,composition,receipt.actor_task_id,receipt.actor_run_id,receipt.target_task_id,receipt.actor_execution_id,resolveRunClientInvocation,target.status==="executing"?"post-publication-consume-partial":"post-publication-consume");const executionBefore=(await composition.executions.read(receipt.target_execution_id)).execution;const specBefore=receipt.target_spec_id===null?null:(await composition.specs.read(receipt.target_spec_id)).spec;const pristine=context2.stateSha256===receipt.state_sha256&&context2.targetSpecRevision===receipt.expected_spec_revision&&context2.targetExecutionRevision===receipt.expected_execution_revision&&(receipt.schema_version===3?executionBefore.status===receipt.expected_execution_status&&(specBefore?.status??null)===receipt.expected_spec_status:executionBefore.status==="blocked"&&(specBefore===null||specBefore.status==="blocked"));const expectedExecutionStatus=receipt.schema_version===3?receipt.expected_execution_status:"blocked";const expectedSpecStatus=receipt.schema_version===3?receipt.expected_spec_status:specBefore===null?null:"blocked";const changeBefore=(await composition.changes.read(receipt.target_change_id)).change;const partial2=currentStep!==void 0&&context2.targetTaskRevision===receipt.expected_task_revision+(target.status==="executing"?1:0)&&context2.targetChangeRevision===receipt.expected_change_revision+(receipt.expected_change_status==="blocked"&&changeBefore.status==="executing"?1:0)&&(changeBefore.status===receipt.expected_change_status||changeBefore.status==="executing")&&(specBefore===null?context2.targetSpecRevision===null&&receipt.expected_spec_revision===null:context2.targetSpecRevision===Number(receipt.expected_spec_revision)+(expectedSpecStatus==="blocked"&&specBefore.status==="active"?1:0))&&context2.targetExecutionRevision===receipt.expected_execution_revision+(expectedExecutionStatus==="blocked"&&executionBefore.status==="running"?1:0)&&(specBefore===null||specBefore.status===expectedSpecStatus||specBefore.status==="active")&&(executionBefore.status===expectedExecutionStatus||executionBefore.status==="running")&&(target.status!=="executing"||receipt.target_spec_id===null&&changeBefore.status==="executing"&&executionBefore.status==="running");if(!pristine&&!partial2||context2.targetChangeId!==receipt.target_change_id||!partial2&&context2.targetChangeRevision!==receipt.expected_change_revision||!partial2&&context2.targetChangeStatus!==receipt.expected_change_status||!partial2&&context2.targetTaskRevision!==receipt.expected_task_revision||context2.targetSpecId!==receipt.target_spec_id||context2.targetExecutionId!==receipt.target_execution_id)throw new UsageError("Post-publication target revisions or state changed");if(successor!==null){if(successor.status!=="running")throw new UsageError("Post-publication successor is terminal before Task resume");const resumed2=await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256});return{run:successor.run,task:resumed2.task,receipt_path:parsed.options.receipt,reused:true,recovered_pending:true}}const runId=createId("RUN","post-publication-closure",{timeZone:composition.layout.project.timezone});const claimed=await composition.executions.claimPostPublicationSequence({clientTurnId:invocation2.clientTurnId,sameTurn,maintenanceRunId:receipt.actor_run_id,maintenanceExecutionId:receipt.actor_execution_id,executionId:receipt.target_execution_id,specId:receipt.target_spec_id,targetTaskId:receipt.target_task_id,predecessorRunId,proposedSuccessorRunId:runId,authorizationSha256:handoffHash2});let execution=(await composition.executions.read(receipt.target_execution_id)).execution;if(receipt.target_spec_id!==null&&execution.status==="blocked")execution=await composition.executions.transition(execution.id,"running");const spec=receipt.target_spec_id===null?null:(await composition.specs.read(receipt.target_spec_id)).spec;if(receipt.target_spec_id!==null&&spec?.status==="blocked")await composition.specs.transition(spec.id,"active");const taskFirstResumed=receipt.target_spec_id===null&&target.status==="blocked"?await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256}):null;if(receipt.target_spec_id===null)execution=(await composition.executions.read(receipt.target_execution_id)).execution;const start={id:claimed,shortName:"post-publication-closure",phase:"execution",runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:true,executionKind:"delivery",executionEligibility:[],entrypoint:receipt.target_spec_id===null?"task":"spec",workType:"rework",client:actor.run.client,agent:actor.run.agent,...actor.run.agent_name===void 0?{}:{agentName:actor.run.agent_name},provider:actor.run.provider,model:sameTurn?actor.run.model:requiredValue(invocation2.observedModel,"observed model"),reasoningEffort:sameTurn?actor.run.reasoning_effort??null:requiredValue(invocation2.observedReasoningEffort,"observed effort"),clientThreadId:invocation2.clientThreadId,clientTurnId:invocation2.clientTurnId,conversationId:actor.run.conversation_id,executionId:receipt.target_execution_id,specId:receipt.target_spec_id,prdId:null,taskId:receipt.target_spec_id===null?receipt.target_task_id:null,changeId:receipt.target_spec_id===null?receipt.target_change_id:null,parentRunId:null,continuationOfRunId:predecessorRunId,...!sameTurn&&precedingStep===void 0?{intake:{intent:"continue",classification_source:"explicit",confidence:1,reason_codes:[`post-publication-${handoffHash2.slice(0,16)}`]}}:{},...sameTurn||precedingStep!==void 0?{sameTurnHandoff:{kind:"post_publication_closure",predecessor_run_id:predecessorRunId,target_spec_id:receipt.target_spec_id,target_task_id:receipt.target_task_id,authorization_sha256:handoffHash2}}:{},...actor.run.developer_identity===void 0?{}:{developerIdentity:actor.run.developer_identity}};await validateRunV2Attribution(start,composition);const run=(await composition.runs.start(start)).started;const resumed=taskFirstResumed??(receipt.target_spec_id===null?{task:target}:await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256}));return{run,task:resumed.task,execution,receipt_path:parsed.options.receipt,reused:false}}var init_post_publication_recovery=__esm({"src/post-publication-recovery.ts"(){"use strict";init_src();init_attribution_v2();init_cli_arguments();init_controlled_recovery_authority();init_post_publication_proof();init_post_publication_receipt();init_post_publication_recovery_sequence();init_post_publication_snapshot();init_run_client_invocation();init_post_publication_receipt()}});import{createHash as createHash41}from"node:crypto";function required2(value,name){if(!value)throw new UsageError(`Post-publication relay requires ${name}`);return value}function closureStateHash(task,change,execution,spec,cycle){return sha2(JSON.stringify({task:[task.id,task.revision,task.status,task.plan_hash],change:[change.id,change.revision,change.status],execution:[execution.id,execution.revision,execution.status,execution.plan_hash],spec:[spec.id,spec.revision,spec.status,spec.plan_ref?.hash??null],cycle}))}async function assertRelayActor(composition,actorRunId,actorTaskId,actorExecutionId){const actor=await composition.runs.read(actorRunId);const{task}=await composition.tasks.read(actorTaskId);const{execution}=await composition.executions.read(actorExecutionId);const macro=actor.run.parent_run_id?await composition.runs.read(actor.run.parent_run_id):null;if(actor.status!=="running"||actor.run.agent!=="agent-orchestrator"||actor.run.run_role!=="subagent"||actor.run.run_purpose!=="orchestration"||actor.run.task_id!==task.id||actor.run.change_id!==task.change_id||actor.run.execution_id!==execution.id||task.status!=="executing"||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)||execution.origin.type!=="spec"||actor.run.spec_id!==execution.origin.spec_id||macro?.status!=="running"||macro.run.agent!=="agent-orchestrator"||macro.run.run_role!=="orchestrator"||macro.run.entrypoint!=="spec"||macro.run.parent_run_id!==null||macro.run.task_id!==null||macro.run.spec_id!==actor.run.spec_id||macro.run.execution_id!==actor.run.execution_id||macro.run.conversation_id!==actor.run.conversation_id||!actor.run.client_thread_id||!actor.run.client_turn_id)throw new UsageError("Relay requires the exact active delegated Task orchestrator and macro");return actor}async function recordRelayDecision(composition,id,scopeId,payload){const decision=JSON.stringify(payload);const existing=await composition.decisions.read("change",scopeId,id).catch(()=>null);if(existing!==null){if(existing.origin!=="agent"||existing.category!=="contract"||existing.decision!==decision)throw new UsageError("Post-publication relay journal conflicts with its canonical Decision");return}await composition.decisions.record({id,shortName:"post-publication-relay",title:"Vincular fechamento historico pos-publicacao",scopeType:"change",scopeId,origin:"agent",category:"contract",context:`Exact post-publication relay for ${payload.target_task_id}`,decision,reason:"Preserve published candidate and historical Evidence under a new observed Run",alternatives:[],consequences:["Records-only closure; no new product publication"],reversible:true,rollback:"Leave the historical Task blocked or executing without rewriting its old Runs",confidence:1,confirmed:false,timeZone:composition.layout.project.timezone})}async function readRelayIntent(composition,actor,targetTaskId,intentId){const changeId=actor.run.change_id;if(!changeId)return null;const record3=await composition.decisions.read("change",changeId,intentId).catch(()=>null);if(record3===null)return null;let value;try{value=JSON.parse(record3.decision)}catch{throw new UsageError("Post-publication relay intent is invalid")}const legacy2=intentId===relayIntentId(actor.run.run_id,targetTaskId);if(!legacy2&&intentId!==relayIntentId(actor.run.run_id,targetTaskId,value.current_state_sha256)||record3.origin!=="agent"||record3.category!=="contract"||value.schema_version!==1||value.kind!=="post_publication_relay_intent"||value.actor_run_id!==actor.run.run_id||value.actor_client_thread_id!==void 0&&(value.actor_client_thread_id!==actor.run.client_thread_id||value.actor_client_turn_id!==actor.run.client_turn_id)||value.actor_client_thread_id===void 0&&value.actor_client_turn_id!==void 0||value.actor_task_id!==actor.run.task_id||value.actor_change_id!==changeId||value.actor_execution_id!==actor.run.execution_id||!Number.isSafeInteger(value.actor_task_revision)||!/^[a-f0-9]{64}$/.test(value.actor_plan_hash)||!/^[a-f0-9]{64}$/.test(value.actor_objective_sha256)||value.authorization_id!==relayAuthorizationId(actor.run.run_id,targetTaskId,legacy2?void 0:value.current_state_sha256)||value.macro_run_id!==actor.run.parent_run_id||value.target_task_id!==targetTaskId||!/^[a-f0-9]{64}$/.test(value.receipt_sha256)||!/^[a-f0-9]{40}$/.test(value.candidate_sha)||!/^[a-f0-9]{40}$/.test(value.published_sha)||!Number.isSafeInteger(value.expected_task_revision)||!Number.isSafeInteger(value.expected_change_revision)||!Number.isSafeInteger(value.expected_execution_revision)||!Number.isSafeInteger(value.expected_spec_revision)||value.retry_predecessor_run_id!==void 0&&(!value.retry_predecessor_run_id.startsWith("RUN-")||!Number.isSafeInteger(value.expected_task_attempt_count)||(value.expected_task_attempt_count??0)<1)||value.retry_predecessor_run_id===void 0&&value.expected_task_attempt_count!==void 0||!/^[a-f0-9]{64}$/.test(value.receipt_state_sha256)||!/^[a-f0-9]{64}$/.test(value.current_state_sha256))throw new UsageError("Post-publication relay intent does not match its actor and target");return value}var sha2,relayIntentId,relayBindingId,relayCaptureId,relayAuthorizationId;var init_post_publication_relay_core=__esm({"src/post-publication-relay-core.ts"(){"use strict";init_cli_arguments();sha2=value=>createHash41("sha256").update(value).digest("hex");relayIntentId=(actorRunId,targetTaskId,stateSha256)=>`DEC-AI-POSTPUB-RELAY-${sha2(JSON.stringify(stateSha256===void 0?[actorRunId,targetTaskId]:[actorRunId,targetTaskId,stateSha256])).slice(0,24).toUpperCase()}`;relayBindingId=targetRunId=>`DEC-AI-POSTPUB-BIND-${sha2(targetRunId).slice(0,24).toUpperCase()}`;relayCaptureId=(actorRunId,agentId2,turnId)=>`DEC-AI-POSTPUB-CAPTURE-${sha2(JSON.stringify([actorRunId,agentId2,turnId])).slice(0,24).toUpperCase()}`;relayAuthorizationId=(actorRunId,targetTaskId,stateSha256)=>`DEC-AI-POSTPUB-AUTH-${sha2(JSON.stringify(stateSha256===void 0?[actorRunId,targetTaskId]:[actorRunId,targetTaskId,stateSha256])).slice(0,24).toUpperCase()}`}});async function authorizationPayloadForIntent(composition,intent,userMessageSha256){const[macro,actorTask]=await Promise.all([composition.runs.read(intent.macro_run_id),composition.tasks.read(intent.actor_task_id).then(({task})=>task)]);if(actorTask.revision!==intent.actor_task_revision||actorTask.plan_hash!==intent.actor_plan_hash||sha2(actorTask.objective)!==intent.actor_objective_sha256||macro.status!=="running"||macro.run.parent_run_id!==null||macro.run.entrypoint!=="spec"||!macro.run.client_thread_id||!macro.run.client_turn_id)throw new UsageError("Macro or delegated Task contract changed before authorization");return{schema_version:1,kind:"post_publication_relay_authorization",macro_run_id:macro.run.run_id,macro_client_thread_id:macro.run.client_thread_id,macro_client_turn_id:macro.run.client_turn_id,source_user_message_sha256:userMessageSha256,actor_run_id:intent.actor_run_id,...intent.actor_client_thread_id===void 0?{}:{actor_client_thread_id:intent.actor_client_thread_id,actor_client_turn_id:intent.actor_client_turn_id},actor_task_id:intent.actor_task_id,actor_task_revision:intent.actor_task_revision,actor_plan_hash:intent.actor_plan_hash,actor_objective:actorTask.objective,target_task_id:intent.target_task_id,target_change_id:intent.target_change_id,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,receipt_state_sha256:intent.receipt_state_sha256,current_state_sha256:intent.current_state_sha256,expected_task_revision:intent.expected_task_revision,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,...intent.retry_predecessor_run_id===void 0?{}:{retry_predecessor_run_id:intent.retry_predecessor_run_id,expected_task_attempt_count:intent.expected_task_attempt_count}}}async function assertIssuedRelayAuthorization(composition,intent){const record3=await composition.decisions.read("change",intent.actor_change_id,intent.authorization_id).catch(()=>null);let recorded=null;try{recorded=JSON.parse(record3?.decision??"")}catch{}const[macro,actor]=await Promise.all([composition.runs.read(intent.macro_run_id),composition.runs.read(intent.actor_run_id)]);if(actor.run.parent_run_id!==macro.run.run_id||actor.run.task_id!==intent.actor_task_id||actor.run.change_id!==intent.actor_change_id||actor.run.execution_id!==intent.actor_execution_id||intent.actor_client_thread_id!==void 0&&(actor.run.client_thread_id!==intent.actor_client_thread_id||actor.run.client_turn_id!==intent.actor_client_turn_id)||macro.run.parent_run_id!==null||macro.run.entrypoint!=="spec"||!macro.run.client_thread_id||!macro.run.client_turn_id||!recorded||sha2(recorded.actor_objective??"")!==intent.actor_objective_sha256)throw new UsageError("Historical relay authorization differs from its original Run ancestry");const expected={schema_version:1,kind:"post_publication_relay_authorization",macro_run_id:macro.run.run_id,macro_client_thread_id:macro.run.client_thread_id,macro_client_turn_id:macro.run.client_turn_id,source_user_message_sha256:recorded.source_user_message_sha256,actor_run_id:intent.actor_run_id,...intent.actor_client_thread_id===void 0?{}:{actor_client_thread_id:intent.actor_client_thread_id,actor_client_turn_id:intent.actor_client_turn_id},actor_task_id:intent.actor_task_id,actor_task_revision:intent.actor_task_revision,actor_plan_hash:intent.actor_plan_hash,actor_objective:recorded.actor_objective,target_task_id:intent.target_task_id,target_change_id:intent.target_change_id,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,receipt_state_sha256:intent.receipt_state_sha256,current_state_sha256:intent.current_state_sha256,expected_task_revision:intent.expected_task_revision,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,...intent.retry_predecessor_run_id===void 0?{}:{retry_predecessor_run_id:intent.retry_predecessor_run_id,expected_task_attempt_count:intent.expected_task_attempt_count}};if(record3?.origin!=="agent"||record3.category!=="contract"||!/^[a-f0-9]{64}$/.test(recorded.source_user_message_sha256)||record3.decision!==JSON.stringify(expected))throw new UsageError("Observed macro authorization for this exact relay snapshot is missing")}async function assertLiveRelayAuthority(composition,intent){await assertIssuedRelayAuthorization(composition,intent);await assertRelayActor(composition,intent.actor_run_id,intent.actor_task_id,intent.actor_execution_id);const recorded=await composition.decisions.read("change",intent.actor_change_id,intent.authorization_id);const source=JSON.parse(recorded.decision);if(recorded.decision!==JSON.stringify(await authorizationPayloadForIntent(composition,intent,source.source_user_message_sha256)))throw new UsageError("Live relay actor plan changed after authorization")}var init_post_publication_relay_authorization=__esm({"src/post-publication-relay-authorization.ts"(){"use strict";init_cli_arguments();init_post_publication_relay_core()}});var init_post_publication_relay_contract=__esm({"src/post-publication-relay-contract.ts"(){"use strict";init_post_publication_relay_authorization();init_post_publication_relay_core()}});import{execFile as execFile9}from"node:child_process";import{createHash as createHash42}from"node:crypto";import{posix as posix7}from"node:path";import{promisify as promisify9}from"node:util";async function git(root,args){try{return(await exec3("git",args,{cwd:root,encoding:"utf8",windowsHide:true,timeout:3e4,maxBuffer:4*1024*1024})).stdout.trim()}catch{throw new UsageError("Historical candidate and published Git ancestry are unavailable")}}async function assertRecordsOnlyPublication(filesystem,receipt,requireCurrentCycle){if(requireCurrentCycle){const cycleText=await filesystem.readText(cyclePath3);const cycle=JSON.parse(cycleText);const row=publishedHistoryRow(cycle,receipt.target_release);if(cycle.state!=="open"||row===null||row.from!==receipt.target_release||row.sha!==receipt.proof.published_sha||sha3(cycleText)!==receipt.proof.cycle_sha256)throw new UsageError("Historical publication cycle differs from its issued receipt")}const candidate=receipt.proof.candidate_sha;const published=receipt.proof.published_sha;await git(filesystem.root,["merge-base","--is-ancestor",candidate,published]);await git(filesystem.root,["merge-base","--is-ancestor",published,"HEAD"]);const commits=(await git(filesystem.root,["rev-list","--reverse","--parents",`${candidate}..${published}`])).split(/\r?\n/).filter(Boolean);for(const row of commits){const[commit,...parents]=row.split(/\s+/);if(!commit||parents.length!==1)throw new UsageError("Published successor contains an intermediary merge");const paths2=(await git(filesystem.root,["diff-tree","--root","-m","--no-commit-id","-r","--name-only","-z",commit])).split("\0").filter(Boolean);if(paths2.some(path=>!path.startsWith(".agents/records/")))throw new UsageError("Published successor contains product or merge changes")}}async function assertIssuedReceipt(filesystem,composition,receipt,mode="live"){const issuer=await composition.runs.read(receipt.actor_run_id);const issuerTask=(await composition.tasks.read(receipt.actor_task_id)).task;if(issuer.finished?.status!=="completed"||issuer.finalization_decision?.outcome!=="completed"||issuerTask.status!=="completed"||issuer.run.task_id!==receipt.actor_task_id||issuer.run.execution_id!==receipt.actor_execution_id||issuer.run.change_id!==issuerTask.change_id||issuer.run.parent_run_id!==null)throw new UsageError("Post-publication receipt issuer is not terminal and attributed");if(receipt.maintenance_direct_authorization_sha256!==void 0&&sha3(issuer.run.direct_execution_authorization??"")!==receipt.maintenance_direct_authorization_sha256)throw new UsageError("Post-publication direct authorization changed after issuance");await assertRecoveryDecision(composition,"change",issuerTask.change_id,receipt.human_decision_id,authorizationPayload(receipt));const issuance=await composition.decisions.read("change",issuerTask.change_id,receipt.issuance_decision_id);const human=await composition.decisions.read("change",issuerTask.change_id,receipt.human_decision_id);if(issuance.origin!=="agent"||issuance.category!=="contract"||issuance.decision!==issuancePayload(receipt)||!issuance.created_at||!human.confirmed_at||Date.parse(human.confirmed_at)>Date.parse(issuance.created_at)||Date.parse(issuance.created_at)>Date.parse(issuer.finished.occurred_at))throw new UsageError("Post-publication receipt issuance is not canonical");await assertRecordsOnlyPublication(filesystem,receipt,mode==="live")}async function evidenceHashes(filesystem,composition,receipt){const{task}=await composition.tasks.read(receipt.target_task_id);const ids2=receipt.proof.evidence_ids;const bundle=await readAssuranceBundle(filesystem,composition.layout,[task],ids2);if(ids2.length===0||new Set(ids2).size!==ids2.length||bundle.evidences.length!==ids2.length||bundle.evidences.some(item=>item.status!=="passed"||item.task_id!==receipt.target_task_id||item.change_id!==receipt.target_change_id||item.execution_id!==receipt.target_execution_id||item.commit_sha!==receipt.proof.candidate_sha))throw new UsageError("Historical Evidence selection differs from the receipt");const directory2=posix7.dirname(composition.layout.activePath("change",task.change_id));const hashes={};for(const id of[...ids2].sort()){const evidence=bundle.evidences.find(item=>item.id===id);if(!evidence||(await composition.runs.read(evidence.run_id)).status!=="completed")throw new UsageError("Historical Evidence producer is not terminal");hashes[id]=sha3(await filesystem.readText(`${directory2}/artifacts/evidence/${id}.md`))}return hashes}var exec3,sha3,cyclePath3;var init_post_publication_relay_proof=__esm({"src/post-publication-relay-proof.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_authority();init_lifecycle_assurance_v2();init_post_publication_cycle();init_post_publication_recovery();exec3=promisify9(execFile9);sha3=value=>createHash42("sha256").update(value).digest("hex");cyclePath3=".agents/config/release-cycle.json"}});async function authenticatedRelayForCapture(composition,actor,targetTaskId,intentId){const intent=await readRelayIntent(composition,actor,targetTaskId,intentId);if(intent===null)return null;await assertRelayActor(composition,actor.run.run_id,intent.actor_task_id,intent.actor_execution_id);const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256||receipt.target_task_id!==targetTaskId||receipt.target_change_id!==intent.target_change_id||receipt.target_execution_id!==intent.target_execution_id||receipt.target_spec_id!==intent.target_spec_id||receipt.proof.candidate_sha!==intent.candidate_sha||receipt.proof.published_sha!==intent.published_sha)throw new UsageError("Historical relay receipt differs from its captured target");await assertIssuedReceipt(composition.filesystem,composition,receipt);const actorTask=(await composition.tasks.read(intent.actor_task_id)).task;if(actorTask.revision!==intent.actor_task_revision||actorTask.plan_hash!==intent.actor_plan_hash||sha2(actorTask.objective)!==intent.actor_objective_sha256||receipt.state_sha256!==intent.receipt_state_sha256)throw new UsageError("Historical relay actor plan or receipt snapshot changed");if(JSON.stringify(await evidenceHashes(composition.filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical relay Evidence changed before native capture");const[{task},{change},{execution},{spec}]=await Promise.all([composition.tasks.read(targetTaskId),composition.changes.read(intent.target_change_id),composition.executions.read(intent.target_execution_id),composition.specs.read(intent.target_spec_id)]);if(task.status!=="executing"||task.revision!==intent.expected_task_revision+1||intent.expected_task_attempt_count!==void 0&&task.attempt_count!==intent.expected_task_attempt_count+1||change.status!=="executing"||change.revision!==intent.expected_change_revision+(intent.retry_predecessor_run_id?0:1)||execution.status!=="running"||execution.revision!==intent.expected_execution_revision+(intent.retry_predecessor_run_id?0:1)||spec.status!=="active"||spec.revision!==intent.expected_spec_revision+(intent.retry_predecessor_run_id?0:1))throw new UsageError("Historical relay Task changed before native capture");await assertLiveRelayAuthority(composition,intent);return intent}async function assertRelayNativeCapture(composition,actor,targetTaskId,intentId,nativeSessionId,agentId2,turnId,record3){if(!intentId||!nativeSessionId||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(nativeSessionId))throw new UsageError("Historical native capture requires exact relay and session");const intent=record3?await authenticatedRelayForCapture(composition,actor,targetTaskId,intentId):await readRelayIntent(composition,actor,targetTaskId,intentId);if(!intent)throw new UsageError("Historical relay is not authenticated for native capture");const id=relayCaptureId(actor.run.run_id,agentId2,turnId);const payload={schema_version:1,kind:"post_publication_relay_capture",intent_id:intentId,actor_run_id:actor.run.run_id,target_task_id:targetTaskId,native_session_id:nativeSessionId,agent_id:agentId2,turn_id:turnId};if(record3){await recordRelayDecision(composition,id,intent.actor_change_id,payload);return}await assertIssuedRelayAuthorization(composition,intent);const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256||JSON.stringify(await evidenceHashes(composition.filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical native replay receipt or Evidence changed");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const existing=await composition.decisions.read("change",intent.actor_change_id,id).catch(()=>null);if(existing?.origin!=="agent"||existing.category!=="contract"||existing.decision!==JSON.stringify(payload))throw new UsageError("Historical native capture differs from its canonical relay")}async function bindPostPublicationRelay(parsed,filesystem,composition){requireOptions(parsed.options,["actor-run","run","relay"]);const targetTaskId=parsed.positionals[2];if(!targetTaskId?.startsWith("TASK-"))throw new UsageError("Exact historical Task is required");const actor=await composition.runs.read(required2(parsed.options["actor-run"],"actor Run"));await assertRelayActor(composition,actor.run.run_id,actor.run.task_id??"",actor.run.execution_id??"");const intent=await readRelayIntent(composition,actor,targetTaskId,required2(parsed.options.relay,"relay intent"));if(!intent)throw new UsageError("Exact issued relay intent is required");await authenticatedRelayForCapture(composition,actor,targetTaskId,parsed.options.relay);const target=(await composition.tasks.read(targetTaskId)).task;const child=await composition.runs.read(required2(parsed.options.run,"historical Run"));const owners2=(await composition.runs.list()).filter(run=>run.status==="running"&&run.run.task_id===targetTaskId);if(target.status!=="executing"||target.revision!==intent.expected_task_revision+1||target.change_id!==intent.target_change_id||owners2.length!==1||owners2[0]?.run.run_id!==child.run.run_id||child.status!=="running"||child.run.parent_run_id!==actor.run.run_id||child.run.agent!=="agent-orchestrator"||child.run.run_role!=="subagent"||child.run.run_purpose!=="orchestration"||child.run.client!=="codex-subagent"||child.run.task_id!==targetTaskId||child.run.change_id!==intent.target_change_id||child.run.execution_id!==intent.target_execution_id||child.run.spec_id!==intent.target_spec_id||child.run.conversation_id!==actor.run.conversation_id||!child.run.client_thread_id||!child.run.client_turn_id||!child.run.model||!child.run.reasoning_effort)throw new UsageError("Relay binding needs one exact observed historical Task Run");if(intent.retry_predecessor_run_id){const captureId=relayCaptureId(actor.run.run_id,child.run.client_thread_id,child.run.client_turn_id);const captureRecord=await composition.decisions.read("change",intent.actor_change_id,captureId).catch(()=>null);let capture2=null;try{capture2=JSON.parse(captureRecord?.decision??"")}catch{}if(captureRecord?.origin!=="agent"||captureRecord.category!=="contract"||!capture2||capture2.intent_id!==parsed.options.relay||capture2.actor_run_id!==actor.run.run_id||capture2.target_task_id!==targetTaskId||capture2.agent_id!==child.run.client_thread_id||capture2.turn_id!==child.run.client_turn_id)throw new UsageError("Relay binding requires the exact native retry capture");await assertRelayNativeCapture(composition,actor,targetTaskId,parsed.options.relay,capture2.native_session_id,child.run.client_thread_id,child.run.client_turn_id,false)}const receipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256)throw new UsageError("Relay receipt bytes changed");await assertIssuedReceipt(filesystem,composition,receipt);if(JSON.stringify(await evidenceHashes(filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence bytes changed before relay binding");const id=relayBindingId(child.run.run_id);const binding={schema_version:1,kind:"post_publication_relay_binding",intent_id:parsed.options.relay,actor_run_id:actor.run.run_id,target_run_id:child.run.run_id,target_task_id:targetTaskId,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,client_thread_id:child.run.client_thread_id,client_turn_id:child.run.client_turn_id,candidate_sha:intent.candidate_sha,evidence_sha256:intent.evidence_sha256};await recordRelayDecision(composition,id,intent.actor_change_id,binding);return{bound:true,binding_id:id,target_run_id:child.run.run_id,receipt_sha256:intent.receipt_sha256}}async function authenticatedBoundRelay(root,composition){if(root.run.task_id===null||root.run.parent_run_id===null||root.run.run_purpose!=="orchestration")return null;const actor=await composition.runs.read(root.run.parent_run_id);if(actor.run.change_id==null)return null;const bindingRecord=await composition.decisions.read("change",actor.run.change_id,relayBindingId(root.run.run_id)).catch(()=>null);if(bindingRecord?.origin!=="agent"||bindingRecord.category!=="contract")return null;let binding;try{binding=JSON.parse(bindingRecord.decision)}catch{throw new UsageError("Post-publication Evidence binding is invalid")}const intent=await readRelayIntent(composition,actor,root.run.task_id,binding.intent_id);if(!intent)throw new UsageError("Bound post-publication relay intent is missing");await assertIssuedRelayAuthorization(composition,intent);if(binding.schema_version!==1||binding.kind!=="post_publication_relay_binding"||binding.intent_id!==relayIntentId(actor.run.run_id,root.run.task_id,binding.intent_id===relayIntentId(actor.run.run_id,root.run.task_id)?void 0:intent.current_state_sha256)||binding.actor_run_id!==actor.run.run_id||binding.target_run_id!==root.run.run_id||binding.target_task_id!==root.run.task_id||binding.target_execution_id!==root.run.execution_id||binding.target_spec_id!==root.run.spec_id||binding.client_thread_id!==root.run.client_thread_id||binding.client_turn_id!==root.run.client_turn_id||binding.receipt_sha256!==intent.receipt_sha256||binding.candidate_sha!==intent.candidate_sha||JSON.stringify(binding.evidence_sha256)!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Post-publication Evidence binding differs from observed ancestry");const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256)throw new UsageError("Post-publication receipt changed after binding");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const actual=await evidenceHashes(composition.filesystem,composition,receipt);if(JSON.stringify(actual)!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence bytes changed after binding");return{intent,evidenceIds:new Set(Object.keys(actual))}}async function historicalRelayEvidenceIds(root,composition){return(await authenticatedBoundRelay(root,composition))?.evidenceIds??new Set}var init_post_publication_relay_binding=__esm({"src/post-publication-relay-binding.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_contract();init_post_publication_relay_proof()}});async function assertRelayRetryPredecessor(composition,actor,predecessorRunId,receipt,task,change,execution,spec){const predecessor=await composition.runs.read(predecessorRunId);const bound=await authenticatedBoundRelay(predecessor,composition);const prior=bound?.intent;const parentAdvance=prior?.retry_predecessor_run_id?0:1;if(predecessor.finished?.status!=="completed"||predecessor.finalization_decision!==null||predecessor.run.parent_run_id!==actor.run.run_id||predecessor.run.task_id!==task.id||!task.status_reason?.includes(predecessorRunId)||!Number.isSafeInteger(task.attempt_count)||!prior||prior.actor_run_id!==actor.run.run_id||prior.target_task_id!==task.id||prior.receipt_sha256!==sha2(JSON.stringify(receipt))||task.revision!==prior.expected_task_revision+2||prior.expected_task_attempt_count!==void 0&&task.attempt_count!==prior.expected_task_attempt_count+1||change.revision!==prior.expected_change_revision+parentAdvance||execution.revision!==prior.expected_execution_revision+parentAdvance||spec.revision!==prior.expected_spec_revision+parentAdvance)throw new UsageError("Historical retry requires its exact terminal bound predecessor");return prior}var init_post_publication_relay_retry=__esm({"src/post-publication-relay-retry.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_binding();init_post_publication_relay_contract()}});var post_publication_relay_exports={};__export(post_publication_relay_exports,{assertRelayNativeCapture:()=>assertRelayNativeCapture,authenticatedBoundRelay:()=>authenticatedBoundRelay,authenticatedRelayForCapture:()=>authenticatedRelayForCapture,authorizePostPublicationRelay:()=>authorizePostPublicationRelay,bindPostPublicationRelay:()=>bindPostPublicationRelay,historicalRelayEvidenceIds:()=>historicalRelayEvidenceIds,preparePostPublicationRelay:()=>preparePostPublicationRelay});async function authorizePostPublicationRelay(parsed,filesystem,composition,lifecycle){const preview2=await preparePostPublicationRelay({...parsed,flags:new Set([...parsed.flags].filter(flag=>flag!=="apply"))},filesystem,composition,lifecycle);if(preview2.applied!==false||!("intent"in preview2))throw new UsageError("Exact historical relay preview is required");const intent=preview2.intent;const macro=await composition.runs.read(intent.macro_run_id);const observed=await resolveRunClientInvocation(filesystem,macro.run.client);if(macro.status!=="running"||macro.run.parent_run_id!==null||macro.run.run_role!=="orchestrator"||observed.clientThreadId!==macro.run.client_thread_id||observed.clientTurnId!==macro.run.client_turn_id||!observed.userMessage?.trim()||observed.observedModel!==macro.run.model||observed.observedReasoningEffort!==macro.run.reasoning_effort)throw new UsageError("Historical relay authorization requires the observed macro root turn");if(!parsed.flags.has("apply"))return{authorized:false,authorization_id:intent.authorization_id,intent_id:preview2.intent_id};const observedMessageSha=sha2(required2(observed.userMessage,"observed user message"));return composition.runs.withUsageAttributionLock(async()=>{const lockedMacro=await composition.runs.read(intent.macro_run_id);const lockedObserved=await resolveRunClientInvocation(filesystem,lockedMacro.run.client);if(lockedMacro.status!=="running"||lockedMacro.run.parent_run_id!==null||lockedMacro.run.run_role!=="orchestrator"||lockedObserved.clientThreadId!==lockedMacro.run.client_thread_id||lockedObserved.clientTurnId!==lockedMacro.run.client_turn_id||!lockedObserved.userMessage?.trim()||sha2(lockedObserved.userMessage)!==observedMessageSha||lockedObserved.observedModel!==lockedMacro.run.model||lockedObserved.observedReasoningEffort!==lockedMacro.run.reasoning_effort)throw new UsageError("Observed macro root turn changed before relay authorization");const current=(await composition.tasks.read(intent.target_task_id)).task;const[change,execution,spec]=await Promise.all([composition.changes.read(intent.target_change_id).then(({change:change2})=>change2),composition.executions.read(intent.target_execution_id).then(({execution:execution2})=>execution2),composition.specs.read(intent.target_spec_id).then(({spec:spec2})=>spec2)]);const cycle=JSON.parse(await filesystem.readText(cyclePath4));if(current.status!=="blocked"||closureStateHash(current,change,execution,spec,cycle)!==intent.current_state_sha256)throw new UsageError("Historical closure preview changed before macro authorization");if(intent.retry_predecessor_run_id){const receipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);await assertRelayRetryPredecessor(composition,await composition.runs.read(intent.actor_run_id),intent.retry_predecessor_run_id,receipt,current,change,execution,spec)}const payload=await authorizationPayloadForIntent(composition,intent,observedMessageSha);await recordRelayDecision(composition,intent.authorization_id,intent.actor_change_id,payload);return{authorized:true,authorization_id:intent.authorization_id,intent_id:preview2.intent_id}})}async function preparePostPublicationRelay(parsed,filesystem,composition,lifecycle){requireOptions(parsed.options,["receipt","actor-task","actor-execution","run","expected-revision"]);const targetTaskId=parsed.positionals[2];if(!targetTaskId?.startsWith("TASK-"))throw new UsageError("Exact historical Task is required");const actor=await assertRelayActor(composition,required2(parsed.options.run,"actor Run"),required2(parsed.options["actor-task"],"actor Task"),required2(parsed.options["actor-execution"],"actor Execution"));const receiptPath2=required2(parsed.options.receipt,"receipt path");const receipt=await readPostPublicationReceipt(filesystem,receiptPath2);if(receipt.target_spec_id===null)throw new UsageError("Task-first historical closure uses resume-post-publication, not a SPEC relay");if(receipt.target_task_id!==targetTaskId)throw new UsageError("Post-publication receipt targets another Task");await assertIssuedReceipt(filesystem,composition,receipt);const hashes=await evidenceHashes(filesystem,composition,receipt);const[{task},{change},{execution},{spec},{task:actorTask}]=await Promise.all([composition.tasks.read(targetTaskId),composition.changes.read(receipt.target_change_id),composition.executions.read(receipt.target_execution_id),composition.specs.read(receipt.target_spec_id),composition.tasks.read(required2(actor.run.task_id,"actor Task"))]);if(!actorTask.plan_hash||!/^[a-f0-9]{64}$/.test(actorTask.plan_hash)||!actorTask.objective)throw new UsageError("Delegated Task plan hash is required for historical closure");const cycle=JSON.parse(await filesystem.readText(cyclePath4));const currentHash=closureStateHash(task,change,execution,spec,cycle);const expected=Number(parsed.options["expected-revision"]);const id=task.status==="blocked"?relayIntentId(actor.run.run_id,targetTaskId,currentHash):parsed.options.relay??relayIntentId(actor.run.run_id,targetTaskId);const existing=await readRelayIntent(composition,actor,targetTaskId,id);const activeParents=change.status==="executing"&&execution.status==="running"&&spec.status==="active";const retryPredecessor=task.status==="blocked"&&activeParents?await assertRelayRetryPredecessor(composition,actor,required2(parsed.options["predecessor-run"],"terminal predecessor Run"),receipt,task,change,execution,spec):null;const parentRevisionAdvance=existing?.retry_predecessor_run_id===void 0?1:0;const resumedStateMatches=existing!==null&&task.revision===expected+1&&(existing.expected_task_attempt_count===void 0||task.attempt_count===existing.expected_task_attempt_count+1)&&change.status==="executing"&&change.revision===existing.expected_change_revision+parentRevisionAdvance&&execution.status==="running"&&execution.revision===existing.expected_execution_revision+parentRevisionAdvance&&spec.status==="active"&&spec.revision===existing.expected_spec_revision+parentRevisionAdvance;if(!Number.isSafeInteger(expected)||expected<1||(task.status==="blocked"?task.revision!==expected:task.status!=="executing"||!resumedStateMatches)||existing!==null&&existing.expected_task_revision!==expected||existing!==null&&parsed.options["predecessor-run"]!==void 0&&parsed.options["predecessor-run"]!==existing.retry_predecessor_run_id||task.status==="blocked"&&(!(change.status==="blocked"&&execution.status==="blocked"&&spec.status==="blocked"||retryPredecessor!==null)||spec.target_release!==receipt.target_release||execution.origin.type!=="spec"||execution.origin.spec_id!==spec.id))throw new UsageError("Historical Task revision or relay state changed");if(task.change_id!==receipt.target_change_id||actor.run.task_id===task.id||(await composition.runs.list()).some(run=>run.run.task_id===task.id&&run.status==="running"))throw new UsageError("Historical Task has another owner or target");const intent={schema_version:1,kind:"post_publication_relay_intent",actor_run_id:actor.run.run_id,...existing===null?{actor_client_thread_id:required2(actor.run.client_thread_id,"actor client thread"),actor_client_turn_id:required2(actor.run.client_turn_id,"actor client turn")}:existing.actor_client_thread_id===void 0?{}:{actor_client_thread_id:existing.actor_client_thread_id,actor_client_turn_id:existing.actor_client_turn_id},actor_task_id:required2(actor.run.task_id,"actor Task"),actor_change_id:required2(actor.run.change_id,"actor Change"),actor_execution_id:required2(actor.run.execution_id,"actor Execution"),actor_task_revision:actorTask.revision,actor_plan_hash:actorTask.plan_hash,actor_objective_sha256:sha2(actorTask.objective),macro_run_id:required2(actor.run.parent_run_id,"macro Run"),authorization_id:existing?.authorization_id??relayAuthorizationId(actor.run.run_id,task.id,currentHash),receipt_path:receiptPath2,receipt_sha256:sha2(JSON.stringify(receipt)),target_task_id:task.id,target_change_id:receipt.target_change_id,target_execution_id:receipt.target_execution_id,target_spec_id:receipt.target_spec_id,expected_task_revision:expected,expected_change_revision:existing?.expected_change_revision??change.revision,expected_execution_revision:existing?.expected_execution_revision??execution.revision,expected_spec_revision:existing?.expected_spec_revision??spec.revision,...existing?.retry_predecessor_run_id||retryPredecessor?{retry_predecessor_run_id:existing?.retry_predecessor_run_id??parsed.options["predecessor-run"],expected_task_attempt_count:existing?.expected_task_attempt_count??task.attempt_count}:{},receipt_state_sha256:receipt.state_sha256,current_state_sha256:existing?.current_state_sha256??currentHash,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,evidence_sha256:hashes};if(existing!==null&&JSON.stringify(existing)!==JSON.stringify(intent))throw new UsageError("Historical relay differs from its canonical intent");if(!parsed.flags.has("apply"))return{applied:false,intent_id:id,expected_task_revision:expected,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,target_task_id:task.id,authorization_id:intent.authorization_id,current_state_sha256:intent.current_state_sha256,receipt_state_sha256:intent.receipt_state_sha256,intent};await assertLiveRelayAuthority(composition,intent);return composition.runs.withUsageAttributionLock(async()=>{const freshReceipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);if(sha2(JSON.stringify(freshReceipt))!==intent.receipt_sha256||freshReceipt.target_task_id!==intent.target_task_id)throw new UsageError("Post-publication receipt changed before relay apply");await assertRelayActor(composition,intent.actor_run_id,intent.actor_task_id,intent.actor_execution_id);if((await composition.runs.list()).some(run=>run.run.task_id===intent.target_task_id&&run.status==="running"))throw new UsageError("Historical Task has another owner before relay apply");const fresh=(await composition.tasks.read(task.id)).task;const[freshChange,freshExecution,freshSpec]=await Promise.all([composition.changes.read(intent.target_change_id).then(({change:change2})=>change2),composition.executions.read(intent.target_execution_id).then(({execution:execution2})=>execution2),composition.specs.read(intent.target_spec_id).then(({spec:spec2})=>spec2)]);const freshActorTask=(await composition.tasks.read(intent.actor_task_id)).task;await assertLiveRelayAuthority(composition,intent);if(freshActorTask.revision!==intent.actor_task_revision||freshActorTask.plan_hash!==intent.actor_plan_hash)throw new UsageError("Delegated Task authorization changed before relay apply");if(fresh.status==="executing"&&existing!==null){const advance=intent.retry_predecessor_run_id?0:1;if(fresh.revision!==expected+1||intent.expected_task_attempt_count!==void 0&&fresh.attempt_count!==intent.expected_task_attempt_count+1||freshChange.status!=="executing"||freshChange.revision!==intent.expected_change_revision+advance||freshExecution.status!=="running"||freshExecution.revision!==intent.expected_execution_revision+advance||freshSpec.status!=="active"||freshSpec.revision!==intent.expected_spec_revision+advance)throw new UsageError("Historical relay replay changed after its canonical intent");return{applied:true,reused:true,intent_id:id,target_task_id:task.id}}if(fresh.status!=="blocked"||fresh.revision!==expected||intent.expected_task_attempt_count!==void 0&&fresh.attempt_count!==intent.expected_task_attempt_count||freshChange.status!==(intent.retry_predecessor_run_id?"executing":"blocked")||freshChange.revision!==intent.expected_change_revision||freshExecution.status!==(intent.retry_predecessor_run_id?"running":"blocked")||freshExecution.revision!==intent.expected_execution_revision||freshSpec.status!==(intent.retry_predecessor_run_id?"active":"blocked")||freshSpec.revision!==intent.expected_spec_revision)throw new UsageError("Historical Task changed before relay apply");const freshCycle=JSON.parse(await filesystem.readText(cyclePath4));if(closureStateHash(fresh,freshChange,freshExecution,freshSpec,freshCycle)!==intent.current_state_sha256)throw new UsageError("Historical closure snapshot changed before relay apply");if(intent.retry_predecessor_run_id)await assertRelayRetryPredecessor(composition,actor,intent.retry_predecessor_run_id,freshReceipt,fresh,freshChange,freshExecution,freshSpec);await assertIssuedReceipt(filesystem,composition,freshReceipt);if(JSON.stringify(await evidenceHashes(filesystem,composition,freshReceipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence changed before relay apply");await recordRelayDecision(composition,id,intent.actor_change_id,intent);await lifecycle.startTaskWithSnapshot(task.id,"resume",{targetTaskId:task.id,targetRelease:freshReceipt.target_release,publishedSha:freshReceipt.proof.published_sha,cycleSha256:freshReceipt.proof.cycle_sha256});return{applied:true,reused:false,intent_id:id,target_task_id:task.id}})}var cyclePath4;var init_post_publication_relay=__esm({"src/post-publication-relay.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_contract();init_post_publication_relay_proof();init_run_client_invocation();init_post_publication_relay_retry();init_post_publication_relay_binding();cyclePath4=".agents/config/release-cycle.json"}});var post_publication_task_first_exports={};__export(post_publication_task_first_exports,{taskFirstPublishedBoundary:()=>taskFirstPublishedBoundary});async function taskFirstPublishedBoundary(root,composition){const run=root.run;if(run.parent_run_id!==null||run.task_id===null||run.spec_id!==null||!run.client_turn_id||!run.execution_id||!run.continuation_of_run_id)return null;const sequence=await composition.executions.readPostPublicationSequence(run.client_turn_id);const claim=sequence?.steps.find(step=>step.successor_run_id===run.run_id);if(claim===void 0&&sequence?.steps.some(step=>step.origin.type==="task"&&step.target_task_id===run.task_id))throw new UsageError("Task-first publication claim differs from the closure owner");if(claim?.origin.type!=="task")return null;if(claim.predecessor_run_id!==run.continuation_of_run_id||claim.target_task_id!==run.task_id||claim.origin.task_id!==run.task_id||claim.execution_id!==run.execution_id)throw new UsageError("Task-first publication claim differs from the closure owner");const receipt=await readPostPublicationReceipt(composition.filesystem,`.local/recovery/post-publication/${claim.authorization_sha256}.json`);if(receipt.target_spec_id!==null||receipt.target_task_id!==run.task_id||receipt.target_change_id!==run.change_id||receipt.target_execution_id!==run.execution_id||receipt.actor_run_id!==sequence?.maintenance_run_id||receipt.client_thread_id!==run.client_thread_id||sha(JSON.stringify(receipt))!==claim.authorization_sha256)throw new UsageError("Task-first publication receipt differs from the closure owner");const{execution}=await composition.executions.read(run.execution_id);if(execution.origin.type!=="task"||execution.origin.task_id!==run.task_id||execution.dag.nodes.length!==1||execution.dag.nodes[0]?.task_id!==run.task_id||execution.dag.nodes[0]?.change_id!==run.change_id)throw new UsageError("Task-first publication Execution has another owner");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const hashes=await evidenceHashes(composition.filesystem,composition,receipt);await assertHistoricalProofSnapshot(receipt,composition,root);return{target_task_id:run.task_id,target_spec_id:null,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,evidence_ids:Object.keys(hashes)}}var init_post_publication_task_first=__esm({"src/post-publication-task-first.ts"(){"use strict";init_cli_arguments();init_post_publication_receipt();init_post_publication_relay_proof();init_post_publication_snapshot()}});async function assertExecutionDescendantsComplete(repositories,executionId,nodes){for(const node of nodes){const{task}=await repositories.tasks.read(node.task_id);if(task.change_id!==node.change_id){throw new LifecycleGateError(`Execution ${executionId} DAG ownership mismatch for ${task.id}`)}if(task.status!=="completed"){throw new LifecycleGateError(`Execution Task must be completed: ${formatLifecycleState(task)}`)}}}async function assertSixStageDeliveryCoverage(filesystem,layout,repositories,task,result2,executionId,enforceLegacyRiskCounts,assurance){const signals=effectiveTaskRiskSignals(task);if(task.assurance_risk_signals_source==="explicit"&&task.assurance_risk_signals?.editorial_delivery===true&&assurance===null)throw new LifecycleGateError("Editorial delivery requires assurance.version: 1");await assertTaskSixStageCoverage({filesystem,layout,repositories},task,result2,executionId,enforceLegacyRiskCounts,assurance===null||!assertEditorialDeliveryEligibility(task,signals))}async function deliveryCandidateProofs(filesystem,layout,tasks,config2,compositionOverride){const bundle=await readAssuranceBundle(filesystem,layout,tasks);const composition=compositionOverride??(await Promise.resolve().then(()=>(init_v2_router(),v2_router_exports))).createV2Composition(filesystem,layout);const boundaries=(await Promise.all(tasks.map(async task=>task.status==="completed"&&task.result?.completed_run_id?historicalPublishedBoundaryForTask(task,await composition.runs.read(task.result.completed_run_id),composition):null))).filter(boundary=>boundary!==null);if(boundaries.length>1)throw new LifecycleGateError("Historical publication has multiple candidate boundaries");const publishedBoundary=boundaries[0];const expected=config2.require_final_commit?(await inspectFinalProductCandidate(filesystem.root,bundle.validations,bundle.evidences,void 0,void 0,void 0,publishedBoundary)).commit:null;const validations=expected===null?bundle.validations:bundle.validations.filter(artifact=>artifact.commit_sha===expected);const evidences=expected===null?bundle.evidences:bundle.evidences.filter(artifact=>artifact.commit_sha===expected);return{bundle,expected,validations,evidences}}async function historicalPublishedBoundaryForTask(task,run,composition){if(run.run.task_id!==task.id||run.run.execution_id===null)return null;if(run.run.spec_id===null){const{taskFirstPublishedBoundary:taskFirstPublishedBoundary2}=await Promise.resolve().then(()=>(init_post_publication_task_first(),post_publication_task_first_exports));return taskFirstPublishedBoundary2(run,composition)}const bound=await authenticatedBoundRelay(run,composition);if(!bound)return null;const{intent,evidenceIds}=bound;const{execution}=await composition.executions.read(intent.target_execution_id);if(evidenceIds.size===0||intent.target_task_id!==task.id||intent.target_execution_id!==run.run.execution_id||intent.target_spec_id!==run.run.spec_id||execution.origin.type!=="spec"||execution.origin.spec_id!==intent.target_spec_id)throw new LifecycleGateError("Historical publication boundary has different Task ownership");return{target_task_id:intent.target_task_id,target_spec_id:intent.target_spec_id,candidate_sha:intent.candidate_sha,published_sha:intent.published_sha,evidence_ids:[...evidenceIds]}}function assertHistoricalRelayChangedFiles(boundary,changedFiles){if(!boundary)return;if(changedFiles.some(path=>!path.startsWith(".agents/records/")||path.includes("\\")||path.split("/").includes("..")||path.endsWith("/")))throw new LifecycleGateError("Historical publication relay permits only causal record files")}async function tasksForChange(repositories,changeId,expectedIds){const tasks=await Promise.all(expectedIds.map(taskId=>repositories.tasks.read(taskId)));for(const{task}of tasks){if(task.change_id!==changeId){throw new LifecycleGateError(`Task ${task.id} does not belong to Change ${changeId}`)}}return tasks.map(({task})=>task)}var init_lifecycle_v2_delivery_assurance=__esm({"src/lifecycle-v2-delivery-assurance.ts"(){"use strict";init_candidate_resolution();init_editorial_delivery_assurance();init_lifecycle_assurance_v2();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_post_publication_relay()}});async function readAssuranceRunAncestry(repository2,ids2){const result2=new Map;for(const owner of new Set(ids2)){const visited=new Set;let id=owner;while(id!==null){if(visited.has(id)||visited.size>=256)throw new Error("Assurance Run ancestry is cyclic or exceeds its depth limit");visited.add(id);let run=result2.get(id);if(!run){run=await repository2.read(id);if(run.run.run_id!==id)throw new Error("Assurance Run identity mismatch");result2.set(id,run)}id=run.run.parent_run_id}}return result2}var init_assurance_run_ancestry=__esm({"src/assurance-run-ancestry.ts"(){"use strict"}});import{execFile as execFile10}from"node:child_process";import{randomUUID as randomUUID6}from"node:crypto";import{lstat as lstat8,mkdtemp,readdir as readdir3,readFile as readFile9,realpath as realpath8,rm as rm5,unlink as unlink3,writeFile as writeFile3}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname6,join as join3,resolve as resolve12}from"node:path";import{promisify as promisify10}from"node:util";async function withCandidateWorkspace(repositoryPath,commit,operation){if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit))throw new Error("candidate validation requires a full commit SHA");const started=performance.now();const repository2=resolve12(repositoryPath);const validationRoot=await realpath8(tmpdir());const path=await mkdtemp(join3(validationRoot,`zaip-candidate-${basename2(repository2)}-`));const ownerPath=`${path}.owner`;const owner=randomUUID6();const assertOwnedPath=async(required3=false)=>{if(dirname6(resolve12(path))!==validationRoot||!basename2(path).startsWith("zaip-candidate-"))throw new Error("Candidate checkout path escaped its owner");const info=await lstat8(path).catch(error51=>{if(error51.code==="ENOENT")return null;throw error51});if(required3&&info===null)throw new Error("Owned candidate directory disappeared");if(info!==null&&(!info.isDirectory()||info.isSymbolicLink()||await realpath8(path)!==path))throw new Error("Candidate checkout is no longer an owned directory")};try{await assertOwnedPath(true);await writeFile3(ownerPath,owner,{flag:"wx",mode:384})}catch(setupError){try{await assertOwnedPath(true);const marker=await readFile9(ownerPath,"utf8").catch(error51=>{if(error51.code==="ENOENT")return null;throw error51});if(marker!==null&&marker!==owner)throw new Error("Candidate ownership marker changed during setup");await rm5(path,{recursive:true,force:true});if(marker!==null)await unlink3(ownerPath)}catch(cleanupError){throw new AggregateError([setupError,cleanupError],"Candidate setup and cleanup failed")}throw setupError}const assertOwnerMarker=async()=>{if(await readFile9(ownerPath,"utf8")!==owner)throw new Error("Candidate checkout ownership marker changed")};const assertOwned=async()=>{await assertOwnerMarker();await assertOwnedPath()};const workspace=Object.freeze({path,repository:repository2,commit});let attached=false;let value;let preparationMs=0;let cleanupMs=0;let primaryFailure;let cleanupFailure;try{await git2(repository2,["worktree","add","--detach",path,commit]);attached=true;owners.set(workspace,{running:false});preparationMs=Math.round(performance.now()-started);value=await operation(workspace)}catch(error51){primaryFailure=error51}finally{const cleanupStarted=performance.now();owners.delete(workspace);try{await assertOwned();if(await lstat8(path).catch(()=>null))await detachCandidateLinks(path);let unregisterFailed=false;const listedBefore=attached?null:await git2(repository2,["worktree","list","--porcelain"]);const partiallyAttached=listedBefore?.stdout.split(/\r?\n/).some(line=>line.startsWith("worktree ")&&resolve12(line.slice(9))===resolve12(path))??false;if(attached||partiallyAttached){try{await git2(repository2,["worktree","remove","--force","--force",path])}catch{unregisterFailed=true}}await assertOwned();if(await lstat8(path).catch(()=>null))await rm5(path,{recursive:true,force:true,maxRetries:3,retryDelay:100});if(unregisterFailed){const listed=await git2(repository2,["worktree","list","--porcelain"]);const registered=listed.stdout.split(/\r?\n/).some(line=>line.startsWith("worktree ")&&resolve12(line.slice(9))===resolve12(path));if(registered)await git2(repository2,["worktree","remove","--force","--force",path])}await assertOwnerMarker();await unlink3(ownerPath);cleanupMs=Math.round(performance.now()-cleanupStarted)}catch(error51){cleanupFailure=error51}}if(cleanupFailure!==void 0){const message2=error51=>error51 instanceof Error?error51.message:String(error51);throw new AggregateError(primaryFailure===void 0?[cleanupFailure]:[primaryFailure,cleanupFailure],`${primaryFailure===void 0?"Candidate operation finished":message2(primaryFailure)}; cleanup incomplete at ${path}: ${message2(cleanupFailure)}`)}if(primaryFailure!==void 0)throw primaryFailure;return{value,preparation_ms:preparationMs,cleanup_ms:cleanupMs}}async function detachCandidateLinks(directory2){for(const entry2 of await readdir3(directory2,{withFileTypes:true})){const path=join3(directory2,entry2.name);if(entry2.isSymbolicLink())await unlink3(path);else if(entry2.isDirectory())await detachCandidateLinks(path)}}function claimCandidateWorkspace(workspace,repository2,commit){const owner=owners.get(workspace);if(!owner||owner.running||workspace.repository!==resolve12(repository2)||workspace.commit!==commit)throw new Error("candidate workspace must be owned, sequential and bound to the same repository and SHA");owner.running=true;return()=>{owner.running=false}}function git2(cwd,args){return exec4("git",args,{cwd,shell:false,windowsHide:true,encoding:"utf8",timeout:3e5,env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/^(GIT_|NODE_OPTIONS$)/i.test(key)))})}var exec4,owners;var init_candidate_validation_session=__esm({"src/candidate-validation-session.ts"(){"use strict";exec4=promisify10(execFile10);owners=new WeakMap}});import{execFile as execFile11}from"node:child_process";import{constants}from"node:fs";import{access,lstat as lstat9,realpath as realpath9,stat as stat3}from"node:fs/promises";import{dirname as dirname7,isAbsolute as isAbsolute7,relative as relative8,resolve as resolve13}from"node:path";import{promisify as promisify11}from"node:util";async function validateIsolatedGitCandidate(input,workspace){if(workspace===void 0){const group=await withCandidateWorkspace(input.repository_path,input.commit_sha,owned=>validateIsolatedGitCandidate(input,owned));return{...group.value,timings_ms:{...group.value.timings_ms,preparation:group.preparation_ms,cleanup:group.cleanup_ms}}}const release=claimCandidateWorkspace(workspace,input.repository_path,input.commit_sha);try{return await validateInWorkspace(input,workspace.path)}finally{release()}}async function validateInWorkspace(input,worktree){const precheckStarted=performance.now();if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(input.commit_sha))throw new Error("candidate validation requires a full commit SHA");if(!isAbsolute7(input.executable_path))throw new Error("candidate validation requires an absolute executable path");if(!Array.isArray(input.args)||input.args.some(argument=>typeof argument!=="string"))throw new Error("candidate validation requires a JSON string array of arguments");const executable=resolve13(input.executable_path);const executableStat=await stat3(executable).catch(()=>null);if(executableStat===null||!executableStat.isFile())throw new Error("candidate validation executable path is not a file");await access(executable,constants.X_OK).catch(()=>{throw new Error("candidate validation executable path is not executable")});const repository2=resolve13(input.repository_path);const toolRelative=relative8(repository2,executable);if(toolRelative===""||!toolRelative.startsWith("..")&&!isAbsolute7(toolRelative))throw new Error("candidate validation requires an external toolchain executable, not a shared-checkout executable");const sourcePaths=[repository2.toLowerCase(),repository2.replaceAll("\\","/").toLowerCase()];if(input.args.some(argument=>sourcePaths.some(path=>argument.toLowerCase().includes(path))))throw new Error("candidate validation arguments must use candidate-relative paths, not shared-checkout paths");if(await realpath9(executable)!==await realpath9(process.execPath))throw new Error("candidate validation requires the current host Node runtime");const harness=input.args[0];if(!harness||harness.startsWith("-")||isAbsolute7(harness)||harness.includes("\\")||harness.includes(":")||harness.includes("\0")||harness.split("/").some(part=>["",".",".."].includes(part))||!/\.(?:c|m)?js$/.test(harness))throw new Error("candidate validation requires a committed relative Node harness; eval, loaders and inline code are not allowed");const commit=await gitOutput(repository2,["rev-parse",`${input.commit_sha}^{commit}`]);const entry2=await gitOutput(repository2,["--literal-pathspecs","ls-tree",commit,"--",harness]);const blob=entry2.match(/^100(?:644|755) blob ([a-f0-9]{40,64})\t/);if(!blob?.[1])throw new Error("candidate harness must be a committed regular file");const tree=await gitOutput(repository2,["rev-parse",`${commit}^{tree}`]);const timeout=input.timeout_ms??12e4;if(!Number.isInteger(timeout)||timeout<1||timeout>36e5)throw new Error("candidate validation timeout must be between 1 and 3600000 milliseconds");{const head=await gitOutput(worktree,["rev-parse","HEAD"]);const worktreeTree=await gitOutput(worktree,["rev-parse","HEAD^{tree}"]);if(head!==commit||worktreeTree!==tree)throw new Error("isolated worktree does not match requested candidate commit and tree");await assertClean(worktree,"before execution");let ancestor=resolve13(worktree,harness);while(ancestor!==worktree){if((await lstat9(ancestor)).isSymbolicLink())throw new Error("candidate harness cannot follow a symlink");ancestor=dirname7(ancestor)}const startedAt=new Date().toISOString();const precheckMs=performance.now()-precheckStarted;const processStarted=performance.now();const execution=await execute(executable,input.args,worktree,timeout);const processMs=Math.round(performance.now()-processStarted);const finishedAt=new Date().toISOString();const verificationStarted=performance.now();const cleanAfter=await isClean(worktree);const finalHead=await gitOutput(worktree,["rev-parse","HEAD"]);const finalTree=await gitOutput(worktree,["rev-parse","HEAD^{tree}"]);const candidateChanged=finalHead!==commit||finalTree!==tree;const diagnostic=candidateChanged?"candidate HEAD or tree changed during execution":!cleanAfter?"candidate has uncommitted changes after execution":execution.diagnostic;return{status:execution.exitCode===0&&cleanAfter&&!candidateChanged?"passed":"failed",command:JSON.stringify([executable,...input.args]),output:{stdout:safeOutput(execution.stdout),stderr:safeOutput(execution.stderr)},timings_ms:{process:processMs,verification:Math.round(precheckMs+performance.now()-verificationStarted)},candidate_execution:{kind:"isolated_git_worktree",protocol:"committed_node_harness_v1",harness_path:harness,harness_blob_sha:blob[1],commit_sha:commit,tree_sha:tree,exit_code:execution.exitCode,diagnostic,started_at:startedAt,finished_at:finishedAt}}}}function safeOutput(value){const redacted=redactSensitive(value);try{assertSafeRecordContent(redacted);return redacted}catch{return"[REDACTED: command output contained sensitive values]"}}async function assertClean(worktree,phase2){if(!await isClean(worktree))throw new Error(`isolated worktree is dirty ${phase2}`)}async function isClean(worktree){return await gitOutput(worktree,["status","--porcelain","--untracked-files=all"])===""}async function execute(executable,args,cwd,timeout){try{const output2=await execFileAsync7(executable,[...args],{cwd,shell:false,windowsHide:true,env:allowedExecutionEnvironment(),timeout,maxBuffer:1024*1024,encoding:"utf8"});return{exitCode:0,diagnostic:null,...output2}}catch(error51){const output2={stdout:error51!==null&&typeof error51==="object"&&"stdout"in error51?String(error51.stdout??"").slice(0,1024*1024):"",stderr:error51!==null&&typeof error51==="object"&&"stderr"in error51?String(error51.stderr??"").slice(0,1024*1024):""};if(isTimedOut(error51))return{exitCode:-1,diagnostic:"command timed out",...output2};if(hasExitCode(error51))return{exitCode:error51.code,diagnostic:`command exited with code ${error51.code}`,...output2};return{exitCode:-1,diagnostic:"command could not start",...output2}}}function allowedExecutionEnvironment(){return Object.fromEntries(executionEnvironmentKeys.flatMap(key=>{const value=process.env[key];return value===void 0?[]:[[key,value]]}))}function hasExitCode(error51){return error51!==null&&typeof error51==="object"&&"code"in error51&&typeof error51.code==="number"}function isTimedOut(error51){return error51!==null&&typeof error51==="object"&&("killed"in error51&&error51.killed===true||"signal"in error51&&error51.signal==="SIGTERM")}async function gitOutput(cwd,args){const{stdout}=await git3(cwd,args);return stdout.trim()}function git3(cwd,args){return execFileAsync7("git",[...args],{cwd,shell:false,windowsHide:true,encoding:"utf8",env:allowedExecutionEnvironment(),maxBuffer:10*1024*1024})}var execFileAsync7,executionEnvironmentKeys;var init_candidate_validation=__esm({"src/candidate-validation.ts"(){"use strict";init_src();init_candidate_validation_session();execFileAsync7=promisify11(execFile11);executionEnvironmentKeys=["APPDATA","COMSPEC","HOME","LANG","LOCALAPPDATA","LC_ALL","PATH","PATHEXT","Path","ProgramFiles","SYSTEMROOT","SystemRoot","TEMP","TMP","USERPROFILE","WINDIR"]}});import{execFile as execFile12}from"node:child_process";import{posix as posix8}from"node:path";import{promisify as promisify12}from"node:util";function ids(value,label){const values=value.split(",").map(item=>item.trim());if(values.length===0||values.some(item=>!item)||new Set(values).size!==values.length)throw new UsageError(`${label} requires unique nonempty ids`);return values}async function context(parsed,composition){if(parsed.options.task!==void 0||parsed.options.change!==void 0)throw new UsageError("--spec/--execution parental proof cannot include --task or --change");requireOptions(parsed.options,["spec","execution","run"]);const specId=parsed.options.spec;const executionId=parsed.options.execution;const runId=parsed.options.run;const[{spec},{execution},fold]=await Promise.all([composition.specs.read(specId),composition.executions.read(executionId),composition.runs.read(runId)]);if(execution.origin.type!=="spec"||execution.origin.spec_id!==specId||!["running","verifying"].includes(execution.status))throw new UsageError("Parental proof requires the active SPEC delivery Execution");const runs=await composition.runs.list();const byId2=new Map(runs.map(entry2=>[entry2.run.run_id,entry2]));let root=fold;const seen=new Set([runId]);while(root.run.parent_run_id!==null){if(seen.has(root.run.parent_run_id))throw new UsageError("Cyclic parental Run ancestry");seen.add(root.run.parent_run_id);const parent=byId2.get(root.run.parent_run_id);if(!parent||parent.run.execution_id!==executionId||parent.run.spec_id!==specId)throw new UsageError("Parental Run ancestry leaves the SPEC Execution");root=parent}if(fold.run.execution_id!==executionId||fold.run.spec_id!==specId||fold.run.task_id!==null||fold.run.change_id!==null||root.status!=="running"||root.run.task_id!==null||root.run.change_id!==null||root.run.execution_id!==executionId||root.run.spec_id!==specId||root.run.execution_kind!=="delivery"||root.run.entrypoint!=="spec"||root.run.agent!=="agent-orchestrator"||spec.status!=="active")throw new UsageError("Parental proof requires a linked active macro Run");const isRoot=runId===root.run.run_id&&fold.status==="running";const isReview2=fold.status==="completed"&&effectiveRunV2Role(fold.run)==="subagent"&&effectiveRunV2Purpose(fold.run)==="review"&&fold.run.agent==="agent-reviewer"&&descendant(runId,root.run.run_id,byId2);if(!isRoot&&!isReview2)throw new UsageError("Parental Run must be the active macro root or its completed reviewer descendant");return{spec,execution,fold,root,isReview:isReview2,directory:posix8.dirname(composition.executions.path(executionId))}}function descendant(runId,rootId,byId2){const seen=new Set;let parentId=byId2.get(runId)?.run.parent_run_id??null;while(parentId!==null&&!seen.has(parentId)){if(parentId===rootId)return true;seen.add(parentId);parentId=byId2.get(parentId)?.run.parent_run_id??null}return false}async function existingCommit(root,value){if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value))throw new UsageError("--commit requires a full lowercase Git SHA");try{const result2=await execFileAsync8("git",["rev-parse","--verify",`${value}^{commit}`],{cwd:root,shell:false,windowsHide:true,encoding:"utf8",timeout:15e3});if(result2.stdout.trim()!==value)throw new Error("noncanonical commit");return value}catch{throw new UsageError("--commit must resolve to an existing Git commit")}}async function runParentValidationCommand(action,parsed,filesystem,composition){if(action!=="execute"&&action!=="record")throw new UsageError("Unknown parental Validation action");assertSafeRecordContent(parsed.options);requireOptions(parsed.options,["id","acceptance","locators","commit","run","spec","execution",...action==="execute"?["executable","args"]:["outcome"]]);const owned=await context(parsed,composition);const acceptance=ids(parsed.options.acceptance,"--acceptance");if(acceptance.some(id2=>!owned.spec.acceptance_ids.includes(id2)))throw new UsageError("Parental Acceptance Criteria must belong to the SPEC");const kind=parsed.options.kind??"test";const prefix=prefixes[kind];if(!prefix||!parsed.options.id.startsWith(prefix)||!/^[A-Z0-9]+(?:-[A-Z0-9]+)*$/.test(parsed.options.id))throw new UsageError("Invalid parental Validation kind or id");if(owned.isReview!==reviewKinds.has(kind))throw new UsageError("Independent review must come from a completed reviewer child; execution uses the active macro root");if(action==="record"&&!owned.isReview)throw new UsageError("Parental implementation Validation requires isolated validation execute");if(action==="execute"&&owned.isReview)throw new UsageError("Reviews are recorded from reviewer results, not executed as commands");const commit=await existingCommit(filesystem.root,parsed.options.commit);const status=parsed.options.outcome??"passed";if(status!=="passed"&&status!=="failed")throw new UsageError("Parental outcome must be passed or failed");let observed=null;if(action==="execute"){let args;try{args=JSON.parse(parsed.options.args)}catch{throw new UsageError("--args requires a JSON string array")}if(!Array.isArray(args)||!args.every(item=>typeof item==="string"))throw new UsageError("--args requires a JSON string array");observed=await validateIsolatedGitCandidate({repository_path:filesystem.root,commit_sha:commit,executable_path:parsed.options.executable,args,...parsed.options["timeout-ms"]===void 0?{}:{timeout_ms:Number(parsed.options["timeout-ms"])}})}const id=parsed.options.id;const path=`${owned.directory}/artifacts/parent/tests/${id}.md`;const artifact=parentValidationArtifactV1Schema.parse({schema_version:3,scope:"spec_execution",id,kind,spec_id:owned.spec.id,execution_id:owned.execution.id,run_id:owned.fold.run.run_id,acceptance_ids:acceptance,executed_at:observed?.candidate_execution.finished_at??new Date().toISOString(),command:observed?.command??parsed.options.command??null,status:observed?.status??status,asserted_outcomes:ids(parsed.options["asserted-outcome"]??`validation ${status}`,"--asserted-outcome"),locators:ids(parsed.options.locators,"--locators"),author_id:parsed.options.author??owned.fold.run.agent,commit_sha:commit,...observed===null?{}:{candidate_execution:observed.candidate_execution},not_applicable_reason:null});if(owned.isReview&&artifact.author_id===owned.root.run.agent)throw new UsageError("Parental review author must differ from the macro author");if(artifact.author_id!==owned.fold.run.agent)throw new UsageError("Parental author must match the observed Run agent");await filesystem.writeTextAtomicExclusive(path,serializeMarkdown({metadata:artifact,body:`# Validation ${id}
3581
+ ${await context2.filesystem.readText(path)}`)}const resolved=candidates.find(document=>containsIdentifier(document,task.id));if(resolved===void 0){throw new LifecycleGateError(`Evidence does not resolve for Task ${task.id}: ${evidenceId2}`)}documents.push(resolved)}const evidence=documents.join("\n");const missing=task.acceptance_ids.filter(id=>!containsIdentifier(evidence,id));if(missing.length>0){throw new LifecycleGateError(`Task ${task.id} Evidence does not cover Acceptance Criteria: ${missing.join(", ")}`)}}async function assertTaskSixStageCoverage(context2,task,result2,executionId,enforceLegacyRiskCounts=true,requireDecision=true){const decisions=[...await context2.repositories.decisions.list({type:"change",id:task.change_id}),...await context2.repositories.decisions.list({type:"execution",id:executionId})];if(requireDecision&&decisions.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Decision for six-stage coverage`)}const changeDirectory=posix4.dirname(context2.layout.activePath("change",task.change_id));const verificationPaths=(await Promise.all(["tests","evals","checks"].map(kind=>context2.filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat();const relatedVerificationPaths=[];for(const path of verificationPaths){const content=await context2.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){relatedVerificationPaths.push(path)}}if(relatedVerificationPaths.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Test, Eval, or Check for six-stage coverage`)}const timestampedEvidence=[];for(const evidenceId2 of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId2}.md`;if(!await context2.filesystem.exists(path))continue;const content=await context2.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){timestampedEvidence.push(path)}}if(timestampedEvidence.length===0){throw new LifecycleGateError(`Task ${task.id} requires an Evidence file with the Task id and an ISO date-time for six-stage coverage`)}if(enforceLegacyRiskCounts){assertRiskScaledArtifactCounts(task.id,task.risk,relatedVerificationPaths.length,result2.evidence_ids.length)}}var init_lifecycle_evidence_v2=__esm({"src/lifecycle-evidence-v2.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function readRequiredRun(repositories,id){try{return await repositories.runs.read(id)}catch(error51){throw new LifecycleGateError(`Run ${id} does not resolve: ${error51 instanceof Error?error51.message:String(error51)}`)}}async function executionForTask(task,repositories){const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(canonicalExecutionId!==null){const{execution}=await repositories.executions.read(canonicalExecutionId);if(!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){throw new LifecycleGateError(`Execution ${canonicalExecutionId} does not contain Task/Change ${task.id}/${task.change_id}`)}return execution}const executions=(await repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id));if(executions.length!==1){throw new LifecycleGateError(`Task ${task.id} must resolve to exactly one Execution; found ${executions.length}`)}return executions[0]}async function executionForCompletionRun(task,canonicalExecution,run,repositories){if(run.run.execution_id===canonicalExecution.id)return canonicalExecution;if(run.run.continuation_of_run_id===null||run.run.execution_id===null){return canonicalExecution}const{execution}=await repositories.executions.read(run.run.execution_id);const ownsTask=execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id);if(execution.kind!=="delivery"||execution.origin.type!=="task"||execution.origin.task_id!==task.id||!ownsTask){throw new LifecycleGateError(`Continuation Run ${run.run.run_id} Execution ${execution.id} does not own Task/Change ${task.id}/${task.change_id}`)}return execution}function assertCompletedRunAttribution(run,task,executionId){if(run.finished?.status!=="completed"){throw new LifecycleGateError(`Run ${run.run.run_id} must be completed`)}assertRunAttribution(run,task,executionId)}function assertRunAttribution(run,task,executionId){const mismatches=[(run.records?.findLast(record3=>"phase"in record3)?.phase??run.run.phase)==="execution"||run.run.phase==="planning"&&run.run.work_type==="rework"?null:"phase",run.run.execution_id===executionId?null:"execution_id",run.run.task_id===task.id?null:"task_id",run.run.change_id===task.change_id?null:"change_id"].filter(value=>value!==null);if(mismatches.length>0){throw new LifecycleGateError(`Run ${run.run.run_id} attribution mismatch: ${mismatches.join(", ")}`)}}var init_lifecycle_run_attribution=__esm({"src/lifecycle-run-attribution.ts"(){"use strict";init_lifecycle_assurance_v2()}});async function validateRunV2Attribution(input,repositories,options={}){const entrypointId={observation:null,conversation:input.conversationId,task:input.taskId,spec:input.specId,prd:input.prdId}[input.entrypoint];if(entrypointId===void 0||entrypointId===null){throw new RunAttributionV2Error(`${input.entrypoint} entrypoint requires its scope id`)}if(input.entrypoint==="conversation"&&[input.taskId,input.specId,input.prdId,input.changeId].some(value=>value!==void 0&&value!==null)){throw new RunAttributionV2Error("Conversation entrypoint cannot claim a delivery lifecycle ancestor")}const execution=await optionalRead(input.executionId,"Execution",id=>repositories.executions.read(id));const task=await optionalRead(input.taskId,"Task",id=>repositories.tasks.read(id));const change=await optionalRead(input.changeId,"Change",id=>repositories.changes.read(id));const spec=await optionalRead(input.specId,"SPEC",id=>repositories.specs.read(id));await optionalRead(input.prdId,"PRD",id=>repositories.prds.read(id));if(input.phase==="execution"&&execution===null){throw new RunAttributionV2Error("Execution phase requires an existing Execution")}const macroTerminalSubRun=input.phase==="execution"&&execution?.execution.status==="completed"&&input.taskId==null&&input.parentRunId!=null&&["execution","review","finalization"].includes(input.runPurpose??"")&&await isDirectRunningMacroParent(input,repositories);if(input.phase==="execution"&&execution!==null&&!new Set(["running","verifying"]).has(execution.execution.status)&&!macroTerminalSubRun&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Execution ${execution.execution.id} is not running or verifying`)}if(task!==null){if(change!==null&&task.task.change_id!==change.change.id){throw new RunAttributionV2Error(`Task ${task.task.id} does not resolve to the attributed Change`)}if(input.phase==="execution"&&change===null){throw new RunAttributionV2Error(`Execution Run for Task ${task.task.id} requires its materialized Change`)}if(input.phase==="execution"&&execution===null){throw new RunAttributionV2Error(`Task ${task.task.id} attribution requires an Execution`)}if(input.phase==="execution"&&!new Set(["executing","verifying"]).has(task.task.status)&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Task ${task.task.id} is not executing or verifying`)}if(execution!==null&&execution.execution.origin.type!=="interaction"&&execution.execution.plan_hash!==null){const node=execution.execution.dag.nodes.find(candidate=>candidate.task_id===task.task.id);if(node===void 0||node.change_id!==task.task.change_id){throw new RunAttributionV2Error(`Execution ${execution.execution.id} does not own Task ${task.task.id} and Change ${task.task.change_id}`)}}}if(change!==null&&task===null&&execution!==null&&execution.execution.origin.type!=="interaction"&&execution.execution.plan_hash!==null){const ownsChange=execution.execution.dag.nodes.some(candidate=>candidate.change_id===change.change.id);if(!ownsChange){throw new RunAttributionV2Error(`Execution ${execution.execution.id} does not contain Change ${change.change.id}`)}}if(spec!==null&&input.prdId!==void 0&&input.prdId!==null&&spec.spec.prd_id!==input.prdId){throw new RunAttributionV2Error(`SPEC ${spec.spec.id} does not belong to PRD ${input.prdId}`)}if(execution!==null){const origin=execution.execution.origin;if(origin.type==="interaction"&&origin.conversation_id!==input.conversationId){throw new RunAttributionV2Error(`Interaction Execution ${execution.execution.id} belongs to another Conversation`)}if(origin.type==="spec"&&origin.spec_id!==input.specId){throw new RunAttributionV2Error(`Execution ${execution.execution.id} requires SPEC ${origin.spec_id}, not ${input.specId??"none"}`)}if(origin.type==="prd"&&origin.prd_id!==input.prdId){throw new RunAttributionV2Error(`Execution ${execution.execution.id} requires PRD ${origin.prd_id}, not ${input.prdId??"none"}`)}if(origin.type==="task"&&origin.task_id!==input.taskId){throw new RunAttributionV2Error(`Task-first Execution ${execution.execution.id} requires Task ${origin.task_id}, not ${input.taskId??"none"}`)}}if(change!==null){if(input.phase==="execution"&&!new Set(["executing","verifying"]).has(change.change.status)&&options.allowObservedHistoricalInvocation!==true){throw new RunAttributionV2Error(`Change ${change.change.id} is not executing or verifying`)}const source=change.change.source;if(source.type==="spec"&&input.specId!==source.spec_id){throw new RunAttributionV2Error(`Change ${change.change.id} belongs to SPEC ${source.spec_id}, not ${input.specId??"none"}`)}if(source.type==="prd"&&input.prdId!==source.prd_id){throw new RunAttributionV2Error(`Change ${change.change.id} belongs to PRD ${source.prd_id}, not ${input.prdId??"none"}`)}if(source.type==="task"&&task!==null&&source.task_id!==task.task.id){throw new RunAttributionV2Error(`Task-first Change ${change.change.id} belongs to ${source.task_id}, not ${task.task.id}`)}}for(const[relationship,relatedId]of[["parent",input.parentRunId],["continuation",input.continuationOfRunId],["retry",input.retryOfRunId]]){if(relatedId===void 0||relatedId===null)continue;const related=await requiredRead(relatedId,`${relationship} Run`,id=>repositories.runs.read(id));if(related.run.conversation_id!==input.conversationId){throw new RunAttributionV2Error(`${relationship} Run ${relatedId} belongs to another Conversation`)}if(relationship==="retry"&&related.run.task_id!==(input.taskId??null)){throw new RunAttributionV2Error(`Retry Run ${relatedId} belongs to another Task`)}}}async function isDirectRunningMacroParent(input,repositories){const parentId=input.parentRunId;if(parentId===null||parentId===void 0||input.executionId==null)return false;const parent=await requiredRead(parentId,"parent Run",id=>repositories.runs.read(id));const macroScopeMatches=input.specId!=null&&parent.run.spec_id===input.specId||input.prdId!=null&&parent.run.prd_id===input.prdId;return parent.status==="running"&&parent.run.parent_run_id===null&&parent.run.task_id===null&&parent.run.execution_id===input.executionId&&parent.run.conversation_id===input.conversationId&&macroScopeMatches}async function optionalRead(id,label,read){return id===void 0||id===null?null:requiredRead(id,label,read)}async function requiredRead(id,label,read){try{return await read(id)}catch(error51){throw new RunAttributionV2Error(`${label} does not resolve: ${id} (${error51 instanceof Error?error51.message:String(error51)})`)}}var RunAttributionV2Error;var init_attribution_v2=__esm({"src/attribution-v2.ts"(){"use strict";RunAttributionV2Error=class extends Error{name="RunAttributionV2Error"}}});import{createHash as createHash36}from"node:crypto";async function checkedImplementationProposal(filesystem,composition,current,inputPath){if(!inputPath.startsWith(".local/")||inputPath.includes("\\")||inputPath.split("/").some(part=>part===".."||part==="."||part===""))throw new UsageError("Implementation proposal must be a canonical .local/ path");const proposal=specImplementationV2Schema.parse(JSON.parse(await filesystem.readText(inputPath)));return checkedImplementationValue(filesystem,composition,current,proposal)}async function checkedImplementationValue(filesystem,composition,current,proposal){if(current.implementation===null)throw new UsageError("SPEC has no implementation snapshot");const original=current.implementation;if(proposal.stack_profile!==original.stack_profile||JSON.stringify(proposal.stack_overrides)!==JSON.stringify(original.stack_overrides)||proposal.stack_components.length!==original.stack_components.length)throw new UsageError("Implementation proposal changes profile, overrides or component count");let changes=0;let expectedDescription=original.stack_description;for(let index=0;index<original.stack_components.length;index+=1){const before=original.stack_components[index];const after=proposal.stack_components[index];if(before.name!==after.name||before.kind!==after.kind||before.version_source!==after.version_source)throw new UsageError("Implementation proposal changes component identity or version source");if(before.version===after.version)continue;changes++;const source=JSON.parse(await filesystem.readText(before.version_source));if(before.name!=="pnpm"||before.version_source!=="package.json"||source.packageManager!==`pnpm@${after.version}`)throw new UsageError("Changed version is not the exact packageManager from package.json");const label=`${before.name} ${before.version}`;if(expectedDescription.split(label).length!==2)throw new UsageError("Old version must occur exactly once in stack description");expectedDescription=expectedDescription.replace(label,`${after.name} ${after.version}`)}if(changes!==1||proposal.stack_description!==expectedDescription)throw new UsageError("Only one sourced version and its exact description may change");await assertSpecImplementationMatchesProject(proposal,filesystem,composition.layout);return{implementation:proposal,deltaSha256:digest6(JSON.stringify({spec_id:current.id,previous_revision:current.revision,previous_implementation:original,next_implementation:proposal}))}}function revisedSpecSource(current,originalSource,implementation,attribution2){if(current.implementation===null||current.plan_ref===null||!["ready","blocked","active"].includes(current.status))throw new UsageError("SPEC has no recoverable materialized implementation");const next=deliverySpecV2Schema.parse({...current,revision:current.revision+1,implementation,implementation_revisions:[...current.implementation_revisions??[],{previous_revision:current.revision,previous_implementation:current.implementation,actor_task_id:attribution2.actorTaskId||null,actor_execution_id:attribution2.actorExecutionId,actor_run_id:attribution2.actorRunId,decision_id:attribution2.decisionId,delta_sha256:attribution2.deltaSha256,revised_at:attribution2.revisedAt}],updated_at:attribution2.revisedAt});const oldHeader=/^---\r?\n[\s\S]*?\r?\n---(?=\r?\n)/.exec(originalSource)?.[0];const newHeader=/^---\n[\s\S]*?\n---/.exec(serializeMarkdown({metadata:next,body:""}))?.[0];if(!oldHeader||!newHeader)throw new UsageError("SPEC frontmatter cannot be revised safely");return`${newHeader}${originalSource.slice(oldHeader.length)}`}function parseRevisedSpec(source){return parseMarkdown(source,deliverySpecV2Schema).metadata}var digest6;var init_controlled_recovery_snapshot=__esm({"src/controlled-recovery-snapshot.ts"(){"use strict";init_src();init_src6();init_cli_arguments();digest6=value=>createHash36("sha256").update(value).digest("hex")}});import{createHash as createHash37}from"node:crypto";async function readReleaseCycle(filesystem){if(!await filesystem.exists(RELEASE_CYCLE_PATH))return null;let value;try{value=JSON.parse(await filesystem.readText(RELEASE_CYCLE_PATH))}catch{throw new UsageError("Release cycle configuration is invalid")}if(value.schema_version!==1||!releaseId.test(value.current_release??"")||!["open","frozen"].includes(value.state??""))throw new UsageError("Release cycle configuration must define schema 1, current_release and state");if(value.recovery_grant!==void 0){const grant=value.recovery_grant;if(grant===null||typeof grant!=="object"||value.state!=="open"||grant.schema_version!==1||!grant.target_task_id?.startsWith("TASK-")||!grant.target_spec_id?.startsWith("SPEC-")||!grant.target_execution_id?.startsWith("EXEC-")||grant.target_release!==value.current_release||!Number.isSafeInteger(grant.expected_task_revision)||grant.expected_task_revision<1||!grant.actor_run_id?.startsWith("RUN-")||!grant.decision_id?.startsWith("DEC-HUMAN-")||!Number.isFinite(Date.parse(grant.prepared_at)))throw new UsageError("Release recovery grant is invalid")}return value}async function assertCurrentReleaseForExecution(filesystem,targetRelease,label){const cycle=await readReleaseCycle(filesystem);if(cycle===null){if(targetRelease)throw new UsageError("Named release requires configured current release");return}if(cycle.state!=="open")throw new UsageError(`Current release ${cycle.current_release} is frozen; ${label} cannot start`);if(cycle.recovery_grant!==void 0)throw new UsageError(`Release ${cycle.current_release} is reserved for recovery of ${cycle.recovery_grant.target_task_id}`);if(targetRelease===null||targetRelease===void 0)throw new UsageError(`${label} has no target release; assign the current release before execution`);if(targetRelease!==cycle.current_release)throw new UsageError(`${label} targets release ${targetRelease}; only current release ${cycle.current_release} may become ready or execute`)}async function releaseTargetForDraft(filesystem,requested){const cycle=await readReleaseCycle(filesystem);if(requested!==void 0&&!releaseId.test(requested))throw new UsageError("Target release must use major.minor, for example 4.6");if(requested!==void 0&&cycle!==null){const[major=0,minor=0]=requested.split(".").map(Number);const[currentMajor=0,currentMinor=0]=cycle.current_release.split(".").map(Number);if(major<currentMajor||major===currentMajor&&minor<currentMinor)throw new UsageError("A new draft cannot target a release older than the current release")}return requested??cycle?.current_release??null}async function taskFirstRelease(filesystem,requested){const target=await releaseTargetForDraft(filesystem,requested);await assertCurrentReleaseForExecution(filesystem,target,"Task-first work");return target}async function assertTaskStartRelease(filesystem,repositories,id){const{task}=await repositories.tasks.read(id);if(["executing","verifying"].includes(task.status))return;const cycle=await readReleaseCycle(filesystem);if(cycle?.recovery_grant!==void 0){const grant=cycle.recovery_grant;if(id!==grant.target_task_id)throw new UsageError("Only the exact blocked recovery Task may resume while grant is active");const execution=await executionForTask(task,repositories);const specTarget=execution.origin.type==="spec"?(await repositories.specs.read(execution.origin.spec_id)).spec.target_release:null;if(task.status!=="blocked"||task.revision!==grant.expected_task_revision||specTarget!==grant.target_release||(task.target_release??specTarget)!==grant.target_release||execution.id!==grant.target_execution_id||execution.origin.type!=="spec"||execution.origin.spec_id!==grant.target_spec_id)throw new UsageError("Only the exact blocked recovery Task may resume while grant is active");return}const target=await effectiveTaskRelease(task,repositories);await assertCurrentReleaseForExecution(filesystem,target,"Task")}async function effectiveTaskRelease(task,repositories){if(task.target_release!=null)return task.target_release;const execution=await executionForTask(task,repositories);return execution.origin.type==="prd"?(await repositories.prds.read(execution.origin.prd_id)).prd.target_release:execution.origin.type==="spec"?(await repositories.specs.read(execution.origin.spec_id)).spec.target_release:null}async function assertPostPublicationTaskStartRelease(filesystem,repositories,id,authorization){const{task}=await repositories.tasks.read(id);if(task.status!=="blocked"||id!==authorization.targetTaskId||await effectiveTaskRelease(task,repositories)!==authorization.targetRelease)throw new UsageError("Post-publication closure authorizes only the exact blocked Task");const source=await filesystem.readText(RELEASE_CYCLE_PATH);const cycle=await readReleaseCycle(filesystem);const raw=JSON.parse(source);const publishedRows=raw.history?.filter(row=>row.from===authorization.targetRelease)??[];if(cycle?.state!=="open"||cycle.recovery_grant!==void 0||publishedRows.length!==1||publishedRows[0]?.sha!==authorization.publishedSha||createHash37("sha256").update(source).digest("hex")!==authorization.cycleSha256)throw new UsageError("Post-publication cycle authorization changed")}var RELEASE_CYCLE_PATH,releaseId;var init_release_cycle=__esm({"src/release-cycle.ts"(){"use strict";init_cli_arguments();init_lifecycle_run_attribution();RELEASE_CYCLE_PATH=".agents/config/release-cycle.json";releaseId=/^(?:[1-9]\d*)\.(?:0|[1-9]\d*)$/}});import{createHash as createHash38,randomUUID as randomUUID5}from"node:crypto";import{lstat as lstat7,readFile as readFile8,realpath as realpath7,rename as rename5,unlink as unlink2}from"node:fs/promises";import{homedir as homedir3}from"node:os";import{resolve as resolve11}from"node:path";async function resolveRunClientInvocation(filesystem,client,options={}){if(!new Set(["codex","codex-desktop"]).has(client)){return{clientThreadId:null,clientTurnId:null,userMessage:null,observedModel:null,observedReasoningEffort:null,observedServiceTier:null}}const argv=options.argv??process.argv.slice(2);const hookFlags=argv.filter(value=>value.startsWith("--codex-hook-"));const hooked=hookFlags.length>0;const hookThreads=hookFlags.filter(value=>value.startsWith("--codex-hook-thread="));const hookThread=hookThreads[0]?.slice("--codex-hook-thread=".length);const explicitThread=normalizedId(options.threadId??process.env.CODEX_THREAD_ID);if(hooked&&(hookFlags.length!==2||hookThreads.length!==1||!hookThread||!/^[A-Za-z0-9_-]{1,256}$/.test(hookThread)||explicitThread!==null&&explicitThread!==hookThread)){throw new Error("Codex hook identity is incomplete or conflicts with the active thread.")}const threadId=explicitThread??hookThread??null;const explicitTurn=normalizedId(options.turnId??process.env.CODEX_TURN_ID);const hookTurn=hooked&&threadId!==null?await observedHookTurn(filesystem.root,threadId,argv,options.now??new Date):null;if(hooked&&(hookTurn===null||explicitTurn!==null&&explicitTurn!==hookTurn)){throw new Error("Codex hook turn receipt is missing, consumed, expired or conflicts with the active turn.")}const turnId=hooked?hookTurn:explicitTurn;const transcriptPath=transcriptPathFromEnvironment();const active=await findActiveCodexInvocation(filesystem.root,{threadId,...transcriptPath===null?{}:{transcriptPath},...options.sessionsRoot===void 0?{}:{sessionsRoot:options.sessionsRoot},...options.now===void 0?{}:{now:options.now}});const matchingActive=turnId===null||active?.turnId===turnId?active:null;return{clientThreadId:threadId??matchingActive?.sessionId??null,clientTurnId:turnId??active?.turnId??null,userMessage:matchingActive?.userMessage??null,observedModel:matchingActive?.model??null,observedReasoningEffort:matchingActive?.reasoningEffort??null,observedServiceTier:matchingActive?.serviceTier??null,transcriptPath:transcriptPath??(matchingActive?resolve11(options.sessionsRoot??resolve11(homedir3(),".codex"),matchingActive.sessionPath):null)}}async function observedHookTurn(root,threadId,argv,now){const hookIds=argv.filter(value=>value.startsWith("--codex-hook-id="));if(hookIds.length!==1)return null;const hookId=hookIds[0]?.slice("--codex-hook-id=".length);if(!hookId||!/^[a-f0-9]{64}$/.test(hookId))return null;const originalArgv=argv.filter(value=>!value.startsWith("--codex-hook-"));const argvSha256=createHash38("sha256").update(JSON.stringify(originalArgv)).digest("hex");const path=resolve11(root,".local/codex-hook-turn/v1",`${hookId}.json`);const claimed=`${path}.${randomUUID5()}.consumed`;try{await rename5(path,claimed);const info=await lstat7(claimed);if(!info.isFile()||info.isSymbolicLink()||info.size>2048)return null;if((await realpath7(claimed)).toLowerCase()!==claimed.toLowerCase())return null;const receipt=JSON.parse(await readFile8(claimed,"utf8"));const age=now.getTime()-Number(receipt.observed_at_ms);if(receipt.schema_version!==1||receipt.thread_id!==threadId||typeof receipt.turn_id!=="string"||!receipt.turn_id||receipt.turn_id.length>256||receipt.tool_use_sha256!==hookId||receipt.argv_sha256!==argvSha256||!Number.isFinite(age)||age<-5e3||age>6e4)return null;return receipt.turn_id}catch{return null}finally{await unlink2(claimed).catch(()=>void 0)}}function transcriptPathFromEnvironment(){const value=process.env.CODEX_TRANSCRIPT_PATH?.trim();return value===void 0||value.length===0||value.length>4096?null:value}function normalizedId(value){const normalized=value?.trim();return normalized===void 0||normalized.length===0?null:normalized}var init_run_client_invocation=__esm({"src/run-client-invocation.ts"(){"use strict";init_src4()}});function activeDescendantRuns(rootRunId,candidates){return descendantRuns(rootRunId,candidates).filter(candidate=>candidate.finished===null)}function descendantRuns(rootRunId,candidates){const descendants=[];const parentIds=new Set([rootRunId]);let discovered=true;while(discovered){discovered=false;for(const candidate of candidates){if(candidate.run.parent_run_id!==null&&parentIds.has(candidate.run.parent_run_id)&&!parentIds.has(candidate.run.run_id)){parentIds.add(candidate.run.run_id);descendants.push(candidate);discovered=true}}}return descendants}var init_run_hierarchy=__esm({"src/run-hierarchy.ts"(){"use strict"}});async function recoveryContext(filesystem,composition,actorTaskId,actorRunId,targetTaskId,actorExecutionId,observe=resolveRunClientInvocation,mode="current-release"){const[actorRecord,actorRun,{task:target},cycle]=await Promise.all([actorTaskId?composition.tasks.read(actorTaskId):Promise.resolve(null),composition.runs.read(actorRunId),composition.tasks.read(targetTaskId),readReleaseCycle(filesystem)]);const actor=actorRecord?.task??null;if((mode==="post-publication-consume"||mode==="post-publication-consume-partial"?actorRun.finished?.status!=="completed"||actorRun.finalization_decision?.outcome!=="completed":actorRun.status!=="running"||actorRun.finalization_decision!==null)||actorRun.run.agent!=="agent-orchestrator"||actorRun.run.run_role!=="orchestrator"||actorRun.run.parent_run_id!==null)throw new UsageError("Recovery requires an active observed root orchestrator");if(mode!=="post-publication-consume"&&mode!=="post-publication-consume-partial"){const invocation2=await observe(filesystem,actorRun.run.client);if(!invocation2.clientThreadId||!invocation2.clientTurnId||invocation2.clientThreadId!==actorRun.run.client_thread_id||invocation2.clientTurnId!==actorRun.run.client_turn_id)throw new UsageError("Recovery Run does not match the observed client turn")}if(actor!==null){if(actor.id===target.id||actor.status!==(mode==="post-publication-consume"||mode==="post-publication-consume-partial"?"completed":"executing")||actorRun.run.task_id!==actor.id||actorRun.run.change_id!==actor.change_id||actorRun.run.execution_kind!=="delivery")throw new UsageError("Recovery maintenance Task has wrong owner or state");const actorExecution=await executionForTask(actor,composition);if(actorRun.run.execution_id!==actorExecution.id||actorExecution.id!==actorExecutionId)throw new UsageError("Maintenance Run is not attributed to its Execution")}else{const{execution:interaction}=await composition.executions.read(actorExecutionId);if(actorRun.run.task_id!==null||actorRun.run.change_id!==null||actorRun.run.execution_id!==interaction.id||actorRun.run.execution_kind!=="interaction"||actorRun.run.entrypoint!=="conversation"||interaction.kind!=="interaction"||interaction.status!=="running")throw new UsageError("Taskless recovery requires the exact active interaction Execution root")}if(target.status!=="blocked"&&!(mode==="post-publication-consume-partial"&&target.status==="executing"))throw new UsageError("Recovery target must remain blocked");const execution=await executionForTask(target,composition);const{change}=await composition.changes.read(target.change_id);const taskFirst=mode!=="current-release"&&execution.origin.type==="task"&&execution.origin.task_id===target.id&&change.source.type==="task"&&change.source.task_id===target.id&&execution.dag.nodes.length===1&&execution.dag.nodes[0]?.task_id===target.id&&execution.dag.nodes[0]?.change_id===change.id;const specOrigin=execution.origin.type==="spec"&&change.source.type==="spec"&&change.source.spec_id===execution.origin.spec_id;if(!taskFirst&&!specOrigin||!["blocked","executing"].includes(change.status)||!["blocked","running"].includes(execution.status))throw new UsageError("Recovery target is not an exact blocked delivery DAG");const spec=execution.origin.type==="spec"?(await composition.specs.read(execution.origin.spec_id)).spec:null;const effectiveTargetRelease=target.target_release??spec?.target_release??null;const history=JSON.parse(await filesystem.readText(".agents/config/release-cycle.json"));const lastAdvance=history.history?.at(-1);const actorReleaseMatches=actor!==null&&(actor.target_release===cycle?.current_release||mode!=="current-release"&&lastAdvance?.from===actor.target_release&&lastAdvance?.to===cycle?.current_release);if(spec!==null&&(spec.plan_ref===null||spec.plan_ref.execution_id!==execution.id||!["blocked","ready","active"].includes(spec.status)||effectiveTargetRelease!==spec.target_release)||effectiveTargetRelease===null||mode==="current-release"&&cycle?.current_release!==effectiveTargetRelease||mode==="current-release"&&actor!==null&&actor.target_release!==effectiveTargetRelease||mode!=="current-release"&&(actor===null||cycle?.state!=="open"||!actorReleaseMatches))throw new UsageError("Recovery ancestry or current release does not match exactly");const allRuns=await composition.runs.list();if(allRuns.some(run=>run.run.task_id===target.id&&run.status==="running"))throw new UsageError("Recovery target still has an active owner Run");if(activeDescendantRuns(actorRun.run.run_id,allRuns).some(run=>run.run.task_id===target.id))throw new UsageError("Recovery target is an active descendant of maintenance");for(const dependencyId of target.depends_on){if((await composition.tasks.read(dependencyId)).task.status!=="completed")throw new UsageError(`Recovery dependency is not completed: ${dependencyId}`)}return{actorTaskId:actor?.id??"",actorExecutionId,actorRunId,decisionScopeType:actor===null?"execution":"change",decisionScopeId:actor===null?actorExecutionId:actor.change_id,targetTaskId:target.id,targetSpecId:spec?.id??null,targetExecutionId:execution.id,targetRelease:effectiveTargetRelease,targetTaskRevision:target.revision,targetChangeId:change.id,targetChangeRevision:change.revision,targetChangeStatus:change.status,targetSpecRevision:spec?.revision??null,targetSpecStatus:spec?.status??null,targetExecutionRevision:execution.revision,targetExecutionStatus:execution.status,stateSha256:digest6(JSON.stringify({task:[target.id,target.revision,target.status,target.plan_hash],change:[change.id,change.revision,change.status],execution:[execution.id,execution.revision,execution.status,execution.plan_hash],spec:spec===null?null:[spec.id,spec.revision,spec.status,spec.plan_ref?.hash],cycle}))}}async function assertRecoveryDecision(composition,scopeType,scopeId,decisionId,payload){const decision=await composition.decisions.read(scopeType,scopeId,decisionId);if(decision.origin!=="human"||decision.confirmed_at===null||Date.parse(decision.confirmed_at)>Date.now()||decision.category!=="contract")throw new UsageError("Recovery requires a confirmed human contract Decision");let actual;try{actual=JSON.parse(decision.decision)}catch{throw new UsageError("Recovery Decision must contain the exact JSON authorization payload")}if(actual===null||typeof actual!=="object"||Array.isArray(actual))throw new UsageError("Recovery Decision payload is not an object");const values=actual;const expectedKeys=Object.keys(payload).sort();if(JSON.stringify(Object.keys(values).sort())!==JSON.stringify(expectedKeys)||expectedKeys.some(key=>values[key]!==payload[key]))throw new UsageError("Recovery Decision does not authorize this exact actor, target, revision and digest")}var init_controlled_recovery_authority=__esm({"src/controlled-recovery-authority.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_snapshot();init_lifecycle_run_attribution();init_release_cycle();init_run_client_invocation();init_run_hierarchy()}});function publishedHistoryRow(cycle,release){if(cycle.schema_version!==1||cycle.state!=="open"||!Array.isArray(cycle.history))return null;const history=cycle.history;const matches=history.map((row,index2)=>row?.from===release?index2:-1).filter(index2=>index2>=0);if(matches.length!==1)return null;const index=matches[0];if(index===void 0)return null;if(history[index]?.kind==="planned-major-retarget")return null;let current=release;const seen=new Set;for(const row of history.slice(index)){if(!row||row.from!==current||seen.has(current)||typeof row.to!=="string"||!/^\d+\.\d+$/.test(row.to))return null;const[major=NaN,minor=NaN]=current.split(".").map(Number);const[nextMajor=NaN,nextMinor=NaN]=row.to.split(".").map(Number);if(!(nextMajor>major||nextMajor===major&&nextMinor>minor))return null;if(row.kind==="planned-major-retarget"){if(nextMajor!==major+1||nextMinor!==0||typeof row.task_id!=="string"||!row.task_id.startsWith("TASK-")||typeof row.run_id!=="string"||!row.run_id.startsWith("RUN-")||typeof row.decision_id!=="string"||!row.decision_id.startsWith("DEC-HUMAN-")||typeof row.authorization_sha256!=="string"||!/^[a-f0-9]{64}$/.test(row.authorization_sha256)||typeof row.occurred_at!=="string"||!Number.isFinite(Date.parse(row.occurred_at))||!Number.isSafeInteger(row.expected_revision)||Number(row.expected_revision)<1||row.sha!==void 0||row.ci_run_id!==void 0||row.release_url!==void 0)return null}else if(row.kind!==void 0||typeof row.sha!=="string"||!/^[a-f0-9]{40}$/.test(row.sha)||!Number.isSafeInteger(row.ci_run_id)||Number(row.ci_run_id)<1||row.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${current}`)return null;seen.add(current);current=row.to}return current===cycle.current_release?history[index]??null:null}var init_post_publication_cycle=__esm({"src/post-publication-cycle.ts"(){"use strict"}});function successfulRun(run,id,sha5,path){return run.id===id&&run.head_sha===sha5&&run.conclusion==="success"&&run.status==="completed"&&run.path===path&&run.repository?.full_name==="zaip-ai/zaip-aios"}function verifiedPublicationRun(input){const{row,candidate,published,publication,publishRunId,recoveryCi}=input;const repaired=Object.keys(row).some(key=>key.startsWith("publisher_recovery_"));if(!repaired)return successfulRun(publication,publishRunId,published,".github/workflows/publish-cli.yml")&&publication.event==="release"&&publication.head_branch===`v${row.from}`;return row.publisher_recovery_sha===candidate&&candidate!==published&&recoveryCi!==void 0&&Number.isSafeInteger(row.publisher_recovery_ci_run_id)&&Number(row.publisher_recovery_ci_run_id)>0&&[".github/workflows/pre-main-candidate.yml",".github/workflows/pre-main-candidate.yml@refs/heads/main"].some(path=>successfulRun(recoveryCi,row.publisher_recovery_ci_run_id,candidate,path))&&recoveryCi.event==="push"&&recoveryCi.head_branch==="main"&&successfulRun(publication,publishRunId,candidate,".github/workflows/publish-cli.yml")&&publication.event==="workflow_dispatch"&&publication.head_branch==="main"}var init_post_publication_publisher=__esm({"src/post-publication-publisher.ts"(){"use strict"}});import{execFile as execFile8}from"node:child_process";import{createHash as createHash39}from"node:crypto";import{posix as posix5}from"node:path";import{promisify as promisify8}from"node:util";async function publishedClosureProof(filesystem,composition,task,evidenceIds,run=query,snapshot){if(evidenceIds.length===0||new Set(evidenceIds).size!==evidenceIds.length)throw new UsageError("Post-publication closure requires exact, unique Evidence IDs");const cycleSource=await filesystem.readText(cyclePath2);let cycle;try{cycle=JSON.parse(cycleSource)}catch{throw new UsageError("Post-publication release cycle is invalid")}const from=await effectiveTaskRelease(task,composition);const row=typeof from==="string"?publishedHistoryRow(cycle,from):null;if(cycle.schema_version!==1||cycle.state!=="open"||typeof cycle.current_release!=="string"||typeof from!=="string"||row===null||row.from!==from||typeof row.to!=="string"||typeof row.sha!=="string"||!/^[a-f0-9]{40}$/.test(row.sha)||!Number.isSafeInteger(row.ci_run_id)||Number(row.ci_run_id)<=0||row.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${from}`)throw new UsageError("Post-publication cycle does not have the exact published Task advance");const bundle=await readAssuranceBundle(filesystem,composition.layout,[task],evidenceIds);if(bundle.evidences.length!==evidenceIds.length)throw new UsageError("Post-publication Evidence selection is incomplete");const changeDirectory=posix5.dirname(composition.layout.activePath("change",task.change_id));const proofPaths=Array.isArray(snapshot)?snapshot.map(([path])=>path):(await Promise.all(["tests","evals","checks","evidence","observations"].map(kind=>filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat().sort();const proofContents=await Promise.all(proofPaths.map(async path=>[path,createHash39("sha256").update(await filesystem.readText(path)).digest("hex")]));const proofContentSha256=createHash39("sha256").update(JSON.stringify(proofContents)).digest("hex");const candidates=[...new Set([...bundle.validations,...bundle.evidences].map(item=>item.commit_sha))];const historicalCandidate=candidates.length===1&&typeof candidates[0]==="string"?candidates[0]:null;if(!historicalCandidate)throw new UsageError("Historical proof requires one exact candidate");const candidate=await requireFinalProductCandidate(filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,[cyclePath2],{target_task_id:task.id,target_spec_id:null,candidate_sha:historicalCandidate,published_sha:row.sha,evidence_ids:evidenceIds});const git8=args=>run("git",args,filesystem.root);let frozen;try{frozen=JSON.parse(await git8(["show",`${candidate}:${cyclePath2}`]))}catch{throw new UsageError("Validated candidate has no frozen release cycle")}if(frozen.state!=="frozen"||frozen.current_release!==from||frozen.release_task_id!==task.id)throw new UsageError("Validated candidate is not frozen for the exact release Task");const published=row.sha;const ci=Number(row.ci_run_id);const version2=`${from}.0`;let publishRunId=null;for(const path of proofPaths.filter(item=>item.includes("/artifacts/observations/"))){try{const observation=parseMarkdown(await filesystem.readText(path),evidenceObservationV1Schema).metadata;const match=/^github-actions-(\d+)-attempt-\d+\/npm-registry$/.exec(observation.environment.id??"");if(observation.task_id===task.id&&observation.change_id===task.change_id&&observation.state==="confirmed"&&observation.environment.class==="published-package"&&observation.environment.version===`@zaip-ai/cli@${version2}`&&observation.candidate_version===version2&&observation.commit_sha===candidate&&observation.correlation_ids.includes(published)&&match&&observation.correlation_ids.includes(match[1]??"")&&observation.locators.includes(`https://github.com/zaip-ai/zaip-aios/actions/runs/${match[1]}`)){publishRunId=Number(match[1]);break}}catch{}}if(publishRunId===null)throw new UsageError("Canonical published-package observation is unavailable");let npmIntegrity="";let releaseAssetDigest="";let releaseAssetsSha256="";try{const remote=await git8(["remote","get-url","origin"]);if(!/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)zaip-ai\/zaip-aios(?:\.git)?\/?$/.test(remote))throw new Error("origin identity differs");const refs=await git8(["ls-remote","origin","refs/heads/main",`refs/tags/v${from}`,`refs/tags/v${from}^{}`]);const lines2=new Map(refs.split(/\r?\n/).filter(Boolean).map(line=>{const[sha5,ref]=line.split(/\s+/);return[ref,sha5]}));if(!/^[a-f0-9]{40}$/.test(lines2.get("refs/heads/main")??"")||(lines2.get(`refs/tags/v${from}^{}`)??lines2.get(`refs/tags/v${from}`))!==published)throw new Error("remote refs differ");await git8(["merge-base","--is-ancestor",published,lines2.get("refs/heads/main")]);const release=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/releases/tags/v${from}`],filesystem.root));const workflow=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${ci}`],filesystem.root));const publication=JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${publishRunId}`],filesystem.root));const recoveryCi=row.publisher_recovery_sha===candidate?JSON.parse(await run("gh",["api",`repos/zaip-ai/zaip-aios/actions/runs/${row.publisher_recovery_ci_run_id}`],filesystem.root)):void 0;const registry2=JSON.parse(await run("registry-metadata",[`https://registry.npmjs.org/@zaip-ai%2fcli/${version2}`],filesystem.root));const dist=registry2.dist;const assets=release.assets;const requiredNames=["local-release-receipt.json","release-manifest.json","sbom.cdx.json",`zaip-ai-cli-${version2}.tgz`].sort();if(!Array.isArray(assets))throw new Error("Release assets unavailable");const inventory3=requiredNames.map(name=>{const matches=assets.filter(item2=>item2.name===name);const item=matches[0];if(matches.length!==1||!item||!Number.isSafeInteger(item.id)||Number(item.id)<1||!Number.isSafeInteger(item.size)||Number(item.size)<1||typeof item.digest!=="string"||!/^sha256:[a-f0-9]{64}$/.test(item.digest))throw new Error("Required release asset missing or invalid");return{name,id:item.id,size:item.size,digest:item.digest}});releaseAssetsSha256=createHash39("sha256").update(JSON.stringify(inventory3)).digest("hex");const asset=assets.find(item=>item.name===`zaip-ai-cli-${version2}.tgz`);const tarball=JSON.parse(await run("registry-tarball",[`https://registry.npmjs.org/@zaip-ai/cli/-/cli-${version2}.tgz`],filesystem.root));if(release.draft!==false||typeof release.published_at!=="string"||release.target_commitish!==published||workflow.id!==ci||workflow.head_sha!==published||workflow.conclusion!=="success"||workflow.status!=="completed"||workflow.event!=="push"||workflow.head_branch!=="main"||workflow.path!==".github/workflows/pre-main-candidate.yml"||workflow.repository?.full_name!=="zaip-ai/zaip-aios"||!verifiedPublicationRun({row,candidate,published,publication,publishRunId,recoveryCi})||registry2.version!==version2||dist?.tarball!==`https://registry.npmjs.org/@zaip-ai/cli/-/cli-${version2}.tgz`||typeof dist.integrity!=="string"||!/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(dist.integrity)||!asset||typeof asset.digest!=="string"||!/^sha256:[a-f0-9]{64}$/.test(asset.digest)||!Number.isSafeInteger(asset.size)||Number(asset.size)<1||tarball.sha256!==asset.digest||tarball.integrity!==dist.integrity||tarball.size!==asset.size)throw new Error("remote publication proof differs");npmIntegrity=dist.integrity;releaseAssetDigest=asset.digest}catch{throw new UsageError("Exact remote main, tag, Release, CI, npm and publication Actions proof is unavailable or mismatched")}return{candidate_sha:candidate,published_sha:published,ci_run_id:ci,release_url:row.release_url,cycle_sha256:createHash39("sha256").update(cycleSource).digest("hex"),proof_content_sha256:proofContentSha256,...snapshot!==void 0?{proof_inventory:proofContents}:{},npm_integrity:npmIntegrity,publish_run_id:publishRunId,release_asset_digest:releaseAssetDigest,release_assets_sha256:releaseAssetsSha256,evidence_ids:[...evidenceIds]}}var exec2,cyclePath2,query;var init_post_publication_proof=__esm({"src/post-publication-proof.ts"(){"use strict";init_src();init_assurance();init_cli_arguments();init_lifecycle_assurance_v2();init_post_publication_cycle();init_post_publication_publisher();init_release_cycle();exec2=promisify8(execFile8);cyclePath2=".agents/config/release-cycle.json";query=async(command2,args,root)=>{if(command2==="registry-metadata"){const url2=args[0];if(!url2||!/^https:\/\/registry\.npmjs\.org\/(?:@zaip-ai%2[fF]cli\/\d+\.\d+\.\d+|-\/package\/@zaip-ai%2[fF]cli\/dist-tags)$/.test(url2))throw new Error("Registry metadata URL is not exact");const response=await fetch(url2,{redirect:"error",signal:AbortSignal.timeout(3e4)});if(!response.ok||!response.body||!response.headers.get("content-type")?.includes("json"))throw new Error("Registry metadata is unavailable");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.byteLength;if(size>2*1024*1024)throw new Error("Registry metadata exceeds proof limit");chunks.push(chunk)}return Buffer.concat(chunks).toString("utf8")}if(command2==="registry-tarball"){const url2=args[0];if(!url2||!/^https:\/\/registry\.npmjs\.org\/@zaip-ai\/cli\/-\/cli-\d+\.\d+\.\d+\.tgz$/.test(url2))throw new Error("Registry tarball URL is not exact");const response=await fetch(url2,{redirect:"error",signal:AbortSignal.timeout(3e4)});if(!response.ok||!response.body)throw new Error("Registry tarball is unavailable");const sha2568=createHash39("sha256");const sha512=createHash39("sha512");let size=0;for await(const chunk of response.body){size+=chunk.byteLength;if(size>16*1024*1024)throw new Error("Registry tarball exceeds proof limit");sha2568.update(chunk);sha512.update(chunk)}return JSON.stringify({sha256:`sha256:${sha2568.digest("hex")}`,integrity:`sha512-${sha512.digest("base64")}`,size})}return(await exec2(command2,args,{cwd:root,encoding:"utf8",windowsHide:true,timeout:3e4,maxBuffer:4*1024*1024})).stdout.trim()}}});import{createHash as createHash40}from"node:crypto";function authorizationPayload(receipt){return{...receipt.maintenance_direct_authorization_sha256===void 0?{}:{maintenance_direct_authorization_sha256:receipt.maintenance_direct_authorization_sha256},actor_task_id:receipt.actor_task_id,actor_execution_id:receipt.actor_execution_id,actor_run_id:receipt.actor_run_id,client_thread_id:receipt.client_thread_id,client_turn_id:receipt.client_turn_id,human_authorization_sha256:receipt.human_authorization_sha256,target_task_id:receipt.target_task_id,target_spec_id:receipt.target_spec_id,target_execution_id:receipt.target_execution_id,target_release:receipt.target_release,expected_task_revision:receipt.expected_task_revision,target_change_id:receipt.target_change_id,expected_change_revision:receipt.expected_change_revision,expected_change_status:receipt.expected_change_status,expected_spec_revision:receipt.expected_spec_revision,...receipt.expected_spec_status===void 0?{}:{expected_spec_status:receipt.expected_spec_status},expected_execution_revision:receipt.expected_execution_revision,...receipt.expected_execution_status===void 0?{}:{expected_execution_status:receipt.expected_execution_status},state_sha256:receipt.state_sha256,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,cycle_sha256:receipt.proof.cycle_sha256,proof_content_sha256:receipt.proof.proof_content_sha256,...receipt.proof.proof_inventory!==void 0?{proof_inventory_sha256:sha(JSON.stringify(receipt.proof.proof_inventory))}:{},npm_integrity:receipt.proof.npm_integrity,publish_run_id:receipt.proof.publish_run_id,release_asset_digest:receipt.proof.release_asset_digest,release_assets_sha256:receipt.proof.release_assets_sha256,evidence_selection_sha256:sha(JSON.stringify([...receipt.proof.evidence_ids].sort()))}}function requiredValue(value,name){if(!value)throw new UsageError(`Post-publication ${name} is required`);return value}function expectedRevision(parsed){const value=Number(parsed.options["expected-revision"]);if(!Number.isSafeInteger(value)||value<1)throw new UsageError("Post-publication expected revision must be positive");return value}function exactId(parsed){const id=parsed.positionals[2];if(!id?.startsWith("TASK-"))throw new UsageError("Exact blocked Task ID is required");return id}async function preparePostPublicationRecovery(parsed,filesystem,composition,publicationQuery){requireOptions(parsed.options,["actor-task","actor-execution","run","expected-revision","evidence"]);const taskId=exactId(parsed);const actorTaskId=requiredValue(parsed.options["actor-task"],"actor-task");const actorExecutionId=requiredValue(parsed.options["actor-execution"],"actor-execution");const actorRunId=requiredValue(parsed.options.run,"run");const context2=await recoveryContext(filesystem,composition,actorTaskId,actorRunId,taskId,actorExecutionId,resolveRunClientInvocation,"post-publication");if(context2.targetTaskRevision!==expectedRevision(parsed))throw new UsageError("Blocked Task revision changed; preview again");const actor=await composition.runs.read(actorRunId);const observed=await resolveRunClientInvocation(filesystem,actor.run.client);const direct=actor.run.direct_execution_authorization;const directObserved=typeof direct==="string"&&direct.trim().length>0&&observed.clientThreadId===actor.run.client_thread_id&&observed.clientTurnId===actor.run.client_turn_id&&!!observed.userMessage&&observed.observedModel===actor.run.model&&observed.observedReasoningEffort===actor.run.reasoning_effort;if(!(actor.run.intake?.classification_source==="explicit"&&actor.run.intake.intent==="new_work")&&!directObserved)throw new UsageError("Post-publication repair requires its explicit human-authorized maintenance root");if(!observed.userMessage||!observed.clientThreadId||!observed.clientTurnId)throw new UsageError("Observed human repair request and client turn are required");const target=(await composition.tasks.read(taskId)).task;if(context2.targetSpecId!==null&&!["blocked","active"].includes(context2.targetSpecStatus??""))throw new UsageError("Post-publication receipt requires a blocked or active historical SPEC");const evidenceIds=csvOption(parsed.options.evidence);const proof=await publishedClosureProof(filesystem,composition,target,evidenceIds,publicationQuery,context2.targetSpecId===null?true:void 0);const base={schema_version:3,...directObserved?{maintenance_direct_authorization_sha256:sha(direct)}:{},kind:"post_publication_closure",actor_task_id:actorTaskId,actor_execution_id:actorExecutionId,actor_run_id:actorRunId,client_thread_id:observed.clientThreadId,client_turn_id:observed.clientTurnId,human_authorization_sha256:sha(observed.userMessage),target_task_id:context2.targetTaskId,target_spec_id:context2.targetSpecId,target_execution_id:context2.targetExecutionId,target_release:context2.targetRelease,expected_task_revision:context2.targetTaskRevision,target_change_id:context2.targetChangeId,expected_change_revision:context2.targetChangeRevision,expected_change_status:context2.targetChangeStatus,expected_spec_revision:context2.targetSpecRevision,expected_spec_status:context2.targetSpecStatus,expected_execution_revision:context2.targetExecutionRevision,expected_execution_status:context2.targetExecutionStatus,state_sha256:context2.stateSha256,proof};const payload=authorizationPayload({...base,human_decision_id:""});if(!parsed.flags.has("apply"))return{receipt_path:null,authorization_payload:payload,applied:false,authorization_status:"pending-human-decision"};const decisionId=requiredValue(parsed.options.decision,"confirmed human Decision");await assertRecoveryDecision(composition,"change",requiredValue(actor.run.change_id,"maintenance Change"),decisionId,payload);const receipt={...base,human_decision_id:decisionId,issuance_decision_id:issuanceId({...base,human_decision_id:decisionId})};const path=receiptPath(receipt);const source=`${JSON.stringify(receipt)}
3582
+ `;let reused=false;if(await filesystem.exists(path)){if(await filesystem.readText(path)!==source)throw new UsageError("Post-publication receipt path contains different bytes");reused=true;try{const issued=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),receipt.issuance_decision_id);if(issued.origin!=="agent"||issued.decision!==issuancePayload(receipt))throw new UsageError("Post-publication receipt conflicts with its canonical issuance Decision");return{receipt_path:path,authorization_payload:payload,applied:true,reused:true}}catch(error51){if(!(error51 instanceof Error)||!("code"in error51)||error51.code!=="ENOENT")throw error51}}if(!reused)await filesystem.writeTextAtomicExclusive(path,source);await composition.decisions.record({id:receipt.issuance_decision_id,shortName:"post-publication-closure",title:"Emitir recibo de fechamento pos-publicacao",scopeType:"change",scopeId:requiredValue(actor.run.change_id,"maintenance Change"),origin:"agent",category:"contract",context:`Observed maintenance Run ${actorRunId} and human request hash ${receipt.human_authorization_sha256}`,decision:issuancePayload(receipt),reason:"Narrow receipt for the exact published release Task after maintenance finalization",alternatives:[],consequences:["Resume only metadata closure with a new finalizer"],reversible:true,rollback:"Leave old Task blocked and preserve publication; receipt grants no product writer",confidence:1,confirmed:false,timeZone:composition.layout.project.timezone});return{receipt_path:path,authorization_payload:payload,applied:true,reused}}async function readPostPublicationReceipt(filesystem,path){if(!/^\.local\/recovery\/post-publication\/[a-f0-9]{64}\.json$/.test(path))throw new UsageError("Post-publication receipt must use its canonical local path");let receipt;try{receipt=JSON.parse(await filesystem.readText(path))}catch{throw new UsageError("Post-publication receipt is unreadable")}if(receipt?.schema_version!==1&&receipt?.schema_version!==2&&receipt?.schema_version!==3||receipt.kind!=="post_publication_closure"||receiptPath(receipt)!==path||!receipt.actor_task_id?.startsWith("TASK-")||!receipt.actor_execution_id?.startsWith("EXEC-")||!receipt.actor_run_id?.startsWith("RUN-")||!receipt.issuance_decision_id?.startsWith("DEC-AI-POSTPUB-")||!receipt.human_decision_id?.startsWith("DEC-HUMAN-")||receipt.issuance_decision_id!==issuanceId((({issuance_decision_id:_ignored,...base})=>base)(receipt))||!receipt.target_task_id?.startsWith("TASK-")||!receipt.target_change_id?.startsWith("CHG-")||!Number.isSafeInteger(receipt.expected_change_revision)||receipt.expected_change_revision<1||!["blocked","executing"].includes(receipt.expected_change_status)||!(receipt.target_spec_id?.startsWith("SPEC-")?Number.isSafeInteger(receipt.expected_spec_revision)&&Number(receipt.expected_spec_revision)>0:(receipt.schema_version===2||receipt.schema_version===3)&&receipt.target_spec_id===null&&receipt.expected_spec_revision===null)||receipt.schema_version===3&&(!(["blocked","active"].includes(receipt.expected_spec_status??"")||receipt.target_spec_id===null&&receipt.expected_spec_status===null)||!["blocked","running"].includes(receipt.expected_execution_status??""))||receipt.maintenance_direct_authorization_sha256!==void 0&&(receipt.schema_version!==2&&receipt.schema_version!==3||!/^[a-f0-9]{64}$/.test(receipt.maintenance_direct_authorization_sha256))||!receipt.target_execution_id?.startsWith("EXEC-")||!/^[a-f0-9]{64}$/.test(receipt.human_authorization_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.state_sha256??"")||!/^[a-f0-9]{40}$/.test(receipt.proof?.candidate_sha??"")||!/^[a-f0-9]{40}$/.test(receipt.proof?.published_sha??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.cycle_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.proof_content_sha256??"")||!/^[a-f0-9]{64}$/.test(receipt.proof?.release_assets_sha256??"")||!/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(receipt.proof?.npm_integrity??"")||!Number.isSafeInteger(receipt.proof?.publish_run_id)||!/^sha256:[a-f0-9]{64}$/.test(receipt.proof?.release_asset_digest??""))throw new UsageError("Post-publication receipt identity is invalid");return receipt}var sha,issuanceId,receiptPath,issuancePayload;var init_post_publication_receipt=__esm({"src/post-publication-receipt.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_authority();init_post_publication_proof();init_run_client_invocation();sha=value=>createHash40("sha256").update(value).digest("hex");issuanceId=receipt=>`DEC-AI-POSTPUB-${sha(JSON.stringify(receipt)).slice(0,24).toUpperCase()}`;receiptPath=receipt=>`.local/recovery/post-publication/${sha(JSON.stringify(receipt))}.json`;issuancePayload=receipt=>JSON.stringify({kind:receipt.kind,actor_run_id:receipt.actor_run_id,target_task_id:receipt.target_task_id,target_spec_id:receipt.target_spec_id,target_execution_id:receipt.target_execution_id,receipt_sha256:sha(JSON.stringify(receipt)),human_authorization_sha256:receipt.human_authorization_sha256})}});async function validatePostPublicationSequence(filesystem,composition,receipt,actor,sequence,clientThreadId,clientTurnId,sameTurn){const handoffHash2=sha(JSON.stringify(receipt));if(sequence!==null&&(sequence.schema_version!==(sameTurn?7:8)||sequence.maintenance_run_id!==receipt.actor_run_id||sequence.maintenance_execution_id!==""&&sequence.maintenance_execution_id!==receipt.actor_execution_id))throw new UsageError("Post-publication sequence has another turn or maintenance authority");const steps=sequence?.steps??[];const currentStep=steps.find(step=>step.target_task_id===receipt.target_task_id);if(currentStep!==void 0&&(currentStep.execution_id!==receipt.target_execution_id||!claimOriginMatches(currentStep.origin,receipt.target_spec_id,receipt.target_task_id)||currentStep.authorization_sha256!==handoffHash2))throw new UsageError("Post-publication step has another target or authority");const precedingStep=currentStep===void 0?steps.at(-1):steps[steps.indexOf(currentStep)-1];for(const step of steps.filter(item=>item!==currentStep)){const priorReceipt=await readPostPublicationReceipt(filesystem,`.local/recovery/post-publication/${step.authorization_sha256}.json`);if(sha(JSON.stringify(priorReceipt))!==step.authorization_sha256||priorReceipt.actor_run_id!==receipt.actor_run_id||priorReceipt.actor_execution_id!==receipt.actor_execution_id||priorReceipt.client_thread_id!==receipt.client_thread_id||priorReceipt.human_authorization_sha256!==receipt.human_authorization_sha256||priorReceipt.target_task_id!==step.target_task_id||priorReceipt.target_execution_id!==step.execution_id||!claimOriginMatches(step.origin,priorReceipt.target_spec_id,step.target_task_id))throw new UsageError("Earlier post-publication receipt has another authority or target");await assertRecoveryDecision(composition,"change",requiredValue(actor.run.change_id,"maintenance Change"),priorReceipt.human_decision_id,authorizationPayload(priorReceipt));const priorIssuance=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),priorReceipt.issuance_decision_id);if(priorIssuance.origin!=="agent"||priorIssuance.decision!==issuancePayload(priorReceipt))throw new UsageError("Earlier post-publication receipt lacks canonical issuance")}const predecessorRunId=precedingStep?.successor_run_id??receipt.actor_run_id;const predecessor=predecessorRunId===receipt.actor_run_id?actor:await composition.runs.read(predecessorRunId);if(precedingStep!==void 0&&(predecessor.finished?.status!=="completed"||predecessor.finalization_decision?.outcome!=="completed"||(precedingStep.origin.type==="spec"?predecessor.run.spec_id!==precedingStep.origin.spec_id:predecessor.run.task_id!==precedingStep.target_task_id)||predecessor.run.execution_id!==precedingStep.execution_id||(await composition.tasks.read(precedingStep.target_task_id)).task.status!=="completed"))throw new UsageError("Previous post-publication successor and Gui must finish first");const allRuns=await composition.runs.list();const roots2=allRuns.filter(run=>run.run.parent_run_id===null&&run.run.client_thread_id===clientThreadId&&run.run.client_turn_id===clientTurnId);const expectedRootIds=new Set([...sameTurn?[receipt.actor_run_id]:[],...steps.map(step=>step.successor_run_id)]);if(sameTurn&&!roots2.some(run=>run.run.run_id===actor.run.run_id)||roots2.some(run=>!expectedRootIds.has(run.run.run_id)))throw new UsageError("Observed turn already has another root owner");for(const[index,step]of steps.entries()){const root=roots2.find(run=>run.run.run_id===step.successor_run_id);if(root===void 0){if(index!==steps.length-1||currentStep!==step)throw new UsageError("Post-publication sequence has an unfinished earlier claim");continue}if(root.run.continuation_of_run_id!==step.predecessor_run_id||root.run.execution_id!==step.execution_id||root.run.spec_id!==(step.origin.type==="spec"?step.origin.spec_id:null)||step.origin.type==="task"&&root.run.task_id!==step.target_task_id||(root.run.same_turn_handoff===void 0?index!==0||sameTurn||!root.run.intake?.reason_codes.includes(`post-publication-${step.authorization_sha256.slice(0,16)}`):index===0&&!sameTurn||root.run.same_turn_handoff.authorization_sha256!==step.authorization_sha256||root.run.same_turn_handoff.predecessor_run_id!==step.predecessor_run_id))throw new UsageError("Post-publication sequence root differs from its claim")}const successor=currentStep===void 0?null:roots2.find(run=>run.run.run_id===currentStep.successor_run_id)??null;if(currentStep===void 0&&steps.some(step=>roots2.find(run=>run.run.run_id===step.successor_run_id)?.status==="running"))throw new UsageError("Previous post-publication root is still active");return{handoffHash:handoffHash2,currentStep,precedingStep,predecessorRunId,successor,allRuns}}function claimOriginMatches(origin,spec,task){return spec===null?origin.type==="task"&&origin.task_id===task:origin.type==="spec"&&origin.spec_id===spec}var init_post_publication_recovery_sequence=__esm({"src/post-publication-recovery-sequence.ts"(){"use strict";init_cli_arguments();init_controlled_recovery_authority();init_post_publication_receipt()}});import{posix as posix6}from"node:path";async function assertHistoricalProofSnapshot(receipt,composition,successor){const directory2=posix6.dirname(composition.layout.activePath("change",receipt.target_change_id));const paths2=(await Promise.all(["tests","evals","checks","evidence","observations"].map(kind=>composition.filesystem.listFiles(`${directory2}/artifacts/${kind}`)))).flat().sort();const inventory3=receipt.proof.proof_inventory;if(inventory3!==void 0&&(!Array.isArray(inventory3)||inventory3.some(entry2=>!Array.isArray(entry2)||entry2.length!==2)))throw new UsageError("Task-first historical proof inventory is malformed");const originalPaths=inventory3?.map(([path])=>path)??paths2;if(inventory3!==void 0&&(!Array.isArray(inventory3)||new Set(originalPaths).size!==originalPaths.length||JSON.stringify([...originalPaths].sort())!==JSON.stringify(originalPaths)||inventory3.some(([path,hash6])=>typeof path!=="string"||typeof hash6!=="string"||!/^[a-f0-9]{64}$/.test(hash6)||!path.startsWith(`${directory2}/artifacts/`)||posix6.normalize(path)!==path||!paths2.includes(path))||sha(JSON.stringify(inventory3))!==receipt.proof.proof_content_sha256))throw new UsageError("Task-first historical proof inventory changed or lost original paths");const contents=await Promise.all(originalPaths.map(async path=>[path,sha(await composition.filesystem.readText(path))]));if(sha(JSON.stringify(contents))!==receipt.proof.proof_content_sha256)throw new UsageError("Task-first historical proof bytes changed after receipt issuance");for(const path of paths2.filter(path2=>!originalPaths.includes(path2))){if(successor===null)throw new UsageError("Historical proof additions require the exact recovery root");let artifact;try{const source=await composition.filesystem.readText(path);artifact=path.includes("/artifacts/evidence/")?parseMarkdown(source,evidenceArtifactV2Schema).metadata:parseMarkdown(source,validationArtifactV2Schema).metadata}catch{throw new UsageError("Historical proof addition is not a typed recovery validation")}if(path.includes("/artifacts/observations/")||posix6.basename(path)!==`${artifact.id}.md`||artifact.run_id!==successor.run.run_id||artifact.task_id!==receipt.target_task_id||artifact.change_id!==receipt.target_change_id||artifact.execution_id!==receipt.target_execution_id||artifact.commit_sha!==receipt.proof.candidate_sha)throw new UsageError("Historical proof addition differs from the recovery root or original candidate")}}var init_post_publication_snapshot=__esm({"src/post-publication-snapshot.ts"(){"use strict";init_src();init_assurance();init_cli_arguments();init_post_publication_receipt()}});async function resumePostPublicationClosure(parsed,filesystem,composition,lifecycle,publicationQuery){requireOptions(parsed.options,["receipt"]);const receipt=await readPostPublicationReceipt(filesystem,requiredValue(parsed.options.receipt,"receipt"));if(exactId(parsed)!==receipt.target_task_id)throw new UsageError("Post-publication receipt targets another Task");const actor=await composition.runs.read(receipt.actor_run_id);const invocation2=await resolveRunClientInvocation(filesystem,actor.run.client);if(!invocation2.clientThreadId||!invocation2.clientTurnId||invocation2.clientThreadId!==receipt.client_thread_id)throw new UsageError("Post-publication continuation needs its observed client thread and turn");const sameTurn=invocation2.clientTurnId===receipt.client_turn_id;if(!sameTurn&&(!invocation2.observedModel||!invocation2.observedReasoningEffort))throw new UsageError("New post-publication turn requires observed model and reasoning effort");if(sameTurn&&(!invocation2.userMessage||sha(invocation2.userMessage)!==receipt.human_authorization_sha256))throw new UsageError("Same-turn human authorization differs from the receipt");const sequence=await composition.executions.readPostPublicationSequence(invocation2.clientTurnId);if(actor.finished?.status!=="completed"||actor.finalization_decision?.outcome!=="completed"||actor.run.execution_id!==receipt.actor_execution_id||actor.run.task_id!==receipt.actor_task_id||actor.run.client_thread_id!==receipt.client_thread_id||actor.run.client_turn_id!==receipt.client_turn_id||(await composition.tasks.read(receipt.actor_task_id)).task.status!=="completed")throw new UsageError("Maintenance Task and Gui must finish before the historical delivery resumes");if(receipt.maintenance_direct_authorization_sha256!==void 0&&sha(actor.run.direct_execution_authorization??"")!==receipt.maintenance_direct_authorization_sha256)throw new UsageError("Maintenance direct authorization differs from its issued receipt");const issuance=await composition.decisions.read("change",requiredValue(actor.run.change_id,"maintenance Change"),receipt.issuance_decision_id);const decisionScope=requiredValue(actor.run.change_id,"maintenance Change");await assertRecoveryDecision(composition,"change",decisionScope,receipt.human_decision_id,authorizationPayload(receipt));const humanDecision=await composition.decisions.read("change",decisionScope,receipt.human_decision_id);if(issuance.origin!=="agent"||issuance.category!=="contract"||issuance.decision!==issuancePayload(receipt)||!issuance.created_at||!humanDecision.confirmed_at||Date.parse(humanDecision.confirmed_at)>Date.parse(issuance.created_at)||Date.parse(issuance.created_at)>Date.parse(actor.finished.occurred_at))throw new UsageError("Canonical receipt issuance was not recorded before maintenance finalization");if(sameTurn&&(invocation2.observedModel!==actor.run.model||invocation2.observedReasoningEffort!==actor.run.reasoning_effort))throw new UsageError("Same-turn handoff model or effort differs from its observed root");const{handoffHash:handoffHash2,currentStep,precedingStep,predecessorRunId,successor,allRuns}=await validatePostPublicationSequence(filesystem,composition,receipt,actor,sequence,invocation2.clientThreadId,invocation2.clientTurnId,sameTurn);const target=(await composition.tasks.read(receipt.target_task_id)).task;if(allRuns.some(run2=>run2.status==="running"&&run2.run.task_id===receipt.target_task_id&&run2.run.run_id!==successor?.run.run_id))throw new UsageError("Post-publication target has another active root owner");if(receipt.proof.proof_inventory!==void 0)await assertHistoricalProofSnapshot(receipt,composition,successor);const proof=await publishedClosureProof(filesystem,composition,target,receipt.proof.evidence_ids,publicationQuery,receipt.proof.proof_inventory);if(JSON.stringify(proof)!==JSON.stringify(receipt.proof))throw new UsageError("Post-publication candidate, publication, Evidence or cycle changed");if(target.status==="executing"){if(successor!==null){if(successor.status!=="running")throw new UsageError("Executing target has no exact active closure owner");const change=(await composition.changes.read(receipt.target_change_id)).change;const execution2=(await composition.executions.read(receipt.target_execution_id)).execution;const expectedExecutionStatus2=receipt.schema_version===3?receipt.expected_execution_status:"blocked";if(target.revision!==receipt.expected_task_revision+1||change.status!=="executing"||change.revision!==receipt.expected_change_revision+(receipt.expected_change_status==="blocked"?1:0)||execution2.status!=="running"||execution2.revision!==receipt.expected_execution_revision+(expectedExecutionStatus2==="blocked"?1:0))throw new UsageError("Active post-publication owner has changed target revisions");return{run:successor.run,receipt_path:parsed.options.receipt,reused:true}}if(receipt.target_spec_id!==null||currentStep===void 0)throw new UsageError("Executing target has no exact pending Task-first claim")}if(target.status!=="blocked"&&target.status!=="executing")throw new UsageError("Post-publication target is no longer blocked");const context2=await recoveryContext(filesystem,composition,receipt.actor_task_id,receipt.actor_run_id,receipt.target_task_id,receipt.actor_execution_id,resolveRunClientInvocation,target.status==="executing"?"post-publication-consume-partial":"post-publication-consume");const executionBefore=(await composition.executions.read(receipt.target_execution_id)).execution;const specBefore=receipt.target_spec_id===null?null:(await composition.specs.read(receipt.target_spec_id)).spec;const pristine=context2.stateSha256===receipt.state_sha256&&context2.targetSpecRevision===receipt.expected_spec_revision&&context2.targetExecutionRevision===receipt.expected_execution_revision&&(receipt.schema_version===3?executionBefore.status===receipt.expected_execution_status&&(specBefore?.status??null)===receipt.expected_spec_status:executionBefore.status==="blocked"&&(specBefore===null||specBefore.status==="blocked"));const expectedExecutionStatus=receipt.schema_version===3?receipt.expected_execution_status:"blocked";const expectedSpecStatus=receipt.schema_version===3?receipt.expected_spec_status:specBefore===null?null:"blocked";const changeBefore=(await composition.changes.read(receipt.target_change_id)).change;const partial2=currentStep!==void 0&&context2.targetTaskRevision===receipt.expected_task_revision+(target.status==="executing"?1:0)&&context2.targetChangeRevision===receipt.expected_change_revision+(receipt.expected_change_status==="blocked"&&changeBefore.status==="executing"?1:0)&&(changeBefore.status===receipt.expected_change_status||changeBefore.status==="executing")&&(specBefore===null?context2.targetSpecRevision===null&&receipt.expected_spec_revision===null:context2.targetSpecRevision===Number(receipt.expected_spec_revision)+(expectedSpecStatus==="blocked"&&specBefore.status==="active"?1:0))&&context2.targetExecutionRevision===receipt.expected_execution_revision+(expectedExecutionStatus==="blocked"&&executionBefore.status==="running"?1:0)&&(specBefore===null||specBefore.status===expectedSpecStatus||specBefore.status==="active")&&(executionBefore.status===expectedExecutionStatus||executionBefore.status==="running")&&(target.status!=="executing"||receipt.target_spec_id===null&&changeBefore.status==="executing"&&executionBefore.status==="running");if(!pristine&&!partial2||context2.targetChangeId!==receipt.target_change_id||!partial2&&context2.targetChangeRevision!==receipt.expected_change_revision||!partial2&&context2.targetChangeStatus!==receipt.expected_change_status||!partial2&&context2.targetTaskRevision!==receipt.expected_task_revision||context2.targetSpecId!==receipt.target_spec_id||context2.targetExecutionId!==receipt.target_execution_id)throw new UsageError("Post-publication target revisions or state changed");if(successor!==null){if(successor.status!=="running")throw new UsageError("Post-publication successor is terminal before Task resume");const resumed2=await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256});return{run:successor.run,task:resumed2.task,receipt_path:parsed.options.receipt,reused:true,recovered_pending:true}}const runId=createId("RUN","post-publication-closure",{timeZone:composition.layout.project.timezone});const claimed=await composition.executions.claimPostPublicationSequence({clientTurnId:invocation2.clientTurnId,sameTurn,maintenanceRunId:receipt.actor_run_id,maintenanceExecutionId:receipt.actor_execution_id,executionId:receipt.target_execution_id,specId:receipt.target_spec_id,targetTaskId:receipt.target_task_id,predecessorRunId,proposedSuccessorRunId:runId,authorizationSha256:handoffHash2});let execution=(await composition.executions.read(receipt.target_execution_id)).execution;if(receipt.target_spec_id!==null&&execution.status==="blocked")execution=await composition.executions.transition(execution.id,"running");const spec=receipt.target_spec_id===null?null:(await composition.specs.read(receipt.target_spec_id)).spec;if(receipt.target_spec_id!==null&&spec?.status==="blocked")await composition.specs.transition(spec.id,"active");const taskFirstResumed=receipt.target_spec_id===null&&target.status==="blocked"?await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256}):null;if(receipt.target_spec_id===null)execution=(await composition.executions.read(receipt.target_execution_id)).execution;const start={id:claimed,shortName:"post-publication-closure",phase:"execution",runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:true,executionKind:"delivery",executionEligibility:[],entrypoint:receipt.target_spec_id===null?"task":"spec",workType:"rework",client:actor.run.client,agent:actor.run.agent,...actor.run.agent_name===void 0?{}:{agentName:actor.run.agent_name},provider:actor.run.provider,model:sameTurn?actor.run.model:requiredValue(invocation2.observedModel,"observed model"),reasoningEffort:sameTurn?actor.run.reasoning_effort??null:requiredValue(invocation2.observedReasoningEffort,"observed effort"),clientThreadId:invocation2.clientThreadId,clientTurnId:invocation2.clientTurnId,conversationId:actor.run.conversation_id,executionId:receipt.target_execution_id,specId:receipt.target_spec_id,prdId:null,taskId:receipt.target_spec_id===null?receipt.target_task_id:null,changeId:receipt.target_spec_id===null?receipt.target_change_id:null,parentRunId:null,continuationOfRunId:predecessorRunId,...!sameTurn&&precedingStep===void 0?{intake:{intent:"continue",classification_source:"explicit",confidence:1,reason_codes:[`post-publication-${handoffHash2.slice(0,16)}`]}}:{},...sameTurn||precedingStep!==void 0?{sameTurnHandoff:{kind:"post_publication_closure",predecessor_run_id:predecessorRunId,target_spec_id:receipt.target_spec_id,target_task_id:receipt.target_task_id,authorization_sha256:handoffHash2}}:{},...actor.run.developer_identity===void 0?{}:{developerIdentity:actor.run.developer_identity}};await validateRunV2Attribution(start,composition);const run=(await composition.runs.start(start)).started;const resumed=taskFirstResumed??(receipt.target_spec_id===null?{task:target}:await lifecycle.startTaskWithSnapshot(receipt.target_task_id,"resume",{targetTaskId:receipt.target_task_id,targetRelease:receipt.target_release,publishedSha:receipt.proof.published_sha,cycleSha256:receipt.proof.cycle_sha256}));return{run,task:resumed.task,execution,receipt_path:parsed.options.receipt,reused:false}}var init_post_publication_recovery=__esm({"src/post-publication-recovery.ts"(){"use strict";init_src();init_attribution_v2();init_cli_arguments();init_controlled_recovery_authority();init_post_publication_proof();init_post_publication_receipt();init_post_publication_recovery_sequence();init_post_publication_snapshot();init_run_client_invocation();init_post_publication_receipt()}});import{createHash as createHash41}from"node:crypto";function required2(value,name){if(!value)throw new UsageError(`Post-publication relay requires ${name}`);return value}function closureStateHash(task,change,execution,spec,cycle){return sha2(JSON.stringify({task:[task.id,task.revision,task.status,task.plan_hash],change:[change.id,change.revision,change.status],execution:[execution.id,execution.revision,execution.status,execution.plan_hash],spec:[spec.id,spec.revision,spec.status,spec.plan_ref?.hash??null],cycle}))}async function assertRelayActor(composition,actorRunId,actorTaskId,actorExecutionId){const actor=await composition.runs.read(actorRunId);const{task}=await composition.tasks.read(actorTaskId);const{execution}=await composition.executions.read(actorExecutionId);const macro=actor.run.parent_run_id?await composition.runs.read(actor.run.parent_run_id):null;if(actor.status!=="running"||actor.run.agent!=="agent-orchestrator"||actor.run.run_role!=="subagent"||actor.run.run_purpose!=="orchestration"||actor.run.task_id!==task.id||actor.run.change_id!==task.change_id||actor.run.execution_id!==execution.id||task.status!=="executing"||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)||execution.origin.type!=="spec"||actor.run.spec_id!==execution.origin.spec_id||macro?.status!=="running"||macro.run.agent!=="agent-orchestrator"||macro.run.run_role!=="orchestrator"||macro.run.entrypoint!=="spec"||macro.run.parent_run_id!==null||macro.run.task_id!==null||macro.run.spec_id!==actor.run.spec_id||macro.run.execution_id!==actor.run.execution_id||macro.run.conversation_id!==actor.run.conversation_id||!actor.run.client_thread_id||!actor.run.client_turn_id)throw new UsageError("Relay requires the exact active delegated Task orchestrator and macro");return actor}async function recordRelayDecision(composition,id,scopeId,payload){const decision=JSON.stringify(payload);const existing=await composition.decisions.read("change",scopeId,id).catch(()=>null);if(existing!==null){if(existing.origin!=="agent"||existing.category!=="contract"||existing.decision!==decision)throw new UsageError("Post-publication relay journal conflicts with its canonical Decision");return}await composition.decisions.record({id,shortName:"post-publication-relay",title:"Vincular fechamento historico pos-publicacao",scopeType:"change",scopeId,origin:"agent",category:"contract",context:`Exact post-publication relay for ${payload.target_task_id}`,decision,reason:"Preserve published candidate and historical Evidence under a new observed Run",alternatives:[],consequences:["Records-only closure; no new product publication"],reversible:true,rollback:"Leave the historical Task blocked or executing without rewriting its old Runs",confidence:1,confirmed:false,timeZone:composition.layout.project.timezone})}async function readRelayIntent(composition,actor,targetTaskId,intentId){const changeId=actor.run.change_id;if(!changeId)return null;const record3=await composition.decisions.read("change",changeId,intentId).catch(()=>null);if(record3===null)return null;let value;try{value=JSON.parse(record3.decision)}catch{throw new UsageError("Post-publication relay intent is invalid")}const legacy2=intentId===relayIntentId(actor.run.run_id,targetTaskId);if(!legacy2&&intentId!==relayIntentId(actor.run.run_id,targetTaskId,value.current_state_sha256)||record3.origin!=="agent"||record3.category!=="contract"||value.schema_version!==1||value.kind!=="post_publication_relay_intent"||value.actor_run_id!==actor.run.run_id||value.actor_client_thread_id!==void 0&&(value.actor_client_thread_id!==actor.run.client_thread_id||value.actor_client_turn_id!==actor.run.client_turn_id)||value.actor_client_thread_id===void 0&&value.actor_client_turn_id!==void 0||value.actor_task_id!==actor.run.task_id||value.actor_change_id!==changeId||value.actor_execution_id!==actor.run.execution_id||!Number.isSafeInteger(value.actor_task_revision)||!/^[a-f0-9]{64}$/.test(value.actor_plan_hash)||!/^[a-f0-9]{64}$/.test(value.actor_objective_sha256)||value.authorization_id!==relayAuthorizationId(actor.run.run_id,targetTaskId,legacy2?void 0:value.current_state_sha256)||value.macro_run_id!==actor.run.parent_run_id||value.target_task_id!==targetTaskId||!/^[a-f0-9]{64}$/.test(value.receipt_sha256)||!/^[a-f0-9]{40}$/.test(value.candidate_sha)||!/^[a-f0-9]{40}$/.test(value.published_sha)||!Number.isSafeInteger(value.expected_task_revision)||!Number.isSafeInteger(value.expected_change_revision)||!Number.isSafeInteger(value.expected_execution_revision)||!Number.isSafeInteger(value.expected_spec_revision)||value.retry_predecessor_run_id!==void 0&&(!value.retry_predecessor_run_id.startsWith("RUN-")||!Number.isSafeInteger(value.expected_task_attempt_count)||(value.expected_task_attempt_count??0)<1)||value.retry_predecessor_run_id===void 0&&value.expected_task_attempt_count!==void 0||!/^[a-f0-9]{64}$/.test(value.receipt_state_sha256)||!/^[a-f0-9]{64}$/.test(value.current_state_sha256))throw new UsageError("Post-publication relay intent does not match its actor and target");return value}var sha2,relayIntentId,relayBindingId,relayCaptureId,relayAuthorizationId;var init_post_publication_relay_core=__esm({"src/post-publication-relay-core.ts"(){"use strict";init_cli_arguments();sha2=value=>createHash41("sha256").update(value).digest("hex");relayIntentId=(actorRunId,targetTaskId,stateSha256)=>`DEC-AI-POSTPUB-RELAY-${sha2(JSON.stringify(stateSha256===void 0?[actorRunId,targetTaskId]:[actorRunId,targetTaskId,stateSha256])).slice(0,24).toUpperCase()}`;relayBindingId=targetRunId=>`DEC-AI-POSTPUB-BIND-${sha2(targetRunId).slice(0,24).toUpperCase()}`;relayCaptureId=(actorRunId,agentId2,turnId)=>`DEC-AI-POSTPUB-CAPTURE-${sha2(JSON.stringify([actorRunId,agentId2,turnId])).slice(0,24).toUpperCase()}`;relayAuthorizationId=(actorRunId,targetTaskId,stateSha256)=>`DEC-AI-POSTPUB-AUTH-${sha2(JSON.stringify(stateSha256===void 0?[actorRunId,targetTaskId]:[actorRunId,targetTaskId,stateSha256])).slice(0,24).toUpperCase()}`}});async function authorizationPayloadForIntent(composition,intent,userMessageSha256){const[macro,actorTask]=await Promise.all([composition.runs.read(intent.macro_run_id),composition.tasks.read(intent.actor_task_id).then(({task})=>task)]);if(actorTask.revision!==intent.actor_task_revision||actorTask.plan_hash!==intent.actor_plan_hash||sha2(actorTask.objective)!==intent.actor_objective_sha256||macro.status!=="running"||macro.run.parent_run_id!==null||macro.run.entrypoint!=="spec"||!macro.run.client_thread_id||!macro.run.client_turn_id)throw new UsageError("Macro or delegated Task contract changed before authorization");return{schema_version:1,kind:"post_publication_relay_authorization",macro_run_id:macro.run.run_id,macro_client_thread_id:macro.run.client_thread_id,macro_client_turn_id:macro.run.client_turn_id,source_user_message_sha256:userMessageSha256,actor_run_id:intent.actor_run_id,...intent.actor_client_thread_id===void 0?{}:{actor_client_thread_id:intent.actor_client_thread_id,actor_client_turn_id:intent.actor_client_turn_id},actor_task_id:intent.actor_task_id,actor_task_revision:intent.actor_task_revision,actor_plan_hash:intent.actor_plan_hash,actor_objective:actorTask.objective,target_task_id:intent.target_task_id,target_change_id:intent.target_change_id,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,receipt_state_sha256:intent.receipt_state_sha256,current_state_sha256:intent.current_state_sha256,expected_task_revision:intent.expected_task_revision,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,...intent.retry_predecessor_run_id===void 0?{}:{retry_predecessor_run_id:intent.retry_predecessor_run_id,expected_task_attempt_count:intent.expected_task_attempt_count}}}async function assertIssuedRelayAuthorization(composition,intent){const record3=await composition.decisions.read("change",intent.actor_change_id,intent.authorization_id).catch(()=>null);let recorded=null;try{recorded=JSON.parse(record3?.decision??"")}catch{}const[macro,actor]=await Promise.all([composition.runs.read(intent.macro_run_id),composition.runs.read(intent.actor_run_id)]);if(actor.run.parent_run_id!==macro.run.run_id||actor.run.task_id!==intent.actor_task_id||actor.run.change_id!==intent.actor_change_id||actor.run.execution_id!==intent.actor_execution_id||intent.actor_client_thread_id!==void 0&&(actor.run.client_thread_id!==intent.actor_client_thread_id||actor.run.client_turn_id!==intent.actor_client_turn_id)||macro.run.parent_run_id!==null||macro.run.entrypoint!=="spec"||!macro.run.client_thread_id||!macro.run.client_turn_id||!recorded||sha2(recorded.actor_objective??"")!==intent.actor_objective_sha256)throw new UsageError("Historical relay authorization differs from its original Run ancestry");const expected={schema_version:1,kind:"post_publication_relay_authorization",macro_run_id:macro.run.run_id,macro_client_thread_id:macro.run.client_thread_id,macro_client_turn_id:macro.run.client_turn_id,source_user_message_sha256:recorded.source_user_message_sha256,actor_run_id:intent.actor_run_id,...intent.actor_client_thread_id===void 0?{}:{actor_client_thread_id:intent.actor_client_thread_id,actor_client_turn_id:intent.actor_client_turn_id},actor_task_id:intent.actor_task_id,actor_task_revision:intent.actor_task_revision,actor_plan_hash:intent.actor_plan_hash,actor_objective:recorded.actor_objective,target_task_id:intent.target_task_id,target_change_id:intent.target_change_id,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,receipt_state_sha256:intent.receipt_state_sha256,current_state_sha256:intent.current_state_sha256,expected_task_revision:intent.expected_task_revision,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,...intent.retry_predecessor_run_id===void 0?{}:{retry_predecessor_run_id:intent.retry_predecessor_run_id,expected_task_attempt_count:intent.expected_task_attempt_count}};if(record3?.origin!=="agent"||record3.category!=="contract"||!/^[a-f0-9]{64}$/.test(recorded.source_user_message_sha256)||record3.decision!==JSON.stringify(expected))throw new UsageError("Observed macro authorization for this exact relay snapshot is missing")}async function assertLiveRelayAuthority(composition,intent){await assertIssuedRelayAuthorization(composition,intent);await assertRelayActor(composition,intent.actor_run_id,intent.actor_task_id,intent.actor_execution_id);const recorded=await composition.decisions.read("change",intent.actor_change_id,intent.authorization_id);const source=JSON.parse(recorded.decision);if(recorded.decision!==JSON.stringify(await authorizationPayloadForIntent(composition,intent,source.source_user_message_sha256)))throw new UsageError("Live relay actor plan changed after authorization")}var init_post_publication_relay_authorization=__esm({"src/post-publication-relay-authorization.ts"(){"use strict";init_cli_arguments();init_post_publication_relay_core()}});var init_post_publication_relay_contract=__esm({"src/post-publication-relay-contract.ts"(){"use strict";init_post_publication_relay_authorization();init_post_publication_relay_core()}});import{execFile as execFile9}from"node:child_process";import{createHash as createHash42}from"node:crypto";import{posix as posix7}from"node:path";import{promisify as promisify9}from"node:util";async function git(root,args){try{return(await exec3("git",args,{cwd:root,encoding:"utf8",windowsHide:true,timeout:3e4,maxBuffer:4*1024*1024})).stdout.trim()}catch{throw new UsageError("Historical candidate and published Git ancestry are unavailable")}}async function assertRecordsOnlyPublication(filesystem,receipt,requireCurrentCycle){const cycleText=await filesystem.readText(cyclePath3);const cycle=JSON.parse(cycleText);const matches=Array.isArray(cycle.history)?cycle.history.filter(entry2=>entry2?.from===receipt.target_release):[];const row=requireCurrentCycle?publishedHistoryRow(cycle,receipt.target_release):matches.length===1?matches[0]:null;if(row===null||row.sha!==receipt.proof.published_sha)throw new UsageError("Historical publication differs from its issued receipt");if(requireCurrentCycle){if(cycle.state!=="open"||row===null||row.from!==receipt.target_release||row.sha!==receipt.proof.published_sha||sha3(cycleText)!==receipt.proof.cycle_sha256)throw new UsageError("Historical publication cycle differs from its issued receipt")}const candidate=receipt.proof.candidate_sha;const published=receipt.proof.published_sha;const recoveryDeclared=row!==null&&Object.keys(row).some(key=>key.startsWith("publisher_recovery_"));if(recoveryDeclared){if(row.sha!==published||!await validatePublisherRecoveryBoundary((...args)=>git(filesystem.root,args),row,candidate,published))throw new UsageError("Historical publisher repair differs from its typed publication boundary")}else{await git(filesystem.root,["merge-base","--is-ancestor",candidate,published])}await git(filesystem.root,["merge-base","--is-ancestor",published,"HEAD"]);const commits=(await git(filesystem.root,["rev-list","--reverse","--parents",`${candidate}..${published}`])).split(/\r?\n/).filter(Boolean);for(const row2 of commits){const[commit,...parents]=row2.split(/\s+/);if(!commit||parents.length!==1)throw new UsageError("Published successor contains an intermediary merge");const paths2=(await git(filesystem.root,["diff-tree","--root","-m","--no-commit-id","-r","--name-only","-z",commit])).split("\0").filter(Boolean);if(paths2.some(path=>!path.startsWith(".agents/records/")))throw new UsageError("Published successor contains product or merge changes")}}async function assertIssuedReceipt(filesystem,composition,receipt,mode="live"){const issuer=await composition.runs.read(receipt.actor_run_id);const issuerTask=(await composition.tasks.read(receipt.actor_task_id)).task;if(issuer.finished?.status!=="completed"||issuer.finalization_decision?.outcome!=="completed"||issuerTask.status!=="completed"||issuer.run.task_id!==receipt.actor_task_id||issuer.run.execution_id!==receipt.actor_execution_id||issuer.run.change_id!==issuerTask.change_id||issuer.run.parent_run_id!==null)throw new UsageError("Post-publication receipt issuer is not terminal and attributed");if(receipt.maintenance_direct_authorization_sha256!==void 0&&sha3(issuer.run.direct_execution_authorization??"")!==receipt.maintenance_direct_authorization_sha256)throw new UsageError("Post-publication direct authorization changed after issuance");await assertRecoveryDecision(composition,"change",issuerTask.change_id,receipt.human_decision_id,authorizationPayload(receipt));const issuance=await composition.decisions.read("change",issuerTask.change_id,receipt.issuance_decision_id);const human=await composition.decisions.read("change",issuerTask.change_id,receipt.human_decision_id);if(issuance.origin!=="agent"||issuance.category!=="contract"||issuance.decision!==issuancePayload(receipt)||!issuance.created_at||!human.confirmed_at||Date.parse(human.confirmed_at)>Date.parse(issuance.created_at)||Date.parse(issuance.created_at)>Date.parse(issuer.finished.occurred_at))throw new UsageError("Post-publication receipt issuance is not canonical");await assertRecordsOnlyPublication(filesystem,receipt,mode==="live")}async function evidenceHashes(filesystem,composition,receipt){const{task}=await composition.tasks.read(receipt.target_task_id);const ids2=receipt.proof.evidence_ids;const bundle=await readAssuranceBundle(filesystem,composition.layout,[task],ids2);if(ids2.length===0||new Set(ids2).size!==ids2.length||bundle.evidences.length!==ids2.length||bundle.evidences.some(item=>item.status!=="passed"||item.task_id!==receipt.target_task_id||item.change_id!==receipt.target_change_id||item.execution_id!==receipt.target_execution_id||item.commit_sha!==receipt.proof.candidate_sha))throw new UsageError("Historical Evidence selection differs from the receipt");const directory2=posix7.dirname(composition.layout.activePath("change",task.change_id));const hashes={};for(const id of[...ids2].sort()){const evidence=bundle.evidences.find(item=>item.id===id);if(!evidence||(await composition.runs.read(evidence.run_id)).status!=="completed")throw new UsageError("Historical Evidence producer is not terminal");hashes[id]=sha3(await filesystem.readText(`${directory2}/artifacts/evidence/${id}.md`))}return hashes}var exec3,sha3,cyclePath3;var init_post_publication_relay_proof=__esm({"src/post-publication-relay-proof.ts"(){"use strict";init_candidate_publisher_recovery();init_cli_arguments();init_controlled_recovery_authority();init_lifecycle_assurance_v2();init_post_publication_cycle();init_post_publication_recovery();exec3=promisify9(execFile9);sha3=value=>createHash42("sha256").update(value).digest("hex");cyclePath3=".agents/config/release-cycle.json"}});async function authenticatedRelayForCapture(composition,actor,targetTaskId,intentId){const intent=await readRelayIntent(composition,actor,targetTaskId,intentId);if(intent===null)return null;await assertRelayActor(composition,actor.run.run_id,intent.actor_task_id,intent.actor_execution_id);const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256||receipt.target_task_id!==targetTaskId||receipt.target_change_id!==intent.target_change_id||receipt.target_execution_id!==intent.target_execution_id||receipt.target_spec_id!==intent.target_spec_id||receipt.proof.candidate_sha!==intent.candidate_sha||receipt.proof.published_sha!==intent.published_sha)throw new UsageError("Historical relay receipt differs from its captured target");await assertIssuedReceipt(composition.filesystem,composition,receipt);const actorTask=(await composition.tasks.read(intent.actor_task_id)).task;if(actorTask.revision!==intent.actor_task_revision||actorTask.plan_hash!==intent.actor_plan_hash||sha2(actorTask.objective)!==intent.actor_objective_sha256||receipt.state_sha256!==intent.receipt_state_sha256)throw new UsageError("Historical relay actor plan or receipt snapshot changed");if(JSON.stringify(await evidenceHashes(composition.filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical relay Evidence changed before native capture");const[{task},{change},{execution},{spec}]=await Promise.all([composition.tasks.read(targetTaskId),composition.changes.read(intent.target_change_id),composition.executions.read(intent.target_execution_id),composition.specs.read(intent.target_spec_id)]);if(task.status!=="executing"||task.revision!==intent.expected_task_revision+1||intent.expected_task_attempt_count!==void 0&&task.attempt_count!==intent.expected_task_attempt_count+1||change.status!=="executing"||change.revision!==intent.expected_change_revision+(intent.retry_predecessor_run_id?0:1)||execution.status!=="running"||execution.revision!==intent.expected_execution_revision+(intent.retry_predecessor_run_id?0:1)||spec.status!=="active"||spec.revision!==intent.expected_spec_revision+(intent.retry_predecessor_run_id?0:1))throw new UsageError("Historical relay Task changed before native capture");await assertLiveRelayAuthority(composition,intent);return intent}async function assertRelayNativeCapture(composition,actor,targetTaskId,intentId,nativeSessionId,agentId2,turnId,record3){if(!intentId||!nativeSessionId||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(nativeSessionId))throw new UsageError("Historical native capture requires exact relay and session");const intent=record3?await authenticatedRelayForCapture(composition,actor,targetTaskId,intentId):await readRelayIntent(composition,actor,targetTaskId,intentId);if(!intent)throw new UsageError("Historical relay is not authenticated for native capture");const id=relayCaptureId(actor.run.run_id,agentId2,turnId);const payload={schema_version:1,kind:"post_publication_relay_capture",intent_id:intentId,actor_run_id:actor.run.run_id,target_task_id:targetTaskId,native_session_id:nativeSessionId,agent_id:agentId2,turn_id:turnId};if(record3){await recordRelayDecision(composition,id,intent.actor_change_id,payload);return}await assertIssuedRelayAuthorization(composition,intent);const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256||JSON.stringify(await evidenceHashes(composition.filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical native replay receipt or Evidence changed");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const existing=await composition.decisions.read("change",intent.actor_change_id,id).catch(()=>null);if(existing?.origin!=="agent"||existing.category!=="contract"||existing.decision!==JSON.stringify(payload))throw new UsageError("Historical native capture differs from its canonical relay")}async function bindPostPublicationRelay(parsed,filesystem,composition){requireOptions(parsed.options,["actor-run","run","relay"]);const targetTaskId=parsed.positionals[2];if(!targetTaskId?.startsWith("TASK-"))throw new UsageError("Exact historical Task is required");const actor=await composition.runs.read(required2(parsed.options["actor-run"],"actor Run"));await assertRelayActor(composition,actor.run.run_id,actor.run.task_id??"",actor.run.execution_id??"");const intent=await readRelayIntent(composition,actor,targetTaskId,required2(parsed.options.relay,"relay intent"));if(!intent)throw new UsageError("Exact issued relay intent is required");await authenticatedRelayForCapture(composition,actor,targetTaskId,parsed.options.relay);const target=(await composition.tasks.read(targetTaskId)).task;const child=await composition.runs.read(required2(parsed.options.run,"historical Run"));const owners2=(await composition.runs.list()).filter(run=>run.status==="running"&&run.run.task_id===targetTaskId);if(target.status!=="executing"||target.revision!==intent.expected_task_revision+1||target.change_id!==intent.target_change_id||owners2.length!==1||owners2[0]?.run.run_id!==child.run.run_id||child.status!=="running"||child.run.parent_run_id!==actor.run.run_id||child.run.agent!=="agent-orchestrator"||child.run.run_role!=="subagent"||child.run.run_purpose!=="orchestration"||child.run.client!=="codex-subagent"||child.run.task_id!==targetTaskId||child.run.change_id!==intent.target_change_id||child.run.execution_id!==intent.target_execution_id||child.run.spec_id!==intent.target_spec_id||child.run.conversation_id!==actor.run.conversation_id||!child.run.client_thread_id||!child.run.client_turn_id||!child.run.model||!child.run.reasoning_effort)throw new UsageError("Relay binding needs one exact observed historical Task Run");if(intent.retry_predecessor_run_id){const captureId=relayCaptureId(actor.run.run_id,child.run.client_thread_id,child.run.client_turn_id);const captureRecord=await composition.decisions.read("change",intent.actor_change_id,captureId).catch(()=>null);let capture2=null;try{capture2=JSON.parse(captureRecord?.decision??"")}catch{}if(captureRecord?.origin!=="agent"||captureRecord.category!=="contract"||!capture2||capture2.intent_id!==parsed.options.relay||capture2.actor_run_id!==actor.run.run_id||capture2.target_task_id!==targetTaskId||capture2.agent_id!==child.run.client_thread_id||capture2.turn_id!==child.run.client_turn_id)throw new UsageError("Relay binding requires the exact native retry capture");await assertRelayNativeCapture(composition,actor,targetTaskId,parsed.options.relay,capture2.native_session_id,child.run.client_thread_id,child.run.client_turn_id,false)}const receipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256)throw new UsageError("Relay receipt bytes changed");await assertIssuedReceipt(filesystem,composition,receipt);if(JSON.stringify(await evidenceHashes(filesystem,composition,receipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence bytes changed before relay binding");const id=relayBindingId(child.run.run_id);const binding={schema_version:1,kind:"post_publication_relay_binding",intent_id:parsed.options.relay,actor_run_id:actor.run.run_id,target_run_id:child.run.run_id,target_task_id:targetTaskId,target_execution_id:intent.target_execution_id,target_spec_id:intent.target_spec_id,receipt_sha256:intent.receipt_sha256,client_thread_id:child.run.client_thread_id,client_turn_id:child.run.client_turn_id,candidate_sha:intent.candidate_sha,evidence_sha256:intent.evidence_sha256};await recordRelayDecision(composition,id,intent.actor_change_id,binding);return{bound:true,binding_id:id,target_run_id:child.run.run_id,receipt_sha256:intent.receipt_sha256}}async function authenticatedBoundRelay(root,composition){if(root.run.task_id===null||root.run.parent_run_id===null||root.run.run_purpose!=="orchestration")return null;const actor=await composition.runs.read(root.run.parent_run_id);if(actor.run.change_id==null)return null;const bindingRecord=await composition.decisions.read("change",actor.run.change_id,relayBindingId(root.run.run_id)).catch(()=>null);if(bindingRecord?.origin!=="agent"||bindingRecord.category!=="contract")return null;let binding;try{binding=JSON.parse(bindingRecord.decision)}catch{throw new UsageError("Post-publication Evidence binding is invalid")}const intent=await readRelayIntent(composition,actor,root.run.task_id,binding.intent_id);if(!intent)throw new UsageError("Bound post-publication relay intent is missing");await assertIssuedRelayAuthorization(composition,intent);if(binding.schema_version!==1||binding.kind!=="post_publication_relay_binding"||binding.intent_id!==relayIntentId(actor.run.run_id,root.run.task_id,binding.intent_id===relayIntentId(actor.run.run_id,root.run.task_id)?void 0:intent.current_state_sha256)||binding.actor_run_id!==actor.run.run_id||binding.target_run_id!==root.run.run_id||binding.target_task_id!==root.run.task_id||binding.target_execution_id!==root.run.execution_id||binding.target_spec_id!==root.run.spec_id||binding.client_thread_id!==root.run.client_thread_id||binding.client_turn_id!==root.run.client_turn_id||binding.receipt_sha256!==intent.receipt_sha256||binding.candidate_sha!==intent.candidate_sha||JSON.stringify(binding.evidence_sha256)!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Post-publication Evidence binding differs from observed ancestry");const receipt=await readPostPublicationReceipt(composition.filesystem,intent.receipt_path);if(sha2(JSON.stringify(receipt))!==intent.receipt_sha256)throw new UsageError("Post-publication receipt changed after binding");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const actual=await evidenceHashes(composition.filesystem,composition,receipt);if(JSON.stringify(actual)!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence bytes changed after binding");return{intent,evidenceIds:new Set(Object.keys(actual))}}async function historicalRelayEvidenceIds(root,composition){return(await authenticatedBoundRelay(root,composition))?.evidenceIds??new Set}var init_post_publication_relay_binding=__esm({"src/post-publication-relay-binding.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_contract();init_post_publication_relay_proof()}});async function assertRelayRetryPredecessor(composition,actor,predecessorRunId,receipt,task,change,execution,spec){const predecessor=await composition.runs.read(predecessorRunId);const bound=await authenticatedBoundRelay(predecessor,composition);const prior=bound?.intent;const parentAdvance=prior?.retry_predecessor_run_id?0:1;if(predecessor.finished?.status!=="completed"||predecessor.finalization_decision!==null||predecessor.run.parent_run_id!==actor.run.run_id||predecessor.run.task_id!==task.id||!task.status_reason?.includes(predecessorRunId)||!Number.isSafeInteger(task.attempt_count)||!prior||prior.actor_run_id!==actor.run.run_id||prior.target_task_id!==task.id||prior.receipt_sha256!==sha2(JSON.stringify(receipt))||task.revision!==prior.expected_task_revision+2||prior.expected_task_attempt_count!==void 0&&task.attempt_count!==prior.expected_task_attempt_count+1||change.revision!==prior.expected_change_revision+parentAdvance||execution.revision!==prior.expected_execution_revision+parentAdvance||spec.revision!==prior.expected_spec_revision+parentAdvance)throw new UsageError("Historical retry requires its exact terminal bound predecessor");return prior}var init_post_publication_relay_retry=__esm({"src/post-publication-relay-retry.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_binding();init_post_publication_relay_contract()}});var post_publication_relay_exports={};__export(post_publication_relay_exports,{assertRelayNativeCapture:()=>assertRelayNativeCapture,authenticatedBoundRelay:()=>authenticatedBoundRelay,authenticatedRelayForCapture:()=>authenticatedRelayForCapture,authorizePostPublicationRelay:()=>authorizePostPublicationRelay,bindPostPublicationRelay:()=>bindPostPublicationRelay,historicalRelayEvidenceIds:()=>historicalRelayEvidenceIds,preparePostPublicationRelay:()=>preparePostPublicationRelay});async function authorizePostPublicationRelay(parsed,filesystem,composition,lifecycle){const preview2=await preparePostPublicationRelay({...parsed,flags:new Set([...parsed.flags].filter(flag=>flag!=="apply"))},filesystem,composition,lifecycle);if(preview2.applied!==false||!("intent"in preview2))throw new UsageError("Exact historical relay preview is required");const intent=preview2.intent;const macro=await composition.runs.read(intent.macro_run_id);const observed=await resolveRunClientInvocation(filesystem,macro.run.client);if(macro.status!=="running"||macro.run.parent_run_id!==null||macro.run.run_role!=="orchestrator"||observed.clientThreadId!==macro.run.client_thread_id||observed.clientTurnId!==macro.run.client_turn_id||!observed.userMessage?.trim()||observed.observedModel!==macro.run.model||observed.observedReasoningEffort!==macro.run.reasoning_effort)throw new UsageError("Historical relay authorization requires the observed macro root turn");if(!parsed.flags.has("apply"))return{authorized:false,authorization_id:intent.authorization_id,intent_id:preview2.intent_id};const observedMessageSha=sha2(required2(observed.userMessage,"observed user message"));return composition.runs.withUsageAttributionLock(async()=>{const lockedMacro=await composition.runs.read(intent.macro_run_id);const lockedObserved=await resolveRunClientInvocation(filesystem,lockedMacro.run.client);if(lockedMacro.status!=="running"||lockedMacro.run.parent_run_id!==null||lockedMacro.run.run_role!=="orchestrator"||lockedObserved.clientThreadId!==lockedMacro.run.client_thread_id||lockedObserved.clientTurnId!==lockedMacro.run.client_turn_id||!lockedObserved.userMessage?.trim()||sha2(lockedObserved.userMessage)!==observedMessageSha||lockedObserved.observedModel!==lockedMacro.run.model||lockedObserved.observedReasoningEffort!==lockedMacro.run.reasoning_effort)throw new UsageError("Observed macro root turn changed before relay authorization");const current=(await composition.tasks.read(intent.target_task_id)).task;const[change,execution,spec]=await Promise.all([composition.changes.read(intent.target_change_id).then(({change:change2})=>change2),composition.executions.read(intent.target_execution_id).then(({execution:execution2})=>execution2),composition.specs.read(intent.target_spec_id).then(({spec:spec2})=>spec2)]);const cycle=JSON.parse(await filesystem.readText(cyclePath4));if(current.status!=="blocked"||closureStateHash(current,change,execution,spec,cycle)!==intent.current_state_sha256)throw new UsageError("Historical closure preview changed before macro authorization");if(intent.retry_predecessor_run_id){const receipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);await assertRelayRetryPredecessor(composition,await composition.runs.read(intent.actor_run_id),intent.retry_predecessor_run_id,receipt,current,change,execution,spec)}const payload=await authorizationPayloadForIntent(composition,intent,observedMessageSha);await recordRelayDecision(composition,intent.authorization_id,intent.actor_change_id,payload);return{authorized:true,authorization_id:intent.authorization_id,intent_id:preview2.intent_id}})}async function preparePostPublicationRelay(parsed,filesystem,composition,lifecycle){requireOptions(parsed.options,["receipt","actor-task","actor-execution","run","expected-revision"]);const targetTaskId=parsed.positionals[2];if(!targetTaskId?.startsWith("TASK-"))throw new UsageError("Exact historical Task is required");const actor=await assertRelayActor(composition,required2(parsed.options.run,"actor Run"),required2(parsed.options["actor-task"],"actor Task"),required2(parsed.options["actor-execution"],"actor Execution"));const receiptPath2=required2(parsed.options.receipt,"receipt path");const receipt=await readPostPublicationReceipt(filesystem,receiptPath2);if(receipt.target_spec_id===null)throw new UsageError("Task-first historical closure uses resume-post-publication, not a SPEC relay");if(receipt.target_task_id!==targetTaskId)throw new UsageError("Post-publication receipt targets another Task");await assertIssuedReceipt(filesystem,composition,receipt);const hashes=await evidenceHashes(filesystem,composition,receipt);const[{task},{change},{execution},{spec},{task:actorTask}]=await Promise.all([composition.tasks.read(targetTaskId),composition.changes.read(receipt.target_change_id),composition.executions.read(receipt.target_execution_id),composition.specs.read(receipt.target_spec_id),composition.tasks.read(required2(actor.run.task_id,"actor Task"))]);if(!actorTask.plan_hash||!/^[a-f0-9]{64}$/.test(actorTask.plan_hash)||!actorTask.objective)throw new UsageError("Delegated Task plan hash is required for historical closure");const cycle=JSON.parse(await filesystem.readText(cyclePath4));const currentHash=closureStateHash(task,change,execution,spec,cycle);const expected=Number(parsed.options["expected-revision"]);const id=task.status==="blocked"?relayIntentId(actor.run.run_id,targetTaskId,currentHash):parsed.options.relay??relayIntentId(actor.run.run_id,targetTaskId);const existing=await readRelayIntent(composition,actor,targetTaskId,id);const activeParents=change.status==="executing"&&execution.status==="running"&&spec.status==="active";const retryPredecessor=task.status==="blocked"&&activeParents?await assertRelayRetryPredecessor(composition,actor,required2(parsed.options["predecessor-run"],"terminal predecessor Run"),receipt,task,change,execution,spec):null;const parentRevisionAdvance=existing?.retry_predecessor_run_id===void 0?1:0;const resumedStateMatches=existing!==null&&task.revision===expected+1&&(existing.expected_task_attempt_count===void 0||task.attempt_count===existing.expected_task_attempt_count+1)&&change.status==="executing"&&change.revision===existing.expected_change_revision+parentRevisionAdvance&&execution.status==="running"&&execution.revision===existing.expected_execution_revision+parentRevisionAdvance&&spec.status==="active"&&spec.revision===existing.expected_spec_revision+parentRevisionAdvance;if(!Number.isSafeInteger(expected)||expected<1||(task.status==="blocked"?task.revision!==expected:task.status!=="executing"||!resumedStateMatches)||existing!==null&&existing.expected_task_revision!==expected||existing!==null&&parsed.options["predecessor-run"]!==void 0&&parsed.options["predecessor-run"]!==existing.retry_predecessor_run_id||task.status==="blocked"&&(!(change.status==="blocked"&&execution.status==="blocked"&&spec.status==="blocked"||retryPredecessor!==null)||spec.target_release!==receipt.target_release||execution.origin.type!=="spec"||execution.origin.spec_id!==spec.id))throw new UsageError("Historical Task revision or relay state changed");if(task.change_id!==receipt.target_change_id||actor.run.task_id===task.id||(await composition.runs.list()).some(run=>run.run.task_id===task.id&&run.status==="running"))throw new UsageError("Historical Task has another owner or target");const intent={schema_version:1,kind:"post_publication_relay_intent",actor_run_id:actor.run.run_id,...existing===null?{actor_client_thread_id:required2(actor.run.client_thread_id,"actor client thread"),actor_client_turn_id:required2(actor.run.client_turn_id,"actor client turn")}:existing.actor_client_thread_id===void 0?{}:{actor_client_thread_id:existing.actor_client_thread_id,actor_client_turn_id:existing.actor_client_turn_id},actor_task_id:required2(actor.run.task_id,"actor Task"),actor_change_id:required2(actor.run.change_id,"actor Change"),actor_execution_id:required2(actor.run.execution_id,"actor Execution"),actor_task_revision:actorTask.revision,actor_plan_hash:actorTask.plan_hash,actor_objective_sha256:sha2(actorTask.objective),macro_run_id:required2(actor.run.parent_run_id,"macro Run"),authorization_id:existing?.authorization_id??relayAuthorizationId(actor.run.run_id,task.id,currentHash),receipt_path:receiptPath2,receipt_sha256:sha2(JSON.stringify(receipt)),target_task_id:task.id,target_change_id:receipt.target_change_id,target_execution_id:receipt.target_execution_id,target_spec_id:receipt.target_spec_id,expected_task_revision:expected,expected_change_revision:existing?.expected_change_revision??change.revision,expected_execution_revision:existing?.expected_execution_revision??execution.revision,expected_spec_revision:existing?.expected_spec_revision??spec.revision,...existing?.retry_predecessor_run_id||retryPredecessor?{retry_predecessor_run_id:existing?.retry_predecessor_run_id??parsed.options["predecessor-run"],expected_task_attempt_count:existing?.expected_task_attempt_count??task.attempt_count}:{},receipt_state_sha256:receipt.state_sha256,current_state_sha256:existing?.current_state_sha256??currentHash,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,evidence_sha256:hashes};if(existing!==null&&JSON.stringify(existing)!==JSON.stringify(intent))throw new UsageError("Historical relay differs from its canonical intent");if(!parsed.flags.has("apply"))return{applied:false,intent_id:id,expected_task_revision:expected,expected_change_revision:intent.expected_change_revision,expected_execution_revision:intent.expected_execution_revision,expected_spec_revision:intent.expected_spec_revision,target_task_id:task.id,authorization_id:intent.authorization_id,current_state_sha256:intent.current_state_sha256,receipt_state_sha256:intent.receipt_state_sha256,intent};await assertLiveRelayAuthority(composition,intent);return composition.runs.withUsageAttributionLock(async()=>{const freshReceipt=await readPostPublicationReceipt(filesystem,intent.receipt_path);if(sha2(JSON.stringify(freshReceipt))!==intent.receipt_sha256||freshReceipt.target_task_id!==intent.target_task_id)throw new UsageError("Post-publication receipt changed before relay apply");await assertRelayActor(composition,intent.actor_run_id,intent.actor_task_id,intent.actor_execution_id);if((await composition.runs.list()).some(run=>run.run.task_id===intent.target_task_id&&run.status==="running"))throw new UsageError("Historical Task has another owner before relay apply");const fresh=(await composition.tasks.read(task.id)).task;const[freshChange,freshExecution,freshSpec]=await Promise.all([composition.changes.read(intent.target_change_id).then(({change:change2})=>change2),composition.executions.read(intent.target_execution_id).then(({execution:execution2})=>execution2),composition.specs.read(intent.target_spec_id).then(({spec:spec2})=>spec2)]);const freshActorTask=(await composition.tasks.read(intent.actor_task_id)).task;await assertLiveRelayAuthority(composition,intent);if(freshActorTask.revision!==intent.actor_task_revision||freshActorTask.plan_hash!==intent.actor_plan_hash)throw new UsageError("Delegated Task authorization changed before relay apply");if(fresh.status==="executing"&&existing!==null){const advance=intent.retry_predecessor_run_id?0:1;if(fresh.revision!==expected+1||intent.expected_task_attempt_count!==void 0&&fresh.attempt_count!==intent.expected_task_attempt_count+1||freshChange.status!=="executing"||freshChange.revision!==intent.expected_change_revision+advance||freshExecution.status!=="running"||freshExecution.revision!==intent.expected_execution_revision+advance||freshSpec.status!=="active"||freshSpec.revision!==intent.expected_spec_revision+advance)throw new UsageError("Historical relay replay changed after its canonical intent");return{applied:true,reused:true,intent_id:id,target_task_id:task.id}}if(fresh.status!=="blocked"||fresh.revision!==expected||intent.expected_task_attempt_count!==void 0&&fresh.attempt_count!==intent.expected_task_attempt_count||freshChange.status!==(intent.retry_predecessor_run_id?"executing":"blocked")||freshChange.revision!==intent.expected_change_revision||freshExecution.status!==(intent.retry_predecessor_run_id?"running":"blocked")||freshExecution.revision!==intent.expected_execution_revision||freshSpec.status!==(intent.retry_predecessor_run_id?"active":"blocked")||freshSpec.revision!==intent.expected_spec_revision)throw new UsageError("Historical Task changed before relay apply");const freshCycle=JSON.parse(await filesystem.readText(cyclePath4));if(closureStateHash(fresh,freshChange,freshExecution,freshSpec,freshCycle)!==intent.current_state_sha256)throw new UsageError("Historical closure snapshot changed before relay apply");if(intent.retry_predecessor_run_id)await assertRelayRetryPredecessor(composition,actor,intent.retry_predecessor_run_id,freshReceipt,fresh,freshChange,freshExecution,freshSpec);await assertIssuedReceipt(filesystem,composition,freshReceipt);if(JSON.stringify(await evidenceHashes(filesystem,composition,freshReceipt))!==JSON.stringify(intent.evidence_sha256))throw new UsageError("Historical Evidence changed before relay apply");await recordRelayDecision(composition,id,intent.actor_change_id,intent);await lifecycle.startTaskWithSnapshot(task.id,"resume",{targetTaskId:task.id,targetRelease:freshReceipt.target_release,publishedSha:freshReceipt.proof.published_sha,cycleSha256:freshReceipt.proof.cycle_sha256});return{applied:true,reused:false,intent_id:id,target_task_id:task.id}})}var cyclePath4;var init_post_publication_relay=__esm({"src/post-publication-relay.ts"(){"use strict";init_cli_arguments();init_post_publication_recovery();init_post_publication_relay_contract();init_post_publication_relay_proof();init_run_client_invocation();init_post_publication_relay_retry();init_post_publication_relay_binding();cyclePath4=".agents/config/release-cycle.json"}});var post_publication_task_first_exports={};__export(post_publication_task_first_exports,{taskFirstPublishedBoundary:()=>taskFirstPublishedBoundary});async function taskFirstPublishedBoundary(root,composition){const run=root.run;if(run.parent_run_id!==null||run.task_id===null||run.spec_id!==null||!run.client_turn_id||!run.execution_id||!run.continuation_of_run_id)return null;const sequence=await composition.executions.readPostPublicationSequence(run.client_turn_id);const claim=sequence?.steps.find(step=>step.successor_run_id===run.run_id);if(claim===void 0&&sequence?.steps.some(step=>step.origin.type==="task"&&step.target_task_id===run.task_id))throw new UsageError("Task-first publication claim differs from the closure owner");if(claim?.origin.type!=="task")return null;if(claim.predecessor_run_id!==run.continuation_of_run_id||claim.target_task_id!==run.task_id||claim.origin.task_id!==run.task_id||claim.execution_id!==run.execution_id)throw new UsageError("Task-first publication claim differs from the closure owner");const receipt=await readPostPublicationReceipt(composition.filesystem,`.local/recovery/post-publication/${claim.authorization_sha256}.json`);const{task}=await composition.tasks.read(run.task_id);if(receipt.target_spec_id!==null||receipt.target_task_id!==run.task_id||receipt.target_change_id!==run.change_id||receipt.target_execution_id!==run.execution_id||receipt.actor_run_id!==sequence?.maintenance_run_id||receipt.client_thread_id!==run.client_thread_id||sha(JSON.stringify(receipt))!==claim.authorization_sha256||await effectiveTaskRelease(task,composition)!==receipt.target_release)throw new UsageError("Task-first publication receipt differs from the closure owner");const{execution}=await composition.executions.read(run.execution_id);if(execution.origin.type!=="task"||execution.origin.task_id!==run.task_id||execution.dag.nodes.length!==1||execution.dag.nodes[0]?.task_id!==run.task_id||execution.dag.nodes[0]?.change_id!==run.change_id)throw new UsageError("Task-first publication Execution has another owner");await assertIssuedReceipt(composition.filesystem,composition,receipt,"issued");const hashes=await evidenceHashes(composition.filesystem,composition,receipt);await assertHistoricalProofSnapshot(receipt,composition,root);return{target_task_id:run.task_id,target_spec_id:null,candidate_sha:receipt.proof.candidate_sha,published_sha:receipt.proof.published_sha,evidence_ids:Object.keys(hashes)}}var init_post_publication_task_first=__esm({"src/post-publication-task-first.ts"(){"use strict";init_cli_arguments();init_post_publication_receipt();init_post_publication_relay_proof();init_post_publication_snapshot();init_release_cycle()}});async function deliveryVerifier(repositories,validations,tasks){for(const review of validations.filter(item=>isReviewKind(item.kind))){const task=tasks.find(item=>item.id===review.task_id);if(task?.result?.completed_run_id==null)continue;const run=await readRequiredRun(repositories,task.result.completed_run_id);const approval=verifierFrom([review],run.run.agent,run.run.run_id);if(approval!==null)return approval}return null}async function assertExecutionDescendantsComplete(repositories,executionId,nodes){for(const node of nodes){const{task}=await repositories.tasks.read(node.task_id);if(task.change_id!==node.change_id){throw new LifecycleGateError(`Execution ${executionId} DAG ownership mismatch for ${task.id}`)}if(task.status!=="completed"){throw new LifecycleGateError(`Execution Task must be completed: ${formatLifecycleState(task)}`)}}}async function assertSixStageDeliveryCoverage(filesystem,layout,repositories,task,result2,executionId,enforceLegacyRiskCounts,assurance){const signals=effectiveTaskRiskSignals(task);if(task.assurance_risk_signals_source==="explicit"&&task.assurance_risk_signals?.editorial_delivery===true&&assurance===null)throw new LifecycleGateError("Editorial delivery requires assurance.version: 1");await assertTaskSixStageCoverage({filesystem,layout,repositories},task,result2,executionId,enforceLegacyRiskCounts,assurance===null||!assertEditorialDeliveryEligibility(task,signals))}async function deliveryCandidateProofs(filesystem,layout,tasks,config2,compositionOverride){const bundle=await readAssuranceBundle(filesystem,layout,tasks);const composition=compositionOverride??(await Promise.resolve().then(()=>(init_v2_router(),v2_router_exports))).createV2Composition(filesystem,layout);const boundaries=(await Promise.all(tasks.map(async task=>task.status==="completed"&&task.result?.completed_run_id?historicalPublishedBoundaryForTask(task,await composition.runs.read(task.result.completed_run_id),composition):null))).filter(boundary=>boundary!==null);if(boundaries.length>1)throw new LifecycleGateError("Historical publication has multiple candidate boundaries");const publishedBoundary=boundaries[0];const expected=config2.require_final_commit?(await inspectFinalProductCandidate(filesystem.root,bundle.validations,bundle.evidences,void 0,void 0,void 0,publishedBoundary)).commit:null;const validations=expected===null?bundle.validations:bundle.validations.filter(artifact=>artifact.commit_sha===expected);const evidences=expected===null?bundle.evidences:bundle.evidences.filter(artifact=>artifact.commit_sha===expected);return{bundle,expected,validations,evidences}}async function historicalPublishedBoundaryForTask(task,run,composition){if(run.run.task_id!==task.id||run.run.execution_id===null)return null;if(run.run.spec_id===null){const{taskFirstPublishedBoundary:taskFirstPublishedBoundary2}=await Promise.resolve().then(()=>(init_post_publication_task_first(),post_publication_task_first_exports));return taskFirstPublishedBoundary2(run,composition)}const bound=await authenticatedBoundRelay(run,composition);if(!bound)return null;const{intent,evidenceIds}=bound;const{execution}=await composition.executions.read(intent.target_execution_id);if(evidenceIds.size===0||intent.target_task_id!==task.id||intent.target_execution_id!==run.run.execution_id||intent.target_spec_id!==run.run.spec_id||execution.origin.type!=="spec"||execution.origin.spec_id!==intent.target_spec_id)throw new LifecycleGateError("Historical publication boundary has different Task ownership");return{target_task_id:intent.target_task_id,target_spec_id:intent.target_spec_id,candidate_sha:intent.candidate_sha,published_sha:intent.published_sha,evidence_ids:[...evidenceIds]}}function assertHistoricalRelayChangedFiles(boundary,changedFiles){if(!boundary)return;if(changedFiles.some(path=>!path.startsWith(".agents/records/")||path.includes("\\")||path.split("/").includes("..")||path.endsWith("/")))throw new LifecycleGateError("Historical publication relay permits only causal record files")}async function tasksForChange(repositories,changeId,expectedIds){const tasks=await Promise.all(expectedIds.map(taskId=>repositories.tasks.read(taskId)));for(const{task}of tasks){if(task.change_id!==changeId){throw new LifecycleGateError(`Task ${task.id} does not belong to Change ${changeId}`)}}return tasks.map(({task})=>task)}var init_lifecycle_v2_delivery_assurance=__esm({"src/lifecycle-v2-delivery-assurance.ts"(){"use strict";init_candidate_resolution();init_editorial_delivery_assurance();init_lifecycle_assurance_v2();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_lifecycle_run_attribution();init_post_publication_relay()}});async function readAssuranceRunAncestry(repository2,ids2){const result2=new Map;for(const owner of new Set(ids2)){const visited=new Set;let id=owner;while(id!==null){if(visited.has(id)||visited.size>=256)throw new Error("Assurance Run ancestry is cyclic or exceeds its depth limit");visited.add(id);let run=result2.get(id);if(!run){run=await repository2.read(id);if(run.run.run_id!==id)throw new Error("Assurance Run identity mismatch");result2.set(id,run)}id=run.run.parent_run_id}}return result2}var init_assurance_run_ancestry=__esm({"src/assurance-run-ancestry.ts"(){"use strict"}});import{execFile as execFile10}from"node:child_process";import{randomUUID as randomUUID6}from"node:crypto";import{lstat as lstat8,mkdtemp,readdir as readdir3,readFile as readFile9,realpath as realpath8,rm as rm5,unlink as unlink3,writeFile as writeFile3}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname6,join as join3,resolve as resolve12}from"node:path";import{promisify as promisify10}from"node:util";async function withCandidateWorkspace(repositoryPath,commit,operation){if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit))throw new Error("candidate validation requires a full commit SHA");const started=performance.now();const repository2=resolve12(repositoryPath);const validationRoot=await realpath8(tmpdir());const path=await mkdtemp(join3(validationRoot,`zaip-candidate-${basename2(repository2)}-`));const ownerPath=`${path}.owner`;const owner=randomUUID6();const assertOwnedPath=async(required3=false)=>{if(dirname6(resolve12(path))!==validationRoot||!basename2(path).startsWith("zaip-candidate-"))throw new Error("Candidate checkout path escaped its owner");const info=await lstat8(path).catch(error51=>{if(error51.code==="ENOENT")return null;throw error51});if(required3&&info===null)throw new Error("Owned candidate directory disappeared");if(info!==null&&(!info.isDirectory()||info.isSymbolicLink()||await realpath8(path)!==path))throw new Error("Candidate checkout is no longer an owned directory")};try{await assertOwnedPath(true);await writeFile3(ownerPath,owner,{flag:"wx",mode:384})}catch(setupError){try{await assertOwnedPath(true);const marker=await readFile9(ownerPath,"utf8").catch(error51=>{if(error51.code==="ENOENT")return null;throw error51});if(marker!==null&&marker!==owner)throw new Error("Candidate ownership marker changed during setup");await rm5(path,{recursive:true,force:true});if(marker!==null)await unlink3(ownerPath)}catch(cleanupError){throw new AggregateError([setupError,cleanupError],"Candidate setup and cleanup failed")}throw setupError}const assertOwnerMarker=async()=>{if(await readFile9(ownerPath,"utf8")!==owner)throw new Error("Candidate checkout ownership marker changed")};const assertOwned=async()=>{await assertOwnerMarker();await assertOwnedPath()};const workspace=Object.freeze({path,repository:repository2,commit});let attached=false;let value;let preparationMs=0;let cleanupMs=0;let primaryFailure;let cleanupFailure;try{await git2(repository2,["worktree","add","--detach",path,commit]);attached=true;owners.set(workspace,{running:false});preparationMs=Math.round(performance.now()-started);value=await operation(workspace)}catch(error51){primaryFailure=error51}finally{const cleanupStarted=performance.now();owners.delete(workspace);try{await assertOwned();if(await lstat8(path).catch(()=>null))await detachCandidateLinks(path);let unregisterFailed=false;const listedBefore=attached?null:await git2(repository2,["worktree","list","--porcelain"]);const partiallyAttached=listedBefore?.stdout.split(/\r?\n/).some(line=>line.startsWith("worktree ")&&resolve12(line.slice(9))===resolve12(path))??false;if(attached||partiallyAttached){try{await git2(repository2,["worktree","remove","--force","--force",path])}catch{unregisterFailed=true}}await assertOwned();if(await lstat8(path).catch(()=>null))await rm5(path,{recursive:true,force:true,maxRetries:3,retryDelay:100});if(unregisterFailed){const listed=await git2(repository2,["worktree","list","--porcelain"]);const registered=listed.stdout.split(/\r?\n/).some(line=>line.startsWith("worktree ")&&resolve12(line.slice(9))===resolve12(path));if(registered)await git2(repository2,["worktree","remove","--force","--force",path])}await assertOwnerMarker();await unlink3(ownerPath);cleanupMs=Math.round(performance.now()-cleanupStarted)}catch(error51){cleanupFailure=error51}}if(cleanupFailure!==void 0){const message2=error51=>error51 instanceof Error?error51.message:String(error51);throw new AggregateError(primaryFailure===void 0?[cleanupFailure]:[primaryFailure,cleanupFailure],`${primaryFailure===void 0?"Candidate operation finished":message2(primaryFailure)}; cleanup incomplete at ${path}: ${message2(cleanupFailure)}`)}if(primaryFailure!==void 0)throw primaryFailure;return{value,preparation_ms:preparationMs,cleanup_ms:cleanupMs}}async function detachCandidateLinks(directory2){for(const entry2 of await readdir3(directory2,{withFileTypes:true})){const path=join3(directory2,entry2.name);if(entry2.isSymbolicLink())await unlink3(path);else if(entry2.isDirectory())await detachCandidateLinks(path)}}function claimCandidateWorkspace(workspace,repository2,commit){const owner=owners.get(workspace);if(!owner||owner.running||workspace.repository!==resolve12(repository2)||workspace.commit!==commit)throw new Error("candidate workspace must be owned, sequential and bound to the same repository and SHA");owner.running=true;return()=>{owner.running=false}}function git2(cwd,args){return exec4("git",args,{cwd,shell:false,windowsHide:true,encoding:"utf8",timeout:3e5,env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/^(GIT_|NODE_OPTIONS$)/i.test(key)))})}var exec4,owners;var init_candidate_validation_session=__esm({"src/candidate-validation-session.ts"(){"use strict";exec4=promisify10(execFile10);owners=new WeakMap}});import{execFile as execFile11}from"node:child_process";import{constants}from"node:fs";import{access,lstat as lstat9,realpath as realpath9,stat as stat3}from"node:fs/promises";import{dirname as dirname7,isAbsolute as isAbsolute7,relative as relative8,resolve as resolve13}from"node:path";import{promisify as promisify11}from"node:util";async function validateIsolatedGitCandidate(input,workspace){if(workspace===void 0){const group=await withCandidateWorkspace(input.repository_path,input.commit_sha,owned=>validateIsolatedGitCandidate(input,owned));return{...group.value,timings_ms:{...group.value.timings_ms,preparation:group.preparation_ms,cleanup:group.cleanup_ms}}}const release=claimCandidateWorkspace(workspace,input.repository_path,input.commit_sha);try{return await validateInWorkspace(input,workspace.path)}finally{release()}}async function validateInWorkspace(input,worktree){const precheckStarted=performance.now();if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(input.commit_sha))throw new Error("candidate validation requires a full commit SHA");if(!isAbsolute7(input.executable_path))throw new Error("candidate validation requires an absolute executable path");if(!Array.isArray(input.args)||input.args.some(argument=>typeof argument!=="string"))throw new Error("candidate validation requires a JSON string array of arguments");const executable=resolve13(input.executable_path);const executableStat=await stat3(executable).catch(()=>null);if(executableStat===null||!executableStat.isFile())throw new Error("candidate validation executable path is not a file");await access(executable,constants.X_OK).catch(()=>{throw new Error("candidate validation executable path is not executable")});const repository2=resolve13(input.repository_path);const toolRelative=relative8(repository2,executable);if(toolRelative===""||!toolRelative.startsWith("..")&&!isAbsolute7(toolRelative))throw new Error("candidate validation requires an external toolchain executable, not a shared-checkout executable");const sourcePaths=[repository2.toLowerCase(),repository2.replaceAll("\\","/").toLowerCase()];if(input.args.some(argument=>sourcePaths.some(path=>argument.toLowerCase().includes(path))))throw new Error("candidate validation arguments must use candidate-relative paths, not shared-checkout paths");if(await realpath9(executable)!==await realpath9(process.execPath))throw new Error("candidate validation requires the current host Node runtime");const harness=input.args[0];if(!harness||harness.startsWith("-")||isAbsolute7(harness)||harness.includes("\\")||harness.includes(":")||harness.includes("\0")||harness.split("/").some(part=>["",".",".."].includes(part))||!/\.(?:c|m)?js$/.test(harness))throw new Error("candidate validation requires a committed relative Node harness; eval, loaders and inline code are not allowed");const commit=await gitOutput(repository2,["rev-parse",`${input.commit_sha}^{commit}`]);const entry2=await gitOutput(repository2,["--literal-pathspecs","ls-tree",commit,"--",harness]);const blob=entry2.match(/^100(?:644|755) blob ([a-f0-9]{40,64})\t/);if(!blob?.[1])throw new Error("candidate harness must be a committed regular file");const tree=await gitOutput(repository2,["rev-parse",`${commit}^{tree}`]);const timeout=input.timeout_ms??12e4;if(!Number.isInteger(timeout)||timeout<1||timeout>36e5)throw new Error("candidate validation timeout must be between 1 and 3600000 milliseconds");{const head=await gitOutput(worktree,["rev-parse","HEAD"]);const worktreeTree=await gitOutput(worktree,["rev-parse","HEAD^{tree}"]);if(head!==commit||worktreeTree!==tree)throw new Error("isolated worktree does not match requested candidate commit and tree");await assertClean(worktree,"before execution");let ancestor=resolve13(worktree,harness);while(ancestor!==worktree){if((await lstat9(ancestor)).isSymbolicLink())throw new Error("candidate harness cannot follow a symlink");ancestor=dirname7(ancestor)}const startedAt=new Date().toISOString();const precheckMs=performance.now()-precheckStarted;const processStarted=performance.now();const execution=await execute(executable,input.args,worktree,timeout);const processMs=Math.round(performance.now()-processStarted);const finishedAt=new Date().toISOString();const verificationStarted=performance.now();const cleanAfter=await isClean(worktree);const finalHead=await gitOutput(worktree,["rev-parse","HEAD"]);const finalTree=await gitOutput(worktree,["rev-parse","HEAD^{tree}"]);const candidateChanged=finalHead!==commit||finalTree!==tree;const diagnostic=candidateChanged?"candidate HEAD or tree changed during execution":!cleanAfter?"candidate has uncommitted changes after execution":execution.diagnostic;return{status:execution.exitCode===0&&cleanAfter&&!candidateChanged?"passed":"failed",command:JSON.stringify([executable,...input.args]),output:{stdout:safeOutput(execution.stdout),stderr:safeOutput(execution.stderr)},timings_ms:{process:processMs,verification:Math.round(precheckMs+performance.now()-verificationStarted)},candidate_execution:{kind:"isolated_git_worktree",protocol:"committed_node_harness_v1",harness_path:harness,harness_blob_sha:blob[1],commit_sha:commit,tree_sha:tree,exit_code:execution.exitCode,diagnostic,started_at:startedAt,finished_at:finishedAt}}}}function safeOutput(value){const redacted=redactSensitive(value);try{assertSafeRecordContent(redacted);return redacted}catch{return"[REDACTED: command output contained sensitive values]"}}async function assertClean(worktree,phase2){if(!await isClean(worktree))throw new Error(`isolated worktree is dirty ${phase2}`)}async function isClean(worktree){return await gitOutput(worktree,["status","--porcelain","--untracked-files=all"])===""}async function execute(executable,args,cwd,timeout){try{const output2=await execFileAsync7(executable,[...args],{cwd,shell:false,windowsHide:true,env:allowedExecutionEnvironment(),timeout,maxBuffer:1024*1024,encoding:"utf8"});return{exitCode:0,diagnostic:null,...output2}}catch(error51){const output2={stdout:error51!==null&&typeof error51==="object"&&"stdout"in error51?String(error51.stdout??"").slice(0,1024*1024):"",stderr:error51!==null&&typeof error51==="object"&&"stderr"in error51?String(error51.stderr??"").slice(0,1024*1024):""};if(isTimedOut(error51))return{exitCode:-1,diagnostic:"command timed out",...output2};if(hasExitCode(error51))return{exitCode:error51.code,diagnostic:`command exited with code ${error51.code}`,...output2};return{exitCode:-1,diagnostic:"command could not start",...output2}}}function allowedExecutionEnvironment(){return Object.fromEntries(executionEnvironmentKeys.flatMap(key=>{const value=process.env[key];return value===void 0?[]:[[key,value]]}))}function hasExitCode(error51){return error51!==null&&typeof error51==="object"&&"code"in error51&&typeof error51.code==="number"}function isTimedOut(error51){return error51!==null&&typeof error51==="object"&&("killed"in error51&&error51.killed===true||"signal"in error51&&error51.signal==="SIGTERM")}async function gitOutput(cwd,args){const{stdout}=await git3(cwd,args);return stdout.trim()}function git3(cwd,args){return execFileAsync7("git",[...args],{cwd,shell:false,windowsHide:true,encoding:"utf8",env:allowedExecutionEnvironment(),maxBuffer:10*1024*1024})}var execFileAsync7,executionEnvironmentKeys;var init_candidate_validation=__esm({"src/candidate-validation.ts"(){"use strict";init_src();init_candidate_validation_session();execFileAsync7=promisify11(execFile11);executionEnvironmentKeys=["APPDATA","COMSPEC","HOME","LANG","LOCALAPPDATA","LC_ALL","PATH","PATHEXT","Path","ProgramFiles","SYSTEMROOT","SystemRoot","TEMP","TMP","USERPROFILE","WINDIR"]}});import{execFile as execFile12}from"node:child_process";import{posix as posix8}from"node:path";import{promisify as promisify12}from"node:util";function ids(value,label){const values=value.split(",").map(item=>item.trim());if(values.length===0||values.some(item=>!item)||new Set(values).size!==values.length)throw new UsageError(`${label} requires unique nonempty ids`);return values}async function context(parsed,composition){if(parsed.options.task!==void 0||parsed.options.change!==void 0)throw new UsageError("--spec/--execution parental proof cannot include --task or --change");requireOptions(parsed.options,["spec","execution","run"]);const specId=parsed.options.spec;const executionId=parsed.options.execution;const runId=parsed.options.run;const[{spec},{execution},fold]=await Promise.all([composition.specs.read(specId),composition.executions.read(executionId),composition.runs.read(runId)]);if(execution.origin.type!=="spec"||execution.origin.spec_id!==specId||!["running","verifying"].includes(execution.status))throw new UsageError("Parental proof requires the active SPEC delivery Execution");const runs=await composition.runs.list();const byId2=new Map(runs.map(entry2=>[entry2.run.run_id,entry2]));let root=fold;const seen=new Set([runId]);while(root.run.parent_run_id!==null){if(seen.has(root.run.parent_run_id))throw new UsageError("Cyclic parental Run ancestry");seen.add(root.run.parent_run_id);const parent=byId2.get(root.run.parent_run_id);if(!parent||parent.run.execution_id!==executionId||parent.run.spec_id!==specId)throw new UsageError("Parental Run ancestry leaves the SPEC Execution");root=parent}if(fold.run.execution_id!==executionId||fold.run.spec_id!==specId||fold.run.task_id!==null||fold.run.change_id!==null||root.status!=="running"||root.run.task_id!==null||root.run.change_id!==null||root.run.execution_id!==executionId||root.run.spec_id!==specId||root.run.execution_kind!=="delivery"||root.run.entrypoint!=="spec"||root.run.agent!=="agent-orchestrator"||spec.status!=="active")throw new UsageError("Parental proof requires a linked active macro Run");const isRoot=runId===root.run.run_id&&fold.status==="running";const isReview2=fold.status==="completed"&&effectiveRunV2Role(fold.run)==="subagent"&&effectiveRunV2Purpose(fold.run)==="review"&&fold.run.agent==="agent-reviewer"&&descendant(runId,root.run.run_id,byId2);if(!isRoot&&!isReview2)throw new UsageError("Parental Run must be the active macro root or its completed reviewer descendant");return{spec,execution,fold,root,isReview:isReview2,directory:posix8.dirname(composition.executions.path(executionId))}}function descendant(runId,rootId,byId2){const seen=new Set;let parentId=byId2.get(runId)?.run.parent_run_id??null;while(parentId!==null&&!seen.has(parentId)){if(parentId===rootId)return true;seen.add(parentId);parentId=byId2.get(parentId)?.run.parent_run_id??null}return false}async function existingCommit(root,value){if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value))throw new UsageError("--commit requires a full lowercase Git SHA");try{const result2=await execFileAsync8("git",["rev-parse","--verify",`${value}^{commit}`],{cwd:root,shell:false,windowsHide:true,encoding:"utf8",timeout:15e3});if(result2.stdout.trim()!==value)throw new Error("noncanonical commit");return value}catch{throw new UsageError("--commit must resolve to an existing Git commit")}}async function runParentValidationCommand(action,parsed,filesystem,composition){if(action!=="execute"&&action!=="record")throw new UsageError("Unknown parental Validation action");assertSafeRecordContent(parsed.options);requireOptions(parsed.options,["id","acceptance","locators","commit","run","spec","execution",...action==="execute"?["executable","args"]:["outcome"]]);const owned=await context(parsed,composition);const acceptance=ids(parsed.options.acceptance,"--acceptance");if(acceptance.some(id2=>!owned.spec.acceptance_ids.includes(id2)))throw new UsageError("Parental Acceptance Criteria must belong to the SPEC");const kind=parsed.options.kind??"test";const prefix=prefixes[kind];if(!prefix||!parsed.options.id.startsWith(prefix)||!/^[A-Z0-9]+(?:-[A-Z0-9]+)*$/.test(parsed.options.id))throw new UsageError("Invalid parental Validation kind or id");if(owned.isReview!==reviewKinds.has(kind))throw new UsageError("Independent review must come from a completed reviewer child; execution uses the active macro root");if(action==="record"&&!owned.isReview)throw new UsageError("Parental implementation Validation requires isolated validation execute");if(action==="execute"&&owned.isReview)throw new UsageError("Reviews are recorded from reviewer results, not executed as commands");const commit=await existingCommit(filesystem.root,parsed.options.commit);const status=parsed.options.outcome??"passed";if(status!=="passed"&&status!=="failed")throw new UsageError("Parental outcome must be passed or failed");let observed=null;if(action==="execute"){let args;try{args=JSON.parse(parsed.options.args)}catch{throw new UsageError("--args requires a JSON string array")}if(!Array.isArray(args)||!args.every(item=>typeof item==="string"))throw new UsageError("--args requires a JSON string array");observed=await validateIsolatedGitCandidate({repository_path:filesystem.root,commit_sha:commit,executable_path:parsed.options.executable,args,...parsed.options["timeout-ms"]===void 0?{}:{timeout_ms:Number(parsed.options["timeout-ms"])}})}const id=parsed.options.id;const path=`${owned.directory}/artifacts/parent/tests/${id}.md`;const artifact=parentValidationArtifactV1Schema.parse({schema_version:3,scope:"spec_execution",id,kind,spec_id:owned.spec.id,execution_id:owned.execution.id,run_id:owned.fold.run.run_id,acceptance_ids:acceptance,executed_at:observed?.candidate_execution.finished_at??new Date().toISOString(),command:observed?.command??parsed.options.command??null,status:observed?.status??status,asserted_outcomes:ids(parsed.options["asserted-outcome"]??`validation ${status}`,"--asserted-outcome"),locators:ids(parsed.options.locators,"--locators"),author_id:parsed.options.author??owned.fold.run.agent,commit_sha:commit,...observed===null?{}:{candidate_execution:observed.candidate_execution},not_applicable_reason:null});if(owned.isReview&&artifact.author_id===owned.root.run.agent)throw new UsageError("Parental review author must differ from the macro author");if(artifact.author_id!==owned.fold.run.agent)throw new UsageError("Parental author must match the observed Run agent");await filesystem.writeTextAtomicExclusive(path,serializeMarkdown({metadata:artifact,body:`# Validation ${id}
3583
3583
  `}));return{validation:artifact,artifact_path:path,...observed===null?{}:{output:observed.output}}}async function runParentEvidenceCommand(action,parsed,filesystem,composition){if(action!=="record")throw new UsageError("Unknown parental Evidence action");assertSafeRecordContent(parsed.options);requireOptions(parsed.options,["id","summary","outcome","validation","run","spec","execution"]);if(parsed.options.outcome!=="passed")throw new UsageError("Parental Evidence requires passed outcome");const owned=await context(parsed,composition);if(owned.isReview)throw new UsageError("Parental Evidence belongs to the active macro Run");const id=parsed.options.id;if(!/^EVD-[A-Z0-9]+(?:-[A-Z0-9]+)*$/.test(id))throw new UsageError("Invalid Evidence id");const validationId=parsed.options.validation;const validationPath=`${owned.directory}/artifacts/parent/tests/${validationId}.md`;let validation;try{validation=parseMarkdown(await filesystem.readText(validationPath),parentValidationArtifactV1Schema).metadata}catch{throw new UsageError("Parent Validation not found or invalid")}const reviewer=validation.run_id===owned.root.run.run_id?null:await composition.runs.read(validation.run_id).catch(()=>null);const byId2=new Map((await composition.runs.list()).map(entry2=>[entry2.run.run_id,entry2]));const validReviewer=reviewer!==null&&reviewer.status==="completed"&&reviewer.run.agent==="agent-reviewer"&&reviewer.run.task_id===null&&reviewer.run.change_id===null&&reviewer.run.spec_id===owned.spec.id&&reviewer.run.execution_id===owned.execution.id&&effectiveRunV2Role(reviewer.run)==="subagent"&&effectiveRunV2Purpose(reviewer.run)==="review"&&validation.author_id===reviewer.run.agent&&descendant(validation.run_id,owned.root.run.run_id,byId2);if(validation.id!==validationId||validation.status!=="passed"||validation.spec_id!==owned.spec.id||validation.execution_id!==owned.execution.id||validation.run_id!==owned.root.run.run_id&&!validReviewer)throw new UsageError("Evidence requires passed Validation of the same SPEC/Execution");const acceptance=parsed.options.acceptance===void 0?validation.acceptance_ids:ids(parsed.options.acceptance,"--acceptance");if(acceptance.some(item=>!validation.acceptance_ids.includes(item)||!owned.spec.acceptance_ids.includes(item)))throw new UsageError("Evidence ACs must be a subset of its passed Validation and SPEC");const artifact=parentEvidenceArtifactV1Schema.parse({schema_version:3,scope:"spec_execution",id,spec_id:owned.spec.id,execution_id:owned.execution.id,run_id:owned.root.run.run_id,acceptance_ids:acceptance,outcome_ids:[],validation_artifact_ids:[validationId],observed_at:new Date().toISOString(),status:"passed",summary:parsed.options.summary,locators:[validationPath],commit_sha:validation.commit_sha,not_applicable_reason:null});const path=`${owned.directory}/artifacts/parent/evidence/${id}.md`;await filesystem.writeTextAtomicExclusive(path,serializeMarkdown({metadata:artifact,body:`# Evidence ${id}
3584
3584
  `}));return{evidence:artifact,artifact_path:path}}var execFileAsync8,reviewKinds,prefixes;var init_parent_assurance_commands=__esm({"src/parent-assurance-commands.ts"(){"use strict";init_src();init_src5();init_assurance();init_candidate_validation();init_cli_arguments();execFileAsync8=promisify12(execFile12);reviewKinds=new Set(["review","spec_review","quality_review"]);prefixes={test:"TEST-",eval:"EVAL-",check:"CHECK-",review:"REVIEW-",spec_review:"REVIEW-SPEC-",quality_review:"REVIEW-QUALITY-",mutation:"MUT-",integration:"INT-",cross_spec_e2e:"E2E-"}}});import{posix as posix9}from"node:path";async function readParentAssuranceBundle(filesystem,layout,specId,executionId){const directory2=posix9.dirname(layout.activePath("execution",executionId));const validations=[];const evidences=[];for(const path of await filesystem.listFiles(`${directory2}/artifacts/parent/tests`)){const artifact=parseMarkdown(await filesystem.readText(path),parentValidationArtifactV1Schema).metadata;if(path!==`${directory2}/artifacts/parent/tests/${artifact.id}.md`||artifact.spec_id!==specId||artifact.execution_id!==executionId)throw new UsageError("Parental Validation ownership/path mismatch");validations.push(artifact)}for(const path of await filesystem.listFiles(`${directory2}/artifacts/parent/evidence`)){const artifact=parseMarkdown(await filesystem.readText(path),parentEvidenceArtifactV1Schema).metadata;if(path!==`${directory2}/artifacts/parent/evidence/${artifact.id}.md`||artifact.spec_id!==specId||artifact.execution_id!==executionId)throw new UsageError("Parental Evidence ownership/path mismatch");evidences.push(artifact)}if(new Set(validations.map(item=>item.id)).size!==validations.length||new Set(evidences.map(item=>item.id)).size!==evidences.length)throw new UsageError("Duplicate parental artifact id");return{validations,evidences}}async function assertParentalSpecAssurance(input){if(input.candidate_commit===null)throw new UsageError("SPEC parental assurance requires a final candidate commit");const bundle=await readParentAssuranceBundle(input.filesystem,input.layout,input.spec_id,input.execution_id);if(bundle.validations.length===0||bundle.evidences.length===0)throw new UsageError("SPEC parental assurance requires explicit SPEC/Execution artifacts");const validations=bundle.validations.filter(item=>item.status==="passed"&&item.commit_sha===input.candidate_commit);const evidences=bundle.evidences.filter(item=>item.status==="passed"&&item.commit_sha===input.candidate_commit);if(validations.length<3||evidences.length<3||["integration","spec_review","quality_review"].some(kind=>!validations.some(item=>item.kind===kind)))throw new UsageError("SPEC parental adoption requires three parent validations, three Evidence and its review/integration modalities");const byId2=await readAssuranceRunAncestry(input.repositories.runs,validations.map(item=>item.run_id));const implementerIds=new Set(validations.filter(item=>!reviewKinds.has(item.kind)).map(item=>item.run_id));if(implementerIds.size!==1)throw new UsageError("SPEC parental assurance requires one macro implementer Run");const rootId=implementerIds.values().next().value;if(!rootId)throw new UsageError("SPEC parental implementer Run missing");const root=byId2.get(rootId);if(!root||root.run.parent_run_id!==null||root.run.task_id!==null||root.run.change_id!==null||root.run.spec_id!==input.spec_id||root.run.execution_id!==input.execution_id||root.run.execution_kind!=="delivery"||root.run.entrypoint!=="spec"||root.run.agent!=="agent-orchestrator")throw new UsageError("SPEC parental implementer Run is not the macro root");const reviews=validations.filter(item=>reviewKinds.has(item.kind));if(!reviews.some(specReview=>specReview.kind==="spec_review"&&reviews.some(qualityReview=>qualityReview.kind==="quality_review"&&qualityReview.run_id!==specReview.run_id)))throw new UsageError("SPEC and quality reviews require distinct reviewer Runs");for(const item of validations){if(item.acceptance_ids.some(id=>!input.acceptance_ids.includes(id)))throw new UsageError("Parental Validation contains an AC outside the SPEC");if(!reviewKinds.has(item.kind)){if(item.run_id!==rootId)throw new UsageError("Parental implementation Validation requires the macro root");if(!item.candidate_execution||item.candidate_execution.commit_sha!==input.candidate_commit||item.candidate_execution.exit_code!==0)throw new UsageError("Parental implementation Validation requires isolated candidate execution");continue}const reviewer=byId2.get(item.run_id);if(reviewer?.status!=="completed"||reviewer.run.spec_id!==input.spec_id||reviewer.run.execution_id!==input.execution_id||reviewer.run.task_id!==null||reviewer.run.change_id!==null||effectiveRunV2Role(reviewer.run)!=="subagent"||effectiveRunV2Purpose(reviewer.run)!=="review"||reviewer.run.agent!=="agent-reviewer"||!descendant(item.run_id,rootId,byId2)||item.author_id===root.run.agent||item.author_id!==reviewer.run.agent)throw new UsageError("Parental independent reviewer identity or ancestry invalid")}for(const item of evidences){if(item.run_id!==rootId||item.acceptance_ids.some(id=>!input.acceptance_ids.includes(id)))throw new UsageError("Parental Evidence ownership or AC mismatch");const linked=item.validation_artifact_ids.map(id=>validations.find(validation=>validation.id===id));if(linked.length===0||linked.some(validation=>!validation||item.acceptance_ids.some(id=>!validation.acceptance_ids.includes(id))))throw new UsageError("Parental Evidence requires a passed same-candidate Validation covering its ACs")}const firstReview=reviews[0];const assessment=assessDeliveryAssurance({contract:resolveDeliveryAssuranceContract("spec"),acceptance_ids:input.acceptance_ids,outcome_ids:[],validations:[...input.task_validations,...validations],evidences:[...input.task_evidences,...evidences],verifier:firstReview===void 0?null:{author_id:root.run.agent,reviewer_id:firstReview.author_id,status:"approved"},mutation:null,rollback_evidence_id:null,expected_commit_sha:input.candidate_commit});if(!assessment.valid)throw new UsageError(`SPEC parental assurance failed: ${assessment.findings.map(item=>`${item.code}: ${item.message}`).join("; ")}`)}var init_parent_assurance_v1=__esm({"src/parent-assurance-v1.ts"(){"use strict";init_src();init_src5();init_assurance();init_assurance_run_ancestry();init_cli_arguments();init_parent_assurance_commands();init_parent_assurance_commands()}});async function parentalRelayProof(composition,actor,intentId,live,excludeRunId){if(!actor.run.task_id||!actor.run.change_id||!actor.run.parent_run_id)throw new UsageError("Parental relay needs the exact delegated actor");const issued=await readIssuedIntent(composition,actor,intentId);if(!issued)throw new UsageError("Parental relay intent is unavailable");await assertIssuedRelayAuthorization(composition,issued);if(live)await assertLiveRelayAuthority(composition,issued);const{task}=await composition.tasks.read(issued.target_task_id);const{change}=await composition.changes.read(issued.target_change_id);const{execution}=await composition.executions.read(issued.target_execution_id);const{spec}=await composition.specs.read(issued.target_spec_id);const historicalRunId=task.result?.completed_run_id;const historicalRun=historicalRunId?await composition.runs.read(historicalRunId):null;const bound=historicalRun?await authenticatedBoundRelay(historicalRun,composition):null;if(actor.run.run_id!==issued.actor_run_id||actor.run.parent_run_id!==issued.macro_run_id||actor.run.task_id!==issued.actor_task_id||actor.run.change_id!==issued.actor_change_id||actor.run.execution_id!==issued.actor_execution_id||task.status!=="completed"||change.status!=="completed"||task.change_id!==change.id||historicalRun?.status!=="completed"||bound?.intent.current_state_sha256!==issued.current_state_sha256||execution.origin.type!=="spec"||execution.origin.spec_id!==spec.id||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===change.id)||live&&((excludeRunId?!["running","verifying"].includes(execution.status):execution.status!=="running")||spec.status!=="active"))throw new UsageError("Parental relay has no completed bound historical Task");const tasks=await Promise.all(execution.dag.nodes.map(async node=>(await composition.tasks.read(node.task_id)).task));if(tasks.some(item=>item.status!=="completed"))throw new UsageError("Parental relay has unfinished historical Tasks");if(live&&(await composition.runs.list()).some(run=>run.status==="running"&&run.run.execution_id===execution.id&&run.run.task_id===null&&run.run.run_purpose==="orchestration"&&run.run.agent==="agent-orchestrator"&&run.run.run_id!==actor.run.run_id&&run.run.run_id!==excludeRunId))throw new UsageError("Parental relay has another active historical owner");const assurance=composition.layout.projectConfig?.assurance;if(assurance?.version!==1)throw new UsageError("Parental relay requires assurance v1");const{expected,validations,evidences}=await deliveryCandidateProofs(composition.filesystem,composition.layout,tasks,assurance,composition);if(!expected||expected!==issued.candidate_sha)throw new UsageError("Parental relay candidate differs from published Evidence");await assertParentalSpecAssurance({filesystem:composition.filesystem,layout:composition.layout,repositories:composition,spec_id:spec.id,execution_id:execution.id,acceptance_ids:spec.acceptance_ids,candidate_commit:expected,task_validations:validations,task_evidences:evidences});const parentBundle=await readParentAssuranceBundle(composition.filesystem,composition.layout,spec.id,execution.id);const passedParentEvidence=parentBundle.evidences.filter(item=>item.status==="passed"&&item.commit_sha===expected).sort((left,right)=>left.id.localeCompare(right.id));const modalities=["integration","spec_review","quality_review"];const parentEvidenceIds=modalities.map(kind=>{const proof=parentEvidenceIdsForKind(parentBundle,passedParentEvidence,kind,expected);if(!proof)throw new UsageError(`Parental relay lacks ${kind} Evidence`);return proof}).sort();if(new Set(parentEvidenceIds).size!==3)throw new UsageError("Parental relay requires three distinct original Evidence");const integrationEvidence=passedParentEvidence.find(item=>item.id===parentEvidenceIdsForKind(parentBundle,passedParentEvidence,"integration",expected));const originalMacroId=parentBundle.validations.find(item=>item.kind==="integration"&&item.status==="passed"&&item.commit_sha===expected&&integrationEvidence?.validation_artifact_ids.includes(item.id))?.run_id;const originalMacro=originalMacroId?await composition.runs.read(originalMacroId):null;if(originalMacro?.status!=="completed"||originalMacro.finalization_decision?.outcome!=="blocked")throw new UsageError("Parental relay requires the immutable prior Gui outcome");return{intent:issued,intentId,task,change,execution,spec,parentEvidenceIds}}function parentEvidenceIdsForKind(bundle,evidences,kind,candidate){const validationIds=new Set(bundle.validations.filter(item=>item.kind===kind&&item.status==="passed"&&item.commit_sha===candidate).map(item=>item.id));const matching=evidences.filter(item=>item.validation_artifact_ids.some(id=>validationIds.has(id)));return matching.length===1?matching[0]?.id??null:null}async function readIssuedIntent(composition,actor,id){const record3=await composition.decisions.read("change",required2(actor.run.change_id,"actor Change"),id).catch(()=>null);if(record3?.origin!=="agent"||record3.category!=="contract")return null;let targetTaskId;try{targetTaskId=JSON.parse(record3.decision).target_task_id}catch{return null}return readRelayIntent(composition,actor,targetTaskId,id)}async function bindParentalRelay(composition,actor,run,intentId,nativeSessionId){const proof=await parentalRelayProof(composition,actor,intentId,true,run.run.run_id);if(run.run.parent_run_id!==actor.run.run_id||run.run.entrypoint!=="spec"||run.run.task_id!==null||run.run.change_id!==null||run.run.execution_id!==proof.execution.id||run.run.spec_id!==proof.spec.id||run.run.agent!=="agent-orchestrator"||run.run.run_role!=="subagent"||run.run.run_purpose!=="orchestration"||!run.run.client_thread_id||!run.run.client_turn_id)throw new UsageError("Parental Run differs from its native capture");const payload={schema_version:1,kind:"post_publication_parental_binding",intent_id:intentId,actor_run_id:actor.run.run_id,target_run_id:run.run.run_id,target_task_id:proof.task.id,target_execution_id:proof.execution.id,target_spec_id:proof.spec.id,client_thread_id:run.run.client_thread_id,client_turn_id:run.run.client_turn_id,native_session_id:nativeSessionId,candidate_sha:proof.intent.candidate_sha,evidence_ids:proof.parentEvidenceIds};await recordRelayDecision(composition,bindingId(run.run.run_id),proof.intent.actor_change_id,payload)}async function authenticatedParentalRelay(run,composition,live=false,nativeSessionId){if(!isParentalRelayShape(run))return null;const actor=await composition.runs.read(required2(run.run.parent_run_id,"parent Run"));const record3=await composition.decisions.read("change",required2(actor.run.change_id,"actor Change"),bindingId(run.run.run_id)).catch(()=>null);if(record3?.origin!=="agent"||record3.category!=="contract")throw new UsageError("Parental Run lacks its issued binding");let binding;try{binding=JSON.parse(record3.decision)}catch{throw new UsageError("Parental binding is malformed")}const proof=await parentalRelayProof(composition,actor,binding.intent_id,live,run.run.run_id);if(binding.schema_version!==1||binding.kind!=="post_publication_parental_binding"||binding.actor_run_id!==actor.run.run_id||binding.target_run_id!==run.run.run_id||binding.target_task_id!==proof.task.id||binding.target_execution_id!==run.run.execution_id||binding.target_spec_id!==run.run.spec_id||binding.client_thread_id!==run.run.client_thread_id||binding.client_turn_id!==run.run.client_turn_id||nativeSessionId!==void 0&&binding.native_session_id!==nativeSessionId||binding.candidate_sha!==proof.intent.candidate_sha||JSON.stringify(binding.evidence_ids)!==JSON.stringify(proof.parentEvidenceIds))throw new UsageError("Parental binding differs from issued native identity");return proof}function isParentalRelayShape(run){const value=run.run;return value.run_role==="subagent"&&value.run_purpose==="orchestration"&&value.agent==="agent-orchestrator"&&value.client==="codex-subagent"&&value.entrypoint==="spec"&&value.task_id===null&&value.change_id===null&&value.execution_id!==null&&value.spec_id!==null&&value.parent_run_id!==null&&value.requires_finalizer===true}var bindingId;var init_post_publication_parental=__esm({"src/post-publication-parental.ts"(){"use strict";init_cli_arguments();init_lifecycle_v2_delivery_assurance();init_parent_assurance_v1();init_post_publication_relay();init_post_publication_relay_contract();bindingId=runId=>`DEC-AI-POSTPUB-PARENT-${sha2(runId).slice(0,24).toUpperCase()}`}});function isNativeTaskAttempt(fold){const run=fold.run;return effectiveRunV2Role(run)==="subagent"&&(effectiveRunV2Purpose(run)==="orchestration"&&run.agent==="agent-orchestrator"||effectiveRunV2Purpose(run)==="execution"&&run.execution_eligibility?.includes("delivery")===true)&&run.client==="codex-subagent"&&run.requires_finalizer===true&&run.execution_kind==="delivery"&&run.entrypoint==="task"&&run.task_id!==null&&run.change_id!==null&&run.execution_id!==null&&run.parent_run_id!==null&&run.client_thread_id!==null&&run.client_turn_id!==null}function ownsLifecycleAttempt(fold){return effectiveRunV2Role(fold.run)==="orchestrator"||isNativeTaskAttempt(fold)||isParentalRelayShape(fold)}var init_task_attempt=__esm({"src/host-native-delegation/task-attempt.ts"(){"use strict";init_src5();init_post_publication_parental()}});function finalizationBarrierBlockReason(barrier){if(barrier.required&&barrier.status==="executor_missing")return"Finalization barrier executor_missing; completion requires a capable executor or an explicitly authorized direct Task root";if(barrier.required&&barrier.status==="evidence_missing"){return"Finalization barrier evidence_missing; resume after passed typed Evidence linked to the same Task, Change, Execution, and Run"}return barrier.required&&!barrier.satisfied?`Finalization barrier ${barrier.status}; resume after a completed zaip-agent-finalizer Sub-Run with authoritative metadata`:null}function assessRunFinalizationBarrier(parent,candidates,evidenceSatisfied=false){const required3=runV2RequiresFinalizer(parent.run)||descendantRuns(parent.run.run_id,candidates).length>0;const evidenceRequired=parent.run.execution_kind==="delivery";if(!required3){return{required:false,evidence_required:false,evidence_satisfied:true,status:"not_required",finalizer_run_id:null,satisfied:true}}const finalizer=directFinalizers(parent.run.run_id,candidates).at(-1);if(finalizer===void 0){return{required:true,evidence_required:evidenceRequired,evidence_satisfied:!evidenceRequired||evidenceSatisfied,status:"missing",finalizer_run_id:null,satisfied:false}}const evidenceAccepted=!evidenceRequired||evidenceSatisfied;const status=finalizer.status==="completed"?!evidenceAccepted?"evidence_missing":!hasExecutionAuthorityForCompletion(parent,candidates)?"executor_missing":finalizer.status:finalizer.status;return{required:true,evidence_required:evidenceRequired,evidence_satisfied:evidenceAccepted,status,finalizer_run_id:finalizer.run.run_id,satisfied:status==="completed"&&evidenceAccepted}}function assertChildRunMayStart(parent,purpose,agent,candidates,executionEligibility=[],options={}){if(parent.finished!==null&&options.allowObservedHistoricalInvocation!==true)throw new Error(`Parent Run is already finished: ${parent.run.run_id}`);const crossedBarrier=ancestorLineage(parent,candidates).find(ancestor=>directFinalizers(ancestor.run.run_id,candidates).length>0);if(crossedBarrier!==void 0&&options.allowObservedHistoricalInvocation!==true){throw new Error(`Run ${crossedBarrier.run.run_id} crossed its finalization barrier; no new Sub-Run may start`)}if(parent.run.agent!=="agent-orchestrator")throw new Error(`Only the Task orchestrator may delegate; worker ${parent.run.agent} cannot create children`);const executionKind=parent.run.execution_kind;if(purpose==="execution"&&options.allowObservedIneligibleInvocation!==true&&(executionKind===void 0||!executionEligibility.includes(executionKind))){throw new Error(`Agent ${agent} lacks an execution capability for Run ${parent.run.run_id}`)}if(purpose==="finalization"&&agent!=="agent-finalizer"){throw new Error(`Finalizer for Run ${parent.run.run_id} requires agent-finalizer`)}if(purpose!=="finalization")return;const active=activeDescendantRuns(parent.run.run_id,candidates);if(active.length>0){throw new Error(`Finalizer for Run ${parent.run.run_id} must be the last Sub-Run; active descendants: ${active.map(run=>run.run.run_id).join(", ")}`)}}function hasExecutionAuthorityForCompletion(parent,candidates){if(effectiveRunV2Role(parent.run)!=="orchestrator"&&!isNativeTaskAttempt(parent))return true;return directExecutors(parent.run.run_id,parent.run.execution_kind,candidates).length>0||isAuthorizedDirectExecutor(parent)||parent.run.task_id===null&&descendantRuns(parent.run.run_id,candidates).some(candidate=>candidate.run.run_purpose==="execution"&&candidate.run.execution_eligibility?.includes("delivery")===true)}function isAuthorizedDirectExecutor(parent){const run=parent.run;return Boolean(run.direct_execution_authorization?.trim())&&run.execution_kind==="delivery"&&run.agent==="agent-orchestrator"&&run.run_role==="orchestrator"&&run.parent_run_id===null&&typeof run.task_id==="string"&&typeof run.change_id==="string"&&typeof run.execution_id==="string"&&Boolean(run.client_thread_id)&&Boolean(run.client_turn_id)&&!run.client_turn_id?.startsWith("local-")&&!["unknown","unavailable","manual"].includes(run.model)}function directExecutors(parentRunId,executionKind,candidates){return candidates.filter(candidate=>candidate.run.parent_run_id===parentRunId&&effectiveRunV2Purpose(candidate.run)==="execution"&&(executionKind!==void 0&&candidate.run.execution_eligibility?.includes(executionKind)===true||executionKind===void 0&&candidate.run.execution_eligibility===void 0&&candidate.run.agent==="agent-task-executor")&&candidate.run.agent!=="agent-finalizer")}function ancestorLineage(parent,candidates){const byId2=new Map(candidates.map(candidate=>[candidate.run.run_id,candidate]));const lineage=[];const visited=new Set;let current=parent;while(current!==void 0&&!visited.has(current.run.run_id)){lineage.push(current);visited.add(current.run.run_id);current=current.run.parent_run_id===null?void 0:byId2.get(current.run.parent_run_id)}return lineage}function directFinalizers(parentRunId,candidates){return candidates.filter(candidate=>candidate.run.parent_run_id===parentRunId&&effectiveRunV2Purpose(candidate.run)==="finalization"&&(candidate.run.agent==="agent-finalizer"||candidate.run.agent==="agent-task-finalizer")).sort((left,right)=>left.run.occurred_at.localeCompare(right.run.occurred_at))}var init_run_finalization_barrier=__esm({"src/run-finalization-barrier.ts"(){"use strict";init_src5();init_task_attempt();init_run_hierarchy()}});import{createHash as createHash43}from"node:crypto";async function amendTaskScopes(parsed,filesystem,composition){requireOptions(parsed.options,["run","add-scopes","reason","expected-revision"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task amend-scopes requires a Task id");const{task}=await composition.tasks.read(id);const run=await composition.runs.read(parsed.options.run);if(run.status!=="running"||run.finalization_decision!=null||run.run.task_id!==id||run.run.change_id!==task.change_id||run.run.execution_kind!=="delivery"||run.run.agent!=="agent-orchestrator"||!["blocked","executing"].includes(task.status))throw new UsageError("Scope amendment requires this Task's active delivery orchestrator");const runs=await composition.runs.list();assertChildRunMayStart(run,"execution","agent-task-executor",runs,["delivery"]);const additions=[...new Set(csvOption(parsed.options["add-scopes"]))].sort();if(!additions.length||additions.some(scope=>scope.includes("\\")||scope.startsWith("/")||scope.includes(":")||scope.split("/").some(part=>part===".."||part==="."||part==="")||scope==="**"||scope==="*"))throw new UsageError("Scope amendments require explicit workspace-relative paths");const reason=parsed.options.reason?.trim();if(!reason)throw new UsageError("Scope amendment requires the authorized rework reason");const key=createHash43("sha256").update(JSON.stringify({task:id,run:run.run.run_id,additions,reason})).digest("hex").slice(0,24);const path=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework/scopes-${key}.json`;const exists3=await filesystem.exists(path);const receipt=exists3?JSON.parse(await filesystem.readText(path)):null;if(receipt?.next_scopes.every(scope=>task.write_scopes.includes(scope)))return{task,amendment_path:path,reused:true};if(activeDescendantRuns(run.run.run_id,runs).length>0)throw new UsageError("Finish active descendants before changing the Task's write scopes");if(task.revision!==Number(parsed.options["expected-revision"])||receipt&&receipt.previous_revision!==task.revision)throw new UsageError("Task revision changed; inspect the current Task before amending scopes");const nextScopes=[...new Set([...task.write_scopes,...additions])];const next=taskV2Schema.parse({...task,revision:task.revision+1,write_scopes:nextScopes,updated_at:new Date().toISOString()});if(!exists3)await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:run.run.run_id,execution_id:run.run.execution_id,plan_hash:task.plan_hash,previous_revision:task.revision,previous_scopes:task.write_scopes,next_scopes:nextScopes,reason,occurred_at:next.updated_at},null,2)}
3585
3585
  `);await composition.tasks.write(next);return{task:next,amendment_path:path,reused:false}}async function assertRecordedTaskScopeDelta(task,baseline,composition){if(JSON.stringify(task.write_scopes)===JSON.stringify(baseline))return;const directory2=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework`;const paths2=await composition.filesystem.listFiles(directory2,".json");if(paths2.length>128)throw new UsageError("Scope rework history requires explicit compaction review");const receipts=await Promise.all(paths2.filter(path=>/\/scopes-[a-f0-9]+\.json$/.test(path)).map(async path=>JSON.parse(await composition.filesystem.readText(path))));let scopes=[...baseline];for(const receipt of receipts.sort((a,b)=>a.previous_revision-b.previous_revision)){if(receipt.schema_version!==1||receipt.task_id!==task.id||receipt.plan_hash!==task.plan_hash||!Number.isInteger(receipt.previous_revision)||receipt.previous_revision>=task.revision||JSON.stringify(receipt.previous_scopes)!==JSON.stringify(scopes)||!Array.isArray(receipt.next_scopes)||!scopes.every(scope=>receipt.next_scopes.includes(scope)))continue;const run=await composition.runs.read(receipt.run_id);if(run.run.task_id!==task.id||run.run.change_id!==task.change_id||run.run.execution_id!==receipt.execution_id||run.run.agent!=="agent-orchestrator")throw new UsageError("Scope rework receipt has incompatible ownership");scopes=receipt.next_scopes}if(JSON.stringify(task.write_scopes)!==JSON.stringify(scopes))throw new UsageError(`Native Task ${task.id} drifted from its PreparedPlan without a recorded scope rework`)}var init_task_scope_amendment=__esm({"src/task-scope-amendment.ts"(){"use strict";init_src7();init_cli_arguments();init_run_finalization_barrier();init_run_hierarchy()}});import{createHash as createHash44}from"node:crypto";async function runAutonomousExecutionCommand(executionId,parsed,composition,driver,agentCatalog){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const{execution}=await composition.executions.read(executionId);const configured=resolveExecutionRuntime(config2,void 0,execution.origin.type);if(configured.runtime!=="autonomous"||parsed.flags.has("materialize-only"))return materializedExecution(configured.runtime,execution,composition.executions.path?.(executionId));if(driver===void 0){throw new UsageError("Autonomous provider protocol is not qualified; keep execution.runtime manual until clean-room qualification")}const capabilities=await driver.capabilities();const hostAuthenticationAvailable=configured.provider==="codex"?await driver.hostAuthenticationAttestation?.():false;if(configured.provider==="codex"&&hostAuthenticationAvailable!==true){throw new UsageError("Codex host authentication attestation is unavailable")}if(capabilities.provider!==configured.provider){throw new UsageError(`Configured provider ${configured.provider} does not match runtime ${capabilities.provider}`)}if(!capabilities.models.includes(configured.model)){throw new UsageError(`Configured model is not supported by runtime: ${configured.model}`)}let input=await buildAutonomousExecutionInput(composition,execution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{failurePolicy:parsed.flags.has("continue-independent")?"continue_independent":void 0,restartFailedState:parsed.flags.has("restart-failed-state"),recheckBlockedState:parsed.flags.has("recheck-blocked-state"),operationalContext:{host_authentication_available:hostAuthenticationAvailable===true,requires_remote_operation:parsed.flags.has("requires-remote-operation")}});const childExecutions=await materializePrdChildExecutions(composition,execution,input);if(childExecutions.length>0){const childBySpec=new Map(childExecutions.map(child=>[child.spec_id,child.id]));input={...input,tasks:input.tasks.map(task=>({...task,...task.commit?.spec_id===null||task.commit?.spec_id===void 0?{}:{child_execution_id:childBySpec.get(task.commit.spec_id)}}))};const budgetAllocation=allocateInvocationBudget(input,childExecutions);const candidates=await mapWithConcurrency(childExecutions,input.policy.max_parallelism,async child=>{const childExecution=(await composition.executions.read(child.id)).execution;const childInput=await buildAutonomousExecutionInput(composition,childExecution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{recheckBlockedState:parsed.flags.has("recheck-blocked-state")});const policy=input.spec_execution_policies[child.spec_id];if(policy?.cancelled===true){await composition.executions.transition(child.id,"cancelled","SPEC execution cancelled by its persisted policy");return{child_execution_id:child.id,spec_id:child.spec_id,status:"cancelled",handoff_worktree_path:null,handoff_commit:null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy.finalizer_scope,invocation_count:0}}const result3=await driver.execute({...childInput,spec_execution_policies:policy===void 0?{}:{[child.spec_id]:policy},policy:{...childInput.policy,max_parallelism:1,max_total_invocations:budgetAllocation.get(child.id)??null}});const status=result3.status==="completed"?"completed":result3.status==="failed"?"failed":"blocked";await composition.executions.transition(child.id,status,`Autonomous child ${status}`);return{child_execution_id:child.id,spec_id:child.spec_id,status,handoff_worktree_path:result3.state?.handoff_worktree_path??null,handoff_commit:result3.state?.handoff_commit??null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy?.finalizer_scope??"spec",invocation_count:result3.state?.invocation_count??0}});const consumedByChildren=candidates.reduce((total,candidate)=>total+candidate.invocation_count,0);input={...input,child_candidates:candidates.map(({invocation_count:_count,...candidate})=>candidate),policy:{...input.policy,max_total_invocations:input.policy.max_total_invocations===null?null:Math.max(1,input.policy.max_total_invocations-consumedByChildren)}}}const result2=await driver.execute(input);return{...result2,dependency_plan:dependencyPlan(input),child_executions:childExecutions}}async function materializePrdChildExecutions(composition,parent,input){if(parent.origin.type!=="prd")return[];const taskById=new Map(input.tasks.map(task=>[task.id,task]));const grouped=new Map;for(const task of input.tasks){const specId=task.commit?.spec_id??null;if(specId===null)continue;grouped.set(specId,[...grouped.get(specId)??[],task])}const children=[];for(const[specId,tasks]of[...grouped].sort(([left],[right])=>left.localeCompare(right))){const ids2=new Set(tasks.map(task=>task.id));if(tasks.some(task=>task.depends_on.some(dependency=>!ids2.has(dependency)||!taskById.has(dependency))))continue;const outsideTasks=input.tasks.filter(task=>!ids2.has(task.id));if(tasks.some(task=>outsideTasks.some(outside2=>writeScopesOverlap(task.write_scopes,outside2.write_scopes)))){continue}const id=childExecutionId(parent.id,specId);const existing=await composition.executions.read(id).catch(()=>null);if(existing===null){const dag={nodes:parent.dag.nodes.filter(node=>ids2.has(node.task_id)),topological_order:parent.dag.topological_order.filter(taskId=>ids2.has(taskId))};await composition.executions.write({...parent,id,parent_execution_id:parent.id,client_turn_id:parent.client_turn_id??id,revision:1,origin:{type:"spec",spec_id:specId},status:"planned",status_reason:null,started_at:null,finished_at:null,result:null,dag,spec_execution_policies:input.spec_execution_policies[specId]===void 0?{}:{[specId]:input.spec_execution_policies[specId]}});await composition.executions.transition(id,"running")}await composition.executions.linkChildExecution(id,parent.id);children.push({id,spec_id:specId})}return children}function childExecutionId(parentExecutionId,specId){return`EXEC-CHILD-${createHash44("sha256").update(`${parentExecutionId}:${specId}`).digest("hex").slice(0,16).toUpperCase()}`}function writeScopesOverlap(left,right){return left.some(leftScope=>right.some(rightScope=>pathsOverlap(scopePrefix(leftScope),scopePrefix(rightScope))))}function scopePrefix(scope){const wildcard=scope.search(/[?*]/);return(wildcard<0?scope:scope.slice(0,wildcard)).replace(/\/+$/,"")}function pathsOverlap(left,right){return left.length===0||right.length===0||left===right||left.startsWith(`${right}/`)||right.startsWith(`${left}/`)}async function mapWithConcurrency(items,limit,worker){const results=new Array(items.length);let cursor=0;const runners=Array.from({length:Math.min(limit,items.length)},async()=>{while(cursor<items.length){const index=cursor++;const item=items[index];if(item!==void 0)results[index]=await worker(item)}});await Promise.all(runners);return results}async function buildAutonomousExecutionInput(composition,execution,limits,agentCatalog,overrides={}){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const taskRecords=await Promise.all(execution.dag.topological_order.map(async taskId=>{const{task}=await composition.tasks.read(taskId);return task}));const preparedPlan=await composition.materializer.readPreparedPlan(execution.parent_execution_id??execution.id);const canonicalTasks=new Map(preparedPlan.blueprints.tasks.map(task=>[task.id,task]));const changes=await Promise.all([...new Set(execution.dag.nodes.map(node=>node.change_id))].map(async changeId=>(await composition.changes.read(changeId)).change));const referencedSpecIds=changes.flatMap(change=>change.source.type==="spec"?[change.source.spec_id]:change.source.type==="prd"&&change.source.spec_id!==null?[change.source.spec_id]:[]);const changeById=new Map(changes.map(change=>[change.id,change]));const manualOrder=await readManualWorkOrder(composition.filesystem);const runtime=resolveExecutionRuntime(config2,{plan:Math.min(execution.policy.max_parallelism,independentBranchLimit(taskRecords)),provider:limits.providerParallelism,squad:agentCatalog===void 0?1:Math.max(1,...agentCatalog.squads.map(squad=>squad.max_parallelism))},execution.origin.type);if(runtime.runtime!=="autonomous")throw new UsageError("Autonomous runtime is not enabled");const tasks=await Promise.all(taskRecords.map(async task=>{const ledger=composition.filesystem?await new FileRecoveryLedger(composition.filesystem).read(task.id):null;if(ledger&&!config2.autonomy&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} has a frozen autonomy ledger; restore project autonomy configuration before managed dispatch`);if(config2.autonomy&&(task.attempt_count??(task.started_at?1:0))>0&&!ledger&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} requires explicit task migrate-autonomy before managed dispatch; historical attempts cannot reset`);const baseline=canonicalTasks.get(task.id);if(baseline===void 0)throw new UsageError(`PreparedPlan is missing Task ${task.id}`);const change=changeById.get(task.change_id);if(change===void 0)throw new Error(`Task ${task.id} references an unreadable Change`);const source=change.source;return{id:task.id,...ledger?{autonomy:ledger}:{},change_id:task.change_id,title:task.title,objective:task.objective,risk:task.risk,priority:priorityNumber(task.priority),manual_order:manualOrderForTask(task.id,change.source,manualOrder),depends_on:[...task.depends_on],acceptance_ids:[...task.acceptance_ids],write_scopes:[...task.write_scopes],scope_receipt:await canonicalScopeReceipt(task,baseline.write_scopes,composition),assurance_contract:effectiveTaskAssurance(task,config2.assurance?.version===1?config2.assurance:{standard_depth:"auto",require_final_commit:false}).contract,...agentCatalog===void 0?{}:{builder:autonomousBuilderForTask(runtime.model,agentCatalog,task.write_scopes),...requiresAutonomousAudit(task)?{verifier:autonomousAuditorForTask(runtime.model,agentCatalog,task)}:{}},commit:{agent:runtime.provider.toUpperCase(),execution_id:execution.id,change_id:task.change_id,task_id:task.id,title:task.title,prd_id:source.type==="prd"?source.prd_id:null,spec_id:source.type==="spec"?source.spec_id:source.type==="prd"?source.spec_id:null},...task.runtime===void 0?{}:{runtime:task.runtime},...task.model_profile===void 0?{}:{model_profile:task.model_profile}}}));if(execution.origin.type==="interaction"){throw new Error(`Interaction Execution ${execution.id} cannot use the delivery runtime`)}return{mode:"autonomous",execution_id:execution.id,source:execution.origin.type,source_identity:{spec_id:execution.origin.type==="spec"?execution.origin.spec_id:null,prd_id:execution.origin.type==="prd"?execution.origin.prd_id:null},created_at:new Date(execution.created_at).toISOString(),...overrides.restartFailedState===true?{restart_failed_state:true}:{},...overrides.recheckBlockedState===true?{recheck_blocked_state:true}:{},host_capabilities:{models:[...limits.capabilities.models],reasoning_efforts:[...limits.capabilities.reasoning_efforts],velocities:[...limits.capabilities.velocities]},operational_context:{provider:runtime.provider,host_authentication_available:false,requires_external_provider:runtime.provider!=="codex",requires_remote_operation:false,...overrides.operationalContext},handoff_seed_paths:[...new Set([composition.layout.activePath("execution",execution.id),...execution.dag.nodes.flatMap(node=>[composition.layout.activePath("task",node.task_id),composition.layout.activePath("change",node.change_id)]),...execution.origin.type==="prd"?[composition.layout.activePath("prd",execution.origin.prd_id)]:execution.origin.type==="spec"?[composition.layout.activePath("spec",execution.origin.spec_id)]:[],...referencedSpecIds.map(specId=>composition.layout.activePath("spec",specId))])].sort(),policy:{...config2.autonomy?{autonomy:config2.autonomy}:{},failure_policy:overrides.failurePolicy??(config2.autonomy?"continue_independent":execution.policy.failure_policy),lease_ms:runtime.lease_ms,max_parallelism:runtime.effective_parallelism,max_operational_retries:execution.policy.max_operational_retries,max_repair_cycles_per_task:Math.min(3,execution.policy.max_repair_cycles_per_task),soft_cycles:execution.policy.soft_model_cycle_budget??24,...runtime.max_phase_attempts===void 0?{}:{max_phase_attempts:runtime.max_phase_attempts},max_execution_ms:null,max_invocation_ms:null,max_total_invocations:config2.autonomy?null:runtime.max_total_invocations===void 0?Math.max(1,tasks.length*30):runtime.max_total_invocations,max_stalled_cycles:3,...isAutomaticModelSource(execution,config2.model_orchestration)?{model_orchestration:config2.model_orchestration}:{},...execution.policy.runtime_defaults===void 0?{}:{execution_override:{model:execution.policy.runtime_defaults.model,reasoning_effort:execution.policy.runtime_defaults.reasoning_effort,velocity:execution.policy.runtime_defaults.velocity??"standard"}}},spec_execution_policies:execution.spec_execution_policies??{},agents:autonomousAgents(runtime.provider,runtime.model,agentCatalog),tasks}}async function readManualWorkOrder(filesystem){try{const parsed=JSON.parse(await filesystem.readText(".agents/dashboard/work-priority.json"));const ids2=typeof parsed==="object"&&parsed!==null&&Array.isArray(parsed.item_ids)?parsed.item_ids:[];return new Map(ids2.filter(id=>typeof id==="string").map((id,index)=>[id,index]))}catch{return new Map}}function manualOrderForTask(taskId,source,order2){return order2.get(taskId)??(source.spec_id?order2.get(source.spec_id):void 0)??(source.prd_id?order2.get(source.prd_id):void 0)??null}function independentBranchLimit(tasks){const selected=[];for(const task of tasks){if(task.depends_on.length>0||task.risk==="critical")continue;if(selected.some(candidate=>scopesOverlap2(candidate.write_scopes,task.write_scopes)))continue;selected.push(task)}return Math.max(1,selected.length)}function scopesOverlap2(left,right){return left.some(leftScope=>right.some(rightScope=>{const leftPrefix=leftScope.replace(/[?*].*$/,"").replace(/\/$/,"");const rightPrefix=rightScope.replace(/[?*].*$/,"").replace(/\/$/,"");return leftPrefix===""||rightPrefix===""||leftPrefix.startsWith(rightPrefix)||rightPrefix.startsWith(leftPrefix)}))}async function canonicalScopeReceipt(task,baseline,composition){await assertRecordedTaskScopeDelta(task,baseline,composition);const current=[...task.write_scopes];return{receipt_id:createHash44("sha256").update(JSON.stringify({task_id:task.id,plan_hash:task.plan_hash,revision:task.revision,scopes:current})).digest("hex"),current_scopes:current,delta_scopes:current.filter(scope=>!baseline.includes(scope))}}function dependencyPlan(input){return{failure_policy:input.policy.failure_policy,unconditioned:input.tasks.filter(task=>task.depends_on.length===0).map(task=>({task_id:task.id})),conditioned:input.tasks.filter(task=>task.depends_on.length>0).map(task=>({task_id:task.id,depends_on:[...task.depends_on]}))}}function isAutomaticModelSource(execution,config2){return config2?.mode==="auto"&&config2.automatic_sources.some(source=>source===execution.origin.type)}function autonomousAgents(provider,model,catalog){if(catalog===void 0){return{orchestrator:{id:`${provider}-orchestrator`,model},builder:{id:`${provider}-task-executor`,model,execution_eligibility:["delivery"]},verifier:{id:`${provider}-verifier`,model,tools:[]},finalizer:{id:`${provider}-execution-finalizer`,model}}}const orchestratorSelection=selectAgent(catalog,{role:"orchestrator",capability:"dag-orchestration"});const orchestrator=orchestratorSelection.agent;const builderSelection=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:[]});const builder=builderSelection.agent;const verifierSelection=selectAgent(catalog,{role:"reviewer",capability:"independent-review"});const verifier=verifierSelection.agent;const finalizerSelection=selectAgent(catalog,{role:"execution-finalizer",capability:"lifecycle-finalization"});const finalizer=finalizerSelection.agent;return{orchestrator:{id:orchestrator.id,model,capability:"dag-orchestration",selection_reasons:orchestratorSelection.reasons,soft_cycles:orchestrator.budget.soft_cycles,tools:orchestrator.tools,execution_eligibility:orchestrator.execution_eligibility},builder:{id:builder.id,model,capability:selectionCapability(builderSelection.reasons),selection_reasons:builderSelection.reasons,soft_cycles:builder.budget.soft_cycles,tools:builder.tools,execution_eligibility:builder.execution_eligibility},verifier:{id:verifier.id,model,capability:"independent-review",selection_reasons:verifierSelection.reasons,soft_cycles:verifier.budget.soft_cycles,tools:verifier.tools,execution_eligibility:verifier.execution_eligibility},finalizer:{id:finalizer.id,model,capability:"lifecycle-finalization",selection_reasons:finalizerSelection.reasons,soft_cycles:finalizer.budget.soft_cycles,tools:finalizer.tools,execution_eligibility:finalizer.execution_eligibility}}}function autonomousAuditorForTask(model,catalog,task){const capability=task.model_profile?.risk_signals.security_or_critical_data===true?"security-audit":"release-audit";const selection2=selectAgent(catalog,{role:"auditor",capability});const agent=selection2.agent;return{id:agent.id,model,capability,selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function requiresAutonomousAudit(task){const signals=task.model_profile?.risk_signals;return task.risk==="critical"||signals?.security_or_critical_data===true||signals?.broad_audit===true}function autonomousBuilderForTask(model,catalog,writeScopes){const selection2=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:writeScopes});const agent=selection2.agent;return{id:agent.id,model,capability:selectionCapability(selection2.reasons),selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function priorityNumber(priority2){return{low:1,medium:2,high:3,urgent:4}[priority2]}function selectionCapability(reasons){return reasons.find(reason=>reason.startsWith("capability:"))?.slice("capability:".length)??""}var init_autonomous_execution_command=__esm({"src/autonomous-execution-command.ts"(){"use strict";init_src();init_src7();init_autonomous_invocation_budget();init_cli_arguments();init_execution_runtime_config();init_lifecycle_assurance_v2();init_task_scope_amendment()}});function astraDiagnosticContext(filesystem,build=buildContextPack){return async task=>{const query2=["RULE-ASTRA-DIAGNOSTIC",...task.acceptance_ids].join(" ");const pack=await build(filesystem,query2,16e3,{role:"orchestrator",phase:"planning",failClosed:true});const items=pack.items.filter(item=>pack.requiredFiles.includes(item.path));if(!items.some(item=>item.path===".agents/rules/astra-diagnostic.md"&&/\bRULE-ASTRA-DIAGNOSTIC\b/.test(item.content))){throw new Error("Astra diagnostic context is missing the canonical diagnostic Rule")}const present=new Set(items.flatMap(item=>item.content.match(/\b(?:AC|REQ)-[A-Z0-9-]+/g)??[]));if(!task.acceptance_ids.every(id=>present.has(id))){throw new Error("Astra diagnostic context is missing a governing Acceptance Criterion")}return items.map(({path,content})=>({path,content:path.startsWith(".agents/requirements/")?governingRequirementSections(content,task.acceptance_ids):content}))}}function governingRequirementSections(content,acceptanceIds){const sections2=content.split(/(?=^## REQ-)/m);const governing=sections2.slice(1).filter(section=>acceptanceIds.some(id=>new Set(section.match(/\bAC-[A-Z0-9-]+\b/g)??[]).has(id)));return governing.length===0?content:[sections2[0],...governing].join("")}var init_autonomous_astra_context=__esm({"src/autonomous-astra-context.ts"(){"use strict";init_src3()}});function allocateSharedCreationValue(value,recipientIds){const recipients=[...new Set(recipientIds)].sort((left,right)=>left.localeCompare(right));const allocation=new Map;if(recipients.length===0)return allocation;if(value===null||!Number.isFinite(value)){for(const recipient of recipients)allocation.set(recipient,null);return allocation}if(Number.isInteger(value)){const share2=Math.floor(value/recipients.length);const remainder=value-share2*recipients.length;recipients.forEach((recipient,index)=>{allocation.set(recipient,share2+(index===recipients.length-1?remainder:0))});return allocation}const share=value/recipients.length;let allocated=0;recipients.forEach((recipient,index)=>{const assigned=index===recipients.length-1?value-allocated:share;allocation.set(recipient,assigned);allocated+=assigned});return allocation}var init_shared_creation_allocation=__esm({"../lifecycle-manifests/src/shared-creation-allocation.ts"(){"use strict"}});function periodTimestamp(entity){const data2=entity.data;if(entity.kind==="evidence")return typeof data2?.observed_at==="string"?data2.observed_at:null;if(entity.kind==="validation")return typeof data2?.executed_at==="string"?data2.executed_at:null;if(entity.kind==="run")return typeof data2?.source_started_at==="string"?data2.source_started_at:typeof data2?.started_at==="string"?data2.started_at:entity.updated_at;return typeof data2?.created_at==="string"?data2.created_at:entity.updated_at}function saoPauloPeriodKey(value,granularity){const date5=new Date(value);if(Number.isNaN(date5.getTime()))return null;const parts=saoPauloDateFormatter.formatToParts(date5);const part=type=>parts.find(item=>item.type===type)?.value;const year=part("year");const month=part("month");const day=part("day");if(year===void 0||month===void 0||day===void 0)return null;if(granularity==="year")return year;if(granularity==="month")return`${year}-${month}`;return`${year}-${month}-${day}`}function buildObservedDuration(runs,phase2="execution"){const values=runs.filter(run=>isRootPhaseRun(run,phase2)).map(run=>{const duration4=durationForRun(run);const started=run.data?.source_started_at??run.data?.started_at;if(typeof duration4!=="number"||duration4<0||typeof started!=="string")return null;const start2=Date.parse(started);return Number.isFinite(start2)?{start:start2,end:start2+duration4}:null});const known2=values.filter(value=>value!==null);const unknown2=values.length-known2.length;const intervals=known2.toSorted((left,right)=>left.start-right.start);let observed=0;let start=Number.NaN;let end=Number.NaN;for(const interval of intervals){if(!Number.isFinite(start)||interval.start>end){if(Number.isFinite(start))observed+=end-start;start=interval.start;end=interval.end}else end=Math.max(end,interval.end)}if(Number.isFinite(start))observed+=end-start;return{known_sum:observed,unknown:unknown2,complete:unknown2===0,coverage_ratio:values.length===0?1:known2.length/values.length}}function buildObservedDurationPeriods(runs,granularity){const groups=new Map;const group=key=>{const current=groups.get(key)??{intervals:[],known:0,unknown:0};groups.set(key,current);return current};for(const run of runs.filter(candidate=>isRootPhaseRun(candidate,"execution"))){const started=run.data?.source_started_at??run.data?.started_at;const duration4=durationForRun(run);if(typeof started!=="string")continue;const start=Date.parse(started);const startKey=saoPauloPeriodKey(started,granularity);if(!Number.isFinite(start)||startKey===null||typeof duration4!=="number"||duration4<0){if(startKey!==null)group(startKey).unknown+=1;continue}const end=start+duration4;let cursor=start;do{const key=saoPauloPeriodKey(new Date(cursor).toISOString(),granularity);if(key===null)break;const bounds=saoPauloPeriodBounds(key,granularity);const segmentEnd=Math.min(end,bounds.end);const target=group(key);target.intervals.push({start:Math.max(start,bounds.start),end:segmentEnd});target.known+=1;if(segmentEnd>=end)break;cursor=segmentEnd}while(cursor<=end)}return Object.fromEntries([...groups].map(([key,value])=>{const population=value.known+value.unknown;return[key,{known_sum:unionIntervals(value.intervals),unknown:value.unknown,complete:value.unknown===0,coverage_ratio:population===0?1:value.known/population}]}))}function durationForRun(run){const source=run.data?.source_duration_ms;if(typeof source==="number")return source;const legacy2=run.data?.duration_ms;return typeof legacy2==="number"?legacy2:null}function isRootPhaseRun(run,phase2){return(phase2===null||run.data?.phase===phase2)&&(run.data?.parent_run_id===null||run.data?.parent_run_id===void 0)}function unionIntervals(intervals){const ordered=intervals.toSorted((left,right)=>left.start-right.start);let observed=0;let start=Number.NaN;let end=Number.NaN;for(const interval of ordered){if(!Number.isFinite(start)||interval.start>end){if(Number.isFinite(start))observed+=end-start;start=interval.start;end=interval.end}else end=Math.max(end,interval.end)}return Number.isFinite(start)?observed+end-start:observed}function saoPauloPeriodBounds(key,granularity){const[year,month="01",day="01"]=key.split("-");const startParts={year:Number(year),month:Number(month),day:Number(day)};const next=new Date(Date.UTC(startParts.year,startParts.month-1,startParts.day));if(granularity==="day")next.setUTCDate(next.getUTCDate()+1);else if(granularity==="month")next.setUTCMonth(next.getUTCMonth()+1,1);else next.setUTCFullYear(next.getUTCFullYear()+1,0,1);return{start:saoPauloLocalMidnight(startParts.year,startParts.month,startParts.day),end:saoPauloLocalMidnight(next.getUTCFullYear(),next.getUTCMonth()+1,next.getUTCDate())}}function saoPauloLocalMidnight(year,month,day){const utcGuess=Date.UTC(year,month-1,day);const zone=saoPauloOffsetFormatter.formatToParts(new Date(utcGuess));const offset=zone.find(part=>part.type==="timeZoneName")?.value??"GMT";const match=/^GMT([+-])(\d{2}):(\d{2})$/.exec(offset);if(match===null)return utcGuess;const offsetMs=(Number(match[2])*60+Number(match[3]))*6e4*(match[1]==="+"?1:-1);return utcGuess-offsetMs}function executionDayCount(runs){return new Set(runs.filter(run=>isRootPhaseRun(run,"execution")).map(run=>run.data?.source_started_at??run.data?.started_at).filter(value=>typeof value==="string").map(value=>saoPauloDateFormatter.format(new Date(value)))).size}function buildUsage(runs){const metric5=field=>{const values=runs.map(run=>run.usage?.[field]??null);const known2=values.filter(value=>value!==null);const unknown2=values.length-known2.length;return{known_sum:known2.reduce((sum,value)=>sum+value,0),unknown:unknown2,complete:unknown2===0,coverage_ratio:values.length===0?1:known2.length/values.length}};const currencies=new Set(runs.map(run=>run.usage?.currency).filter(value=>value!==null));return{input_tokens:metric5("input_tokens"),output_tokens:metric5("output_tokens"),total_tokens:metric5("total_tokens"),cost:{...metric5("cost"),currency:currencies.size===1?[...currencies][0]??null:null}}}var saoPauloDateFormatter,saoPauloOffsetFormatter;var init_summary_metrics=__esm({"../lifecycle-manifests/src/summary-metrics.ts"(){"use strict";saoPauloDateFormatter=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"});saoPauloOffsetFormatter=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"})}});function durationForRun2(run){const source=run.data?.source_duration_ms;if(typeof source==="number")return source;const legacy2=run.data?.duration_ms;return typeof legacy2==="number"?legacy2:null}function creationDurationForRun(run){const canonical=run.data?.duration_ms;if(typeof canonical==="number")return canonical;return durationForRun2(run)}function buildCompactTaskMetrics(entities){return entities.filter(entity=>entity.kind==="task").map(task=>({id:task.id,status:task.status,risk:task.risk,updated_at:task.updated_at,finished_at:typeof task.data?.finished_at==="string"?task.data.finished_at:null})).sort((left,right)=>left.id.localeCompare(right.id))}function buildCompactMacroMetrics(entities){const macros=entities.filter(entity=>entity.kind==="prd"||entity.kind==="spec");const specs=macros.filter(entity=>entity.kind==="spec");const changes=entities.filter(entity=>entity.kind==="change");const tasks=entities.filter(entity=>entity.kind==="task");const executions=entities.filter(entity=>entity.kind==="execution");const runs=entities.filter(entity=>entity.kind==="run");const macroById=new Map(macros.map(macro=>[macro.id,macro]));const creationSpecsByRun=new Map;for(const spec of specs){const runId=stringField(spec.data,"creation_run_id");if(runId===null)continue;creationSpecsByRun.set(runId,[...creationSpecsByRun.get(runId)??[],spec.id])}return macros.map(macro=>{const specIds=new Set(macro.kind==="spec"?[macro.id]:specs.filter(spec=>stringField(spec.data,"prd_id")===macro.id).map(spec=>spec.id));const changeIds=new Set(changes.filter(change=>{const source=recordField2(change.data,"source");const type=stringField(source,"type");return macro.kind==="prd"&&type==="prd"&&stringField(source,"prd_id")===macro.id||(type==="spec"||type==="prd")&&specIds.has(stringField(source,"spec_id")??"")}).map(change=>change.id));const taskIds=new Set(tasks.filter(task=>changeIds.has(stringField(task.data,"change_id")??"")).map(task=>task.id));for(const id of plannedTaskIds(macro,macroById))taskIds.add(id);const executionIds=new Set(executions.filter(execution=>{const origin=recordField2(execution.data,"origin");const type=stringField(origin,"type");if(macro.kind==="prd"&&type==="prd"&&stringField(origin,"prd_id")===macro.id||type==="spec"&&specIds.has(stringField(origin,"spec_id")??""))return true;return executionTaskIds(execution.data).some(id=>taskIds.has(id))}).map(execution=>execution.id));const creationRunIds=new Set([macro,...specs.filter(spec=>specIds.has(spec.id))].map(entity=>stringField(entity.data,"creation_run_id")).filter(id=>id!==null));const relatedRuns=runs.filter(run=>{const data2=run.data;return creationRunIds.has(run.id)||specIds.has(stringField(data2,"spec_id")??"")||macro.kind==="prd"&&stringField(data2,"prd_id")===macro.id||taskIds.has(stringField(data2,"task_id")??"")||executionIds.has(stringField(data2,"execution_id")??"")});const canonicalRuns=[...new Map(relatedRuns.map(run=>[run.id,run])).values()];const rootExecutionRuns=canonicalRuns.filter(run=>run.data?.phase==="execution"&&run.data.parent_run_id==null);const sharedCreationRuns=macro.kind==="spec"?canonicalRuns.filter(run=>(creationSpecsByRun.get(run.id)?.length??0)>=1):[];const sharedCreationRunIds=new Set(sharedCreationRuns.map(run=>run.id));const observedDuration=buildObservedDuration(canonicalRuns.filter(run=>!sharedCreationRunIds.has(run.id)));const observedLifecycleDuration=observedLifecycleRootDuration(canonicalRuns);const knownRootRuns=rootExecutionRuns.filter(run=>{const duration4=durationForRun2(run);const started=run.data?.source_started_at??run.data?.started_at;return typeof duration4==="number"&&duration4>=0&&typeof started==="string"&&Number.isFinite(Date.parse(started))});const creationAllocation=(run,metric5,value)=>{const segments2=Array.isArray(run.data?.pricing_segments)?run.data.pricing_segments:[];const attributed=segments2.find(segment2=>stringField(segment2,"attributed_spec_id")===macro.id);if(attributed!==void 0){if(metric5==="duration")return numberField(attributed,"duration_ms");if(metric5==="tokens")return numberField(attributed,"total_tokens");return numberField(attributed,"recorded_brl")}const recipients=creationSpecsByRun.get(run.id)??[];return allocateSharedCreationValue(value,recipients).get(macro.id)??null};const allocatedDuration=sharedCreationRuns.map(run=>{const duration4=creationDurationForRun(run);return creationAllocation(run,"duration",duration4)}).filter(value=>value!==null);const durationMs=knownRootRuns.length===0&&allocatedDuration.length===0?null:observedDuration.known_sum+allocatedDuration.reduce((sum,value)=>sum+value,0);const executionStatuses=executions.filter(execution=>executionIds.has(execution.id)).map(execution=>execution.status??"");return{id:macro.id,title:macro.title??macro.id,kind:macro.kind,parent_id:macro.kind==="spec"?stringField(macro.data,"prd_id"):null,lifecycle_status:macro.status??"draft",work_status:compactMacroWorkStatus(macro.status,executionStatuses),created_at:stringField(macro.data,"created_at")??macro.updated_at,updated_at:macro.updated_at,task_count:taskIds.size,run_count:canonicalRuns.length,rework_run_count:canonicalRuns.filter(run=>stringField(run.data,"work_type")==="rework").length,canonical_run_ids:canonicalRuns.map(run=>run.id).sort(),root_execution_run_ids:rootExecutionRuns.map(run=>run.id).sort(),duration_ms:durationMs,observed_root_duration_ms:durationMs,observed_lifecycle_duration_ms:observedLifecycleDuration.known_runs===0?null:observedLifecycleDuration.known_sum,duration_coverage:{eligible_runs:rootExecutionRuns.length,known_runs:knownRootRuns.length,unknown_runs:rootExecutionRuns.length-knownRootRuns.length,coverage_ratio:rootExecutionRuns.length===0?1:knownRootRuns.length/rootExecutionRuns.length},duration_provenance:allocatedDuration.length>0?"shared_creation_allocation":knownRootRuns.length===0?"unavailable":"observed",lifecycle_duration_coverage:observedLifecycleDuration.coverage,lifecycle_duration_provenance:observedLifecycleDuration.known_runs===0?"unavailable":"observed",total_tokens:sumKnown(canonicalRuns.map(run=>sharedCreationRunIds.has(run.id)?creationAllocation(run,"tokens",run.usage?.total_tokens??null):run.usage?.total_tokens??null)),cost:sumKnown(canonicalRuns.map(run=>sharedCreationRunIds.has(run.id)?creationAllocation(run,"cost",run.usage?.cost??null):run.usage?.cost??null))}}).sort((left,right)=>left.id.localeCompare(right.id))}function observedLifecycleRootDuration(runs){const roots2=runs.filter(run=>run.data?.parent_run_id==null);const intervals=[];let known_runs=0;for(const run of roots2){const duration4=durationForRun2(run);const started=run.data?.source_started_at??run.data?.started_at;const start2=typeof started==="string"?Date.parse(started):Number.NaN;if(typeof duration4!=="number"||duration4<0||!Number.isFinite(start2))continue;known_runs+=1;intervals.push({start:start2,end:start2+duration4})}const ordered=intervals.toSorted((left,right)=>left.start-right.start);let known_sum=0;let start=Number.NaN;let end=Number.NaN;for(const interval of ordered){if(!Number.isFinite(start)||interval.start>end){if(Number.isFinite(start))known_sum+=end-start;start=interval.start;end=interval.end}else end=Math.max(end,interval.end)}if(Number.isFinite(start))known_sum+=end-start;const eligible_runs=roots2.length;return{known_sum,known_runs,coverage:{eligible_runs,known_runs,unknown_runs:eligible_runs-known_runs,coverage_ratio:eligible_runs===0?1:known_runs/eligible_runs}}}function compactMacroWorkStatus(lifecycleStatus,executionStatuses){if(lifecycleStatus==="delivered")return"completed";if(lifecycleStatus==="blocked")return"blocked";if(lifecycleStatus==="failed")return"failed";if(lifecycleStatus==="cancelled")return"cancelled";if(executionStatuses.some(status=>status==="running"||status==="paused"))return"executing";if(executionStatuses.includes("verifying"))return"verifying";if(executionStatuses.length>0&&executionStatuses.every(status=>status==="completed"))return lifecycleStatus==="active"?"verifying":"completed";if(lifecycleStatus==="active")return"executing";if(executionStatuses.includes("blocked"))return"blocked";if(executionStatuses.includes("failed"))return"failed";return"planning"}function plannedTaskIds(macro,macros){const own=blueprintTaskIds(recordField2(macro.data,"prepared_plan"));if(own.length>0||macro.kind!=="spec")return own;const parentId=stringField(macro.data,"prd_id");const parent=parentId===null?void 0:macros.get(parentId);const blueprints=recordField2(recordField2(parent?.data??null,"prepared_plan"),"blueprints");const matchingChanges=new Set(arrayField(blueprints,"changes").filter(change=>stringField(recordField2(change,"source"),"spec_id")===macro.id).map(change=>stringField(change,"id")).filter(id=>id!==null));return arrayField(blueprints,"tasks").filter(task=>matchingChanges.has(stringField(task,"change_id")??"")).map(task=>stringField(task,"id")).filter(id=>id!==null)}function blueprintTaskIds(plan){return arrayField(recordField2(plan,"blueprints"),"tasks").map(task=>stringField(task,"id")).filter(id=>id!==null)}function executionTaskIds(data2){return arrayField(recordField2(data2,"dag"),"nodes").map(node=>stringField(node,"task_id")).filter(id=>id!==null)}function recordField2(value,key){const candidate=value?.[key];return typeof candidate==="object"&&candidate!==null&&!Array.isArray(candidate)?candidate:null}function arrayField(value,key){const candidate=value?.[key];return Array.isArray(candidate)?candidate.filter(item=>typeof item==="object"&&item!==null&&!Array.isArray(item)):[]}function stringField(value,key){return typeof value?.[key]==="string"?value[key]:null}function numberField(value,key){return typeof value?.[key]==="number"?value[key]:null}function sumKnown(values){const known2=values.filter(value=>value!==null);return known2.length===0?null:known2.reduce((sum,value)=>sum+value,0)}var init_compact_macro_metrics=__esm({"../lifecycle-manifests/src/compact-macro-metrics.ts"(){"use strict";init_shared_creation_allocation();init_summary_metrics()}});function validateJournalLines(lines2,limit=JOURNAL_SEGMENT_BYTES){if(lines2.length>999999)throw new Error("Lifecycle journal segment space exhausted");for(const line of lines2)if(Buffer.byteLength(`${line}
@@ -3588,14 +3588,14 @@ ${await context2.filesystem.readText(path)}`)}const resolved=candidates.find(doc
3588
3588
  `}function contentHash(content){return createHash45("sha256").update(content).digest("hex").slice(0,16)}var DAILY_VIEWS_ROOT,DAILY_VIEWS_MANIFEST_PATH;var init_daily_read_model_storage=__esm({"../lifecycle-manifests/src/daily-read-model-storage.ts"(){"use strict";init_daily_read_model_shards();DAILY_VIEWS_ROOT=".agents/records/lifecycle/views";DAILY_VIEWS_MANIFEST_PATH=`${DAILY_VIEWS_ROOT}/manifest.json`}});function buildDailyLifecycleReadModels(entities,overview,updatedAt,sourceLatestAt,previous,dirtyMonths){const reusable=previous!==null&&dirtyMonths.size>0;const retained=reusable?Object.fromEntries(Object.entries(previous.days).filter(([day])=>!dirtyMonths.has(day.slice(0,7)))):{};const dirtyRuns=entities.filter(entity=>{if(entity.kind!=="run")return false;if(!reusable)return true;const timestamp13=periodTimestamp(entity);return timestamp13!==null&&dirtyMonths.has(saoPauloPeriodKey(timestamp13,"month")??"")});const entityById=new Map(entities.map(entity=>[entity.id,entity]));const relations=buildRelations(entities);const descriptors=buildDescriptors(entities,dirtyRuns,relations);const facts=new Map;for(const run of dirtyRuns){const timestamp13=periodTimestamp(run);if(timestamp13===null)continue;const day=saoPauloPeriodKey(timestamp13,"day");if(day===null)continue;const executionId=stringField2(run.data,"execution_id");const execution=executionId===null?void 0:entityById.get(executionId);const origin=recordField3(execution?.data,"origin");const taskId=stringField2(run.data,"task_id")??stringField2(origin,"task_id");const specId=stringField2(run.data,"spec_id")??stringField2(origin,"spec_id")??(taskId===null?null:relations.taskToSpec.get(taskId)??null);const directPrdId=stringField2(run.data,"prd_id")??stringField2(origin,"prd_id");const taskPrdId=taskId===null?void 0:relations.taskToPrd.get(taskId);const specPrdId=specId===null?void 0:relations.specToPrd.get(specId);const prdId=directPrdId??taskPrdId??specPrdId??null;const conversationId2=stringField2(run.data,"conversation_id")??stringField2(run.data,"client_thread_id")??stringField2(origin,"conversation_id");for(const[kind,id]of[["task",taskId],["spec",specId],["prd",prdId],["execution",executionId],["conversation",conversationId2]]){if(id===null||!descriptors.has(`${kind}:${id}`))continue;appendFact(facts,day,kind,id,run)}}for(const descriptor2 of descriptors.values()){if(descriptor2.created_at===null)continue;const day=saoPauloPeriodKey(descriptor2.created_at,"day");if(day===null)continue;appendFact(facts,day,descriptor2.kind,descriptor2.id,null)}const selectedDays=Object.keys(overview).filter(day=>!reusable||dirtyMonths.has(day.slice(0,7))).sort();const days=Object.fromEntries(selectedDays.map(day=>{const dayOverview=overview[day];if(dayOverview===void 0)throw new Error(`Missing overview for selected day: ${day}`);const groups=facts.get(day);const rows=kind=>[...groups?.get(kind)??new Map].flatMap(([id,runs])=>{const descriptor2=descriptors.get(`${kind}:${id}`);return descriptor2===void 0?[]:[compactDetail(descriptor2,day,runs)]}).sort(order);return[day,{overview:dayOverview,tasks:rows("task"),specs:rows("spec"),prds:rows("prd"),executions:rows("execution"),conversations:rows("conversation")}]}));return{schema_version:1,updated_at:updatedAt,source_latest_at:sourceLatestAt,days:{...retained,...days}}}function buildRelations(entities){const changeToSpec=new Map;const changeToPrd=new Map;const specToPrd=new Map;for(const entity of entities){if(entity.kind==="change"){const source=recordField3(entity.data,"source");const specId=stringField2(source,"spec_id");const prdId=stringField2(source,"prd_id");if(specId!==null)changeToSpec.set(entity.id,specId);if(prdId!==null)changeToPrd.set(entity.id,prdId)}else if(entity.kind==="spec"){const prdId=stringField2(entity.data,"prd_id");if(prdId!==null)specToPrd.set(entity.id,prdId)}}const taskToSpec=new Map;const taskToPrd=new Map;for(const task of entities.filter(entity=>entity.kind==="task")){const changeId=stringField2(task.data,"change_id");const specId=stringField2(task.data,"spec_id")??(changeId===null?null:changeToSpec.get(changeId)??null);const directPrdId=stringField2(task.data,"prd_id");const changePrdId=changeId===null?void 0:changeToPrd.get(changeId);const specPrdId=specId===null?void 0:specToPrd.get(specId);const prdId=directPrdId??changePrdId??specPrdId??null;if(specId!==null)taskToSpec.set(task.id,specId);if(prdId!==null)taskToPrd.set(task.id,prdId)}return{taskToSpec,taskToPrd,specToPrd}}function buildDescriptors(entities,runs,relations){const result2=new Map;for(const entity of entities){if(!["task","spec","prd","execution"].includes(entity.kind))continue;const kind=entity.kind;const data2=entity.data??{};const origin=recordField3(data2,"origin");const parent=kind==="task"?relations.taskToSpec.get(entity.id)??relations.taskToPrd.get(entity.id)??null:kind==="spec"?relations.specToPrd.get(entity.id)??null:kind==="execution"?stringField2(origin,"task_id")??stringField2(origin,"spec_id")??stringField2(origin,"prd_id"):null;const windowAt=kind==="task"?stringField2(data2,"finished_at")??entity.updated_at:entity.updated_at;result2.set(`${kind}:${entity.id}`,descriptor(entity.id,kind,entity.title,entity.status,entity.risk,periodTimestamp(entity),windowAt,parent))}for(const run of runs){const executionId=stringField2(run.data,"execution_id");const conversationId2=stringField2(run.data,"conversation_id")??stringField2(run.data,"client_thread_id");const createdAt=periodTimestamp(run);if(executionId!==null&&!result2.has(`execution:${executionId}`))result2.set(`execution:${executionId}`,descriptor(executionId,"execution",null,run.status,null,createdAt,createdAt,stringField2(run.data,"task_id")));if(conversationId2!==null){const key=`conversation:${conversationId2}`;const prior=result2.get(key);if(prior===void 0||createdAt!==null&&(prior.created_at===null||createdAt<prior.created_at))result2.set(key,descriptor(conversationId2,"conversation",null,run.status,null,createdAt,createdAt,executionId))}}return result2}function descriptor(id,kind,title,status,risk2,createdAt,windowAt,parentId){return{id,title:title??id,kind,status,risk:risk2,created_at:createdAt,window_at:windowAt??createdAt??new Date(0).toISOString(),parent_id:parentId}}function appendFact(facts,day,kind,id,run){const groups=facts.get(day)??new Map;const byId2=groups.get(kind)??new Map;const current=byId2.get(id)??[];if(run!==null)current.push(run);byId2.set(id,current);groups.set(kind,byId2);facts.set(day,groups)}function stringField2(source,field){return typeof source==="object"&&source!==null&&typeof source[field]==="string"?source[field]:null}function recordField3(source,field){if(typeof source!=="object"||source===null)return null;const value=source[field];return typeof value==="object"&&value!==null?value:null}function order(left,right){return right.occurred_at.localeCompare(left.occurred_at)||left.id.localeCompare(right.id)}function compactDetail(descriptor2,day,runs){const unique2=uniqueRuns2(runs);const phase2=descriptor2.kind==="conversation"?null:"execution";return{id:descriptor2.id,title:descriptor2.title,kind:descriptor2.kind,status:descriptor2.status,risk:descriptor2.risk,occurred_at:periodTimestamp(unique2.at(0)??{kind:"task",updated_at:`${day}T00:00:00.000Z`})??`${day}T00:00:00.000Z`,window_at:descriptor2.window_at,parent_id:descriptor2.parent_id,run_count:unique2.length,cost_currency:singleCurrency(unique2),lifecycle_elapsed_ms:lifecycleElapsedMs(unique2,phase2),metrics:readMetrics(unique2,phase2)}}function lifecycleElapsedMs(runs,phase2){const roots2=runs.filter(run=>(phase2===null||run.data?.phase===phase2)&&(run.data?.parent_run_id===null||run.data?.parent_run_id===void 0));if(roots2.length===0)return null;const terminal=new Set(["completed","failed","cancelled"]);const intervals=roots2.flatMap(run=>{if(!terminal.has(run.status??""))return[];const startedAt=stringField2(run.data,"started_at");const finishedAt=stringField2(run.data,"finished_at");const start2=startedAt===null?Number.NaN:Date.parse(startedAt);const end2=finishedAt===null?Number.NaN:Date.parse(finishedAt);return Number.isFinite(start2)&&Number.isFinite(end2)&&end2>=start2?[{start:start2,end:end2}]:[]});if(intervals.length!==roots2.length)return null;const ordered=intervals.toSorted((left,right)=>left.start-right.start);const[first,...remaining]=ordered;if(first===void 0)return null;let total=0;let start=first.start;let end=first.end;for(const interval of remaining){if(interval.start>end){total+=end-start;start=interval.start;end=interval.end}else end=Math.max(end,interval.end)}return total+end-start}function singleCurrency(runs){const values=new Set(runs.flatMap(run=>run.usage?.currency?[run.usage.currency]:[]));const[currency]=values;return values.size===1?currency??null:null}function uniqueRuns2(runs){const seen=new Set;return runs.filter(run=>{const key=stringField2(run.data,"source_segment_key")??run.id;if(seen.has(key))return false;seen.add(key);return true})}function readMetrics(runs,phase2){const metric5=value=>{const values=runs.map(value);const known2=values.filter(item=>item!==null);const unknown2=values.length-known2.length;return{known_sum:known2.reduce((sum,item)=>sum+item,0),unknown:unknown2,complete:unknown2===0,coverage_ratio:values.length===0?1:known2.length/values.length}};return{duration:buildObservedDuration(runs,phase2),total_tokens:metric5(run=>run.usage?.total_tokens??null),cost:metric5(run=>run.usage?.cost??null)}}var init_daily_read_models=__esm({"../lifecycle-manifests/src/daily-read-models.ts"(){"use strict";init_summary_metrics()}});function buildObservedExecutionMetrics(runs){return{routing:known(runs.map(run=>hasRoute(run)?1:null)),delegated_runs:known(runs.map(run=>delegated(run))),rework_runs:known(runs.map(run=>workType(run))),blocked_runs:known(runs.map(run=>blocked(run)))}}function buildCaptureDiagnostics(runs){const captured_at=captureKnown(runs.map(run=>timestamp12(run)===null?null:1));const usage=captureKnown(runs.map(run=>typeof run.usage?.total_tokens==="number"?1:null));const source_duration=captureKnown(runs.map(run=>typeof run.data?.source_duration_ms==="number"?1:null));const causes=[captured_at.unknown>0?"missing_capture_timestamp":null,usage.unknown>0?"missing_usage":null,source_duration.unknown>0?"missing_source_duration":null].filter(value=>value!==null);return{status:runs.length===0?"unavailable":causes.length===0?"complete":"partial",causes,coverage:{captured_at,usage,source_duration}}}function hasRoute(run){return typeof run.data?.agent_selection_capability==="string"&&run.data.agent_selection_capability.length>0||typeof run.data?.agent_selection_reasons==="string"&&run.data.agent_selection_reasons.length>0||Array.isArray(run.data?.agent_selection_reasons)&&run.data.agent_selection_reasons.length>0?1:null}function delegated(run){const parent=run.data?.parent_run_id;return typeof parent==="string"?1:parent===null?0:null}function workType(run){return run.data?.work_type==="rework"?1:run.data?.work_type==="new"?0:null}function blocked(run){const outcome=run.data?.lifecycle_outcome??run.data?.task_outcome;return outcome==="blocked"?1:["completed","failed","cancelled"].includes(String(outcome))?0:null}function timestamp12(run){const value=run.data?.captured_at;return typeof value==="string"&&Number.isFinite(Date.parse(value))?value:null}function captureKnown(values){if(values.length===0)return{known_sum:0,unknown:0,complete:false,coverage_ratio:0};return known(values)}function known(values){const observed=values.filter(value=>value!==null);return{known_sum:observed.reduce((total,value)=>total+value,0),unknown:values.length-observed.length,complete:values.length>0&&observed.length===values.length,coverage_ratio:values.length===0?0:observed.length/values.length}}var init_observed_execution_metrics=__esm({"../lifecycle-manifests/src/observed-execution-metrics.ts"(){"use strict"}});import{randomUUID as randomUUID7}from"node:crypto";async function withLifecycleCanonicalMutationLock(filesystem,operation,options={}){const now=options.now??Date.now;const isProcessAlive3=options.is_process_alive??isProcessAliveByPid;const delayFn=options.delay??delay3;const timeoutMs=options.timeout_ms??DEFAULT_TIMEOUT_MS;const deadline=now()+timeoutMs;const startedAt=now();const owner=lockForCurrentProcess();const content=`${JSON.stringify(owner)}
3589
3589
  `;let attempts=0;while(now()<deadline){attempts+=1;try{await filesystem.writeTextExclusive(MUTATION_LOCK_PATH,content)}catch(error51){if(!isNodeError7(error51)||error51.code!=="EEXIST")throw error51;await recoverOnlyProvenDeadOwner(filesystem,now,isProcessAlive3);if(now()>=deadline)break;await delayFn(Math.min(RETRY_DELAY_MS,Math.max(0,deadline-now())));continue}try{return await operation()}finally{await filesystem.removeFileIfContentMatches(MUTATION_LOCK_PATH,content)}}throw new LifecycleCanonicalMutationBusyError({waited_ms:Math.max(0,now()-startedAt),attempts,owner:await observedOwner(filesystem,now,isProcessAlive3)})}async function observedOwner(filesystem,now,isProcessAlive3){try{const lock2=parseMutationLock(await filesystem.readText(MUTATION_LOCK_PATH));if(lock2===null)return null;return{pid:lock2.pid,acquired_at:lock2.acquired_at,age_ms:Math.max(0,ageMs(lock2,now)),alive:isProcessAlive3(lock2.pid)}}catch(error51){if(isNodeError7(error51)&&error51.code==="ENOENT")return null;throw error51}}async function recoverOnlyProvenDeadOwner(filesystem,now,isProcessAlive3){let observed;try{observed=await filesystem.readText(MUTATION_LOCK_PATH)}catch(error51){if(isNodeError7(error51)&&error51.code==="ENOENT")return;throw error51}const lock2=parseMutationLock(observed);if(lock2===null||isProcessAlive3(lock2.pid)||ageMs(lock2,now)<STALE_OWNER_MINIMUM_AGE_MS)return;await filesystem.removeFileIfContentMatches(MUTATION_LOCK_PATH,observed)}function lockForCurrentProcess(){return{schema_version:1,pid:process.pid,owner_nonce:randomUUID7(),acquired_at:new Date().toISOString()}}function parseMutationLock(content){try{const value=JSON.parse(content);return value.schema_version===1&&Number.isSafeInteger(value.pid)&&value.pid>0&&typeof value.owner_nonce==="string"&&value.owner_nonce.length>0&&typeof value.acquired_at==="string"&&Number.isFinite(Date.parse(value.acquired_at))?value:null}catch{return null}}function ageMs(lock2,now){return now()-Date.parse(lock2.acquired_at)}function isProcessAliveByPid(pid){try{process.kill(pid,0);return true}catch(error51){return isNodeError7(error51)&&error51.code==="EPERM"}}function isNodeError7(error51){return error51 instanceof Error&&"code"in error51}function delay3(milliseconds){return new Promise(resolve32=>setTimeout(resolve32,milliseconds))}var MUTATION_LOCK_PATH,DEFAULT_TIMEOUT_MS,RETRY_DELAY_MS,STALE_OWNER_MINIMUM_AGE_MS,LifecycleCanonicalMutationBusyError;var init_canonical_mutation_lock=__esm({"../lifecycle-manifests/src/source-size-manifests/canonical-mutation-lock.ts"(){"use strict";MUTATION_LOCK_PATH=".local/locks/lifecycle-canonical-mutation.lock";DEFAULT_TIMEOUT_MS=3e3;RETRY_DELAY_MS=25;STALE_OWNER_MINIMUM_AGE_MS=1e3;LifecycleCanonicalMutationBusyError=class extends Error{constructor(diagnostics){super(`Lifecycle canonical mutation is busy after ${diagnostics.waited_ms}ms; `+(diagnostics.owner===null?"lock owner is unavailable":`owner pid ${diagnostics.owner.pid} has held it for ${diagnostics.owner.age_ms}ms (${diagnostics.owner.alive?"alive":"not observed alive"})`));this.diagnostics=diagnostics;this.name="LifecycleCanonicalMutationBusyError"}diagnostics;code="LIFECYCLE_CANONICAL_MUTATION_BUSY"}}});var init_golden_observability=__esm({"../lifecycle-manifests/src/golden/golden-observability.ts"(){"use strict"}});var init_golden_observability_fixture=__esm({"../lifecycle-manifests/src/golden/golden-observability-fixture.ts"(){"use strict"}});var init_golden=__esm({"../lifecycle-manifests/src/golden/index.ts"(){"use strict";init_golden_observability();init_golden_observability_fixture()}});function relationEdgesFor(entity){if((entity.relation_edges?.length??0)>0)return entity.relation_edges??[];return entity.relations.map(target_id=>({target_id,type:"references",direction:"outbound",provenance:"derived",source_locator:null}))}function graphNeighbors(entities,id){const byId2=new Map(entities.map(entity=>[entity.id,entity]));const result2=new Map;const own=byId2.get(id);if(own!==void 0){for(const edge of relationEdgesFor(own)){const entity=byId2.get(edge.target_id);if(entity!==void 0)result2.set(`${entity.id}:outbound:${edge.type}`,{entity,edge})}}for(const entity of entities){for(const edge of relationEdgesFor(entity)){if(edge.target_id===id){result2.set(`${entity.id}:inbound:${edge.type}`,{entity,edge:{...edge,direction:"inbound"}})}}}return[...result2.values()].sort((left,right)=>left.entity.id.localeCompare(right.entity.id))}function stateShard(id){let hash6=0;for(const character of id)hash6=hash6*31+character.charCodeAt(0)>>>0;return hash6%STATE_SHARDS}function buildSnapshot(entities,updatedAt,previousSummary=null,dirtyMonths=new Set){const byKind={};const byStatus={};const byKindStatus={};for(const entity of entities){byKind[entity.kind]=(byKind[entity.kind]??0)+1;if(entity.status!==null){byStatus[entity.status]=(byStatus[entity.status]??0)+1;const statuses=byKindStatus[entity.kind]??{};statuses[entity.status]=(statuses[entity.status]??0)+1;byKindStatus[entity.kind]=statuses}}const runs=entities.filter(entity=>entity.kind==="run");const usage=buildUsage(runs);const canReusePeriods=previousSummary?.run_metrics!==void 0&&dirtyMonths.size>0;const periods=canReusePeriods?buildIncrementalPeriods(entities,previousSummary,dirtyMonths):{daily:buildPeriods(entities,"day"),monthly:buildPeriods(entities,"month"),annual:buildPeriods(entities,"year")};const sourceLatestAt=entities.map(entity=>entity.updated_at).sort().at(-1)??null;return{schema_version:1,updated_at:updatedAt,freshness:{source_latest_at:sourceLatestAt,lag_ms:sourceLatestAt===null?null:Math.max(0,Date.parse(updatedAt)-Date.parse(sourceLatestAt))},capture_diagnostics:buildCaptureDiagnostics(runs),execution_observability:buildObservedExecutionMetrics(runs),counts:{total:entities.length,by_kind:byKind,by_status:byStatus,by_kind_status:byKindStatus},usage,duration:buildObservedDuration(runs),execution_day_count:executionDayCount(runs),events:buildKnownRunMetric(runs,"events"),run_metrics:buildCompactRunMetrics(runs),task_metrics:buildCompactTaskMetrics(entities),macro_metrics:buildCompactMacroMetrics(entities),task_status_counts:countTaskField(entities,"status"),task_risk_counts:countTaskField(entities,"risk"),top_tasks:buildTopTasks(runs),latest_task_created_at:latestTaskCreatedAt(entities),periods}}function compactOverview(summary){const{run_metrics:_runMetrics,daily_read_models:_dailyReadModels,...overview}=summary;return overview}function buildIncrementalPeriods(entities,previous,dirtyMonths){const dirtyYears=new Set([...dirtyMonths].map(month=>month.slice(0,4)));const dirtyEntities=entities.filter(entity=>{const timestamp13=periodTimestamp(entity);const month=timestamp13===null?null:saoPauloPeriodKey(timestamp13,"month");return month!==null&&dirtyMonths.has(month)});const dirtyYearEntities=entities.filter(entity=>{const timestamp13=periodTimestamp(entity);const year=timestamp13===null?null:saoPauloPeriodKey(timestamp13,"year");return year!==null&&dirtyYears.has(year)});const retain=(source,isDirty)=>Object.fromEntries(Object.entries(source).filter(([key])=>!isDirty(key)));return{daily:{...retain(previous.periods.daily,key=>dirtyMonths.has(key.slice(0,7))),...buildPeriods(dirtyEntities,"day")},monthly:{...retain(previous.periods.monthly,key=>dirtyMonths.has(key)),...buildPeriods(dirtyEntities,"month")},annual:{...retain(previous.periods.annual,key=>dirtyYears.has(key)),...buildPeriods(dirtyYearEntities,"year")}}}function affectedPeriodMonths(entity){const timestamp13=periodTimestamp(entity);const startMonth=timestamp13===null?null:saoPauloPeriodKey(timestamp13,"month");if(startMonth===null)return[];const duration4=entity.kind==="run"?entity.data?.source_duration_ms:null;const startedAt=timestamp13===null?Number.NaN:Date.parse(timestamp13);if(typeof duration4!=="number"||duration4<=0||!Number.isFinite(startedAt)){return[startMonth]}const endMonth=saoPauloPeriodKey(new Date(startedAt+Math.max(0,duration4-1)).toISOString(),"month");return endMonth===null||endMonth===startMonth?[startMonth]:[startMonth,endMonth]}function buildPeriods(entities,granularity){const groups=new Map;const durationByPeriod=buildObservedDurationPeriods(entities.filter(entity=>entity.kind==="run"),granularity);for(const entity of entities){const timestamp13=periodTimestamp(entity);if(timestamp13===null)continue;const key=saoPauloPeriodKey(timestamp13,granularity);if(key===null)continue;groups.set(key,[...groups.get(key)??[],entity])}return Object.fromEntries([...new Set([...groups.keys(),...Object.keys(durationByPeriod)])].sort((left,right)=>left.localeCompare(right)).map(key=>{const group=groups.get(key)??[];const runs=group.filter(entity=>entity.kind==="run");return[key,{prds:group.filter(entity=>entity.kind==="prd").length,specs:group.filter(entity=>entity.kind==="spec").length,tasks:group.filter(entity=>entity.kind==="task").length,validations:group.filter(entity=>entity.kind==="validation").length,evidences:group.filter(entity=>entity.kind==="evidence").length,runs:runs.length,usage:buildUsage(runs),duration:durationByPeriod[key]??buildObservedDuration(runs),execution_day_count:executionDayCount(runs),events:buildKnownRunMetric(runs,"events"),task_status_counts:countTaskField(group,"status"),task_risk_counts:countTaskField(group,"risk"),top_tasks:buildTopTasks(runs),latest_task_created_at:latestTaskCreatedAt(group)}]}))}function countTaskField(entities,field){const counts={};for(const entity of entities){if(entity.kind!=="task")continue;const value=entity[field];if(value!==null)counts[value]=(counts[value]??0)+1}return counts}function latestTaskCreatedAt(entities){return entities.filter(entity=>entity.kind==="task").map(entity=>typeof entity.data?.created_at==="string"?entity.data.created_at:entity.updated_at).sort().at(-1)??null}function buildActiveWork(entities,updatedAt){const workKinds=new Set(["prd","spec","change","task","execution","run"]);const terminal=new Set(["completed","delivered","cancelled","superseded","failed","rolled_back","passed"]);return{schema_version:1,updated_at:updatedAt,items:entities.filter(entity=>workKinds.has(entity.kind)&&entity.status!==null&&!terminal.has(entity.status)).sort((left,right)=>right.updated_at.localeCompare(left.updated_at)).map(({usage:_usage,data:_data,...entity})=>entity)}}function pretty2(value){return`${JSON.stringify(value,null,2)}
3590
3590
  `}function isNodeError8(error51){return error51 instanceof Error&&"code"in error51}function isProcessAlive2(pid){try{process.kill(pid,0);return true}catch(error51){return isNodeError8(error51)&&error51.code==="EPERM"}}function delay4(milliseconds){return new Promise(resolve32=>setTimeout(resolve32,milliseconds))}var LIFECYCLE_MANIFEST_ROOT,MANIFEST_PATH,ENTITY_SNAPSHOT_PATH,LEGACY_STATE_PATH,STATE_ROOT,STATE_SHARDS,SUMMARY_PATH,OVERVIEW_PATH,ACTIVE_WORK_PATH,LOCK_PATH,entityKindSchema,ENTITY_KINDS,relationTypeSchema,relationProvenanceSchema,relationEdgeSchema,usageSchema,compactEntitySchema,lifecycleManifestEventSchema,LifecycleManifestStore;var init_src8=__esm({"../lifecycle-manifests/src/index.ts"(){"use strict";init_zod();init_compact_macro_metrics();init_journal_segments();init_shared_creation_allocation();init_compact_run_metrics();init_daily_read_model_storage();init_daily_read_models();init_observed_execution_metrics();init_summary_metrics();init_canonical_mutation_lock();init_golden();init_summary_metrics();LIFECYCLE_MANIFEST_ROOT=".agents/records/lifecycle";MANIFEST_PATH=`${LIFECYCLE_MANIFEST_ROOT}/manifest.json`;ENTITY_SNAPSHOT_PATH=`${LIFECYCLE_MANIFEST_ROOT}/entity-snapshot.json`;LEGACY_STATE_PATH=`${LIFECYCLE_MANIFEST_ROOT}/entity-state.json`;STATE_ROOT=`${LIFECYCLE_MANIFEST_ROOT}/indexes`;STATE_SHARDS=16;SUMMARY_PATH=`${LIFECYCLE_MANIFEST_ROOT}/summary.json`;OVERVIEW_PATH=`${LIFECYCLE_MANIFEST_ROOT}/overview.json`;ACTIVE_WORK_PATH=`${LIFECYCLE_MANIFEST_ROOT}/active-work.json`;LOCK_PATH=".local/locks/lifecycle-manifest.lock";entityKindSchema=external_exports.enum(["prd","spec","change","task","execution","run","decision","validation","evidence"]);ENTITY_KINDS=entityKindSchema.options;relationTypeSchema=external_exports.enum(["parent","child","references","evidence","requirement"]);relationProvenanceSchema=external_exports.enum(["explicit","derived"]);relationEdgeSchema=external_exports.object({target_id:external_exports.string().min(1),type:relationTypeSchema,direction:external_exports.enum(["outbound","inbound"]),provenance:relationProvenanceSchema,source_locator:external_exports.string().min(1).nullable().default(null)}).strict();usageSchema=external_exports.object({input_tokens:external_exports.number().int().nonnegative().nullable().default(null),output_tokens:external_exports.number().int().nonnegative().nullable().default(null),cached_input_tokens:external_exports.number().int().nonnegative().nullable().default(null),total_tokens:external_exports.number().int().nonnegative().nullable().default(null),cost:external_exports.number().nonnegative().nullable().default(null),currency:external_exports.string().min(1).nullable().default(null)}).strict();compactEntitySchema=external_exports.object({kind:entityKindSchema,id:external_exports.string().min(1),title:external_exports.string().min(1).nullable().default(null),status:external_exports.string().min(1).nullable().default(null),risk:external_exports.string().min(1).nullable().default(null),priority:external_exports.string().min(1).nullable().default(null),updated_at:external_exports.string().datetime({offset:true}),relations:external_exports.array(external_exports.string().min(1)).default([]),relation_edges:external_exports.array(relationEdgeSchema).optional(),usage:usageSchema.nullable().default(null),data:external_exports.record(external_exports.string(),external_exports.unknown()).nullable().default(null)}).strict();lifecycleManifestEventSchema=external_exports.object({schema_version:external_exports.literal(1),event_id:external_exports.string().min(1),occurred_at:external_exports.string().datetime({offset:true}),operation:external_exports.enum(["upsert","remove"]),entity:compactEntitySchema}).strict();LifecycleManifestStore=class{constructor(filesystem){this.filesystem=filesystem}filesystem;async append(event){return this.appendMany([event])}async appendMany(events){const parsed=events.map(event=>lifecycleManifestEventSchema.parse(event));validateJournalLines(parsed.map(event=>JSON.stringify(event)));return this.withLock(async()=>{const byMonth=new Map;for(const event of parsed){const month=event.occurred_at.slice(0,7);byMonth.set(month,[...byMonth.get(month)??[],event])}await Promise.all([...byMonth].map(([month,monthEvents])=>appendJournalSegments(this.filesystem,`${LIFECYCLE_MANIFEST_ROOT}/chunks`,month,monthEvents.map(event=>JSON.stringify(event)))));return this.refreshUnlocked()})}async refresh(){return this.withLock(()=>this.refreshUnlocked())}async refreshUnlocked(){const manifest=await this.readJson(MANIFEST_PATH,{schema_version:1,updated_at:new Date(0).toISOString(),offsets:{}});const states=await this.readStates();const[previousSummary,previousDailyReadModels]=await Promise.all([this.readSummary(),this.readDailyReadModels()]);const dirtyShards=new Set;const dirtyMonths=new Set;const legacyState=await this.filesystem.exists(LEGACY_STATE_PATH)||(await Promise.all(ENTITY_KINDS.map(kind=>this.filesystem.exists(this.aggregateStatePath(kind))))).some(Boolean);if(legacyState){for(const kind of ENTITY_KINDS){for(let shard=0;shard<STATE_SHARDS;shard+=1){dirtyShards.add(`${kind}:${shard}`)}}}const journals=await this.filesystem.listFiles(`${LIFECYCLE_MANIFEST_ROOT}/chunks`,".jsonl");for(const journal of journals){const offset=manifest.offsets[journal]??0;const delta=await this.filesystem.readTextFrom(journal,offset);for(const line of delta.content.split(/\r?\n/).filter(Boolean)){const event=lifecycleManifestEventSchema.parse(JSON.parse(line));const state=states[event.entity.kind];const previous=state.entities[event.entity.id];for(const candidate of[previous,event.entity]){if(candidate===void 0)continue;for(const month of affectedPeriodMonths(candidate))dirtyMonths.add(month)}if(event.operation==="remove")delete state.entities[event.entity.id];else state.entities[event.entity.id]=event.entity;dirtyShards.add(`${event.entity.kind}:${stateShard(event.entity.id)}`)}manifest.offsets[journal]=delta.nextOffset}if(dirtyShards.size===0&&!legacyState&&previousDailyReadModels!==null&&previousSummary!==null){return previousSummary}const updatedAt=new Date().toISOString();manifest.updated_at=updatedAt;const entities=ENTITY_KINDS.flatMap(kind=>Object.values(states[kind].entities));const baseSnapshot=buildSnapshot(entities,updatedAt,previousSummary,dirtyMonths);const dailyReadModels=buildDailyLifecycleReadModels(entities,baseSnapshot.periods.daily,updatedAt,baseSnapshot.freshness.source_latest_at,previousDailyReadModels,dirtyMonths);const snapshot=baseSnapshot;const active=buildActiveWork(entities,updatedAt);await Promise.all([this.filesystem.writeTextAtomic(MANIFEST_PATH,pretty2(manifest)),this.filesystem.removeFile(ENTITY_SNAPSHOT_PATH),...[...dirtyShards].map(key=>{const[kind,rawShard]=key.split(":");const shard=Number(rawShard);const entities2=Object.fromEntries(Object.entries(states[kind].entities).filter(([id])=>stateShard(id)===shard));return this.filesystem.writeTextAtomic(this.statePath(kind,shard),pretty2({schema_version:1,entities:entities2}))}),this.filesystem.writeTextAtomic(SUMMARY_PATH,pretty2(snapshot)),this.filesystem.writeTextAtomic(OVERVIEW_PATH,pretty2(compactOverview(snapshot))),this.writeDailyReadModels(dailyReadModels),this.filesystem.writeTextAtomic(ACTIVE_WORK_PATH,pretty2(active))]);if(await this.filesystem.exists(LEGACY_STATE_PATH))await this.filesystem.removeFile(LEGACY_STATE_PATH);await Promise.all(ENTITY_KINDS.map(async kind=>{const path=this.aggregateStatePath(kind);if(await this.filesystem.exists(path))await this.filesystem.removeFile(path)}));return snapshot}async replace(events){return this.withLock(async()=>{const now=new Date().toISOString();const path=`${LIFECYCLE_MANIFEST_ROOT}/chunks/${now.slice(0,7)}.jsonl`;const content=events.map(event=>JSON.stringify(lifecycleManifestEventSchema.parse(event))).join("\n");validateJournalLines(content?content.split("\n"):[]);const existingJournals=await this.filesystem.listFiles(`${LIFECYCLE_MANIFEST_ROOT}/chunks`,".jsonl");const existingShards=await this.filesystem.listFiles(STATE_ROOT,".json");const existingViews=await this.filesystem.listFiles(DAILY_VIEWS_ROOT,".json");await Promise.all(existingJournals.filter(journal=>journal!==path).map(journal=>this.filesystem.removeFile(journal)));await this.filesystem.removeFile(path);await appendJournalSegments(this.filesystem,`${LIFECYCLE_MANIFEST_ROOT}/chunks`,now.slice(0,7),content?content.split("\n"):[]);await Promise.all([this.filesystem.writeTextAtomic(MANIFEST_PATH,pretty2({schema_version:1,updated_at:new Date(0).toISOString(),offsets:{}})),this.filesystem.removeFile(ENTITY_SNAPSHOT_PATH),this.filesystem.removeFile(LEGACY_STATE_PATH),...existingShards.map(shard=>this.filesystem.removeFile(shard)),...existingViews.map(view=>this.filesystem.removeFile(view))]);return this.refreshUnlocked()})}async readSummary(){if(!await this.filesystem.exists(SUMMARY_PATH))return null;return JSON.parse(await this.filesystem.readText(SUMMARY_PATH))}async readOverview(){if(!await this.filesystem.exists(OVERVIEW_PATH))return this.readSummary();return JSON.parse(await this.filesystem.readText(OVERVIEW_PATH))}async readDailyReadModels(collection){return await readDailyReadModelsView(this.filesystem,collection)??(await this.readSummary())?.daily_read_models??null}async writeDailyReadModels(snapshot){await writeDailyReadModelsView(this.filesystem,snapshot)}async readActiveWork(){if(!await this.filesystem.exists(ACTIVE_WORK_PATH))return null;return JSON.parse(await this.filesystem.readText(ACTIVE_WORK_PATH))}async readEntities(kind){const manifest=await this.readJson(MANIFEST_PATH,null);const states=await this.readStates();const sharded=ENTITY_KINDS.flatMap(candidate=>Object.values(states[candidate].entities));if(sharded.length>0){return kind===void 0?sharded:Object.values(states[kind].entities)}const snapshot=await this.readJson(ENTITY_SNAPSHOT_PATH,null);if(manifest!==null&&snapshot?.schema_version===1&&snapshot.updated_at===manifest.updated_at){return Object.values(snapshot.entities).filter(entity=>kind===void 0||entity.kind===kind)}return[]}statePath(kind,shard){return`${STATE_ROOT}/${kind}/${shard.toString(16).padStart(2,"0")}.json`}aggregateStatePath(kind){return`${STATE_ROOT}/${kind}.json`}async readStates(){const states=Object.fromEntries(await Promise.all(ENTITY_KINDS.map(async kind=>[kind,await this.readKindState(kind)])));const legacy2=await this.readJson(LEGACY_STATE_PATH,null);for(const entity of Object.values(legacy2?.entities??{})){states[entity.kind].entities[entity.id]=entity}return states}async readKindState(kind){const aggregate=await this.readJson(this.aggregateStatePath(kind),null);if(aggregate!==null)return aggregate;const shardPaths=await this.filesystem.listFiles(`${STATE_ROOT}/${kind}`,".json");const shards=await Promise.all(shardPaths.map(path=>this.readJson(path,null)));return{schema_version:1,entities:Object.assign({},...shards.map(shard=>shard?.entities??{}))}}async readJson(path,fallback){try{return JSON.parse(await this.filesystem.readText(path))}catch(error51){if(isNodeError8(error51)&&error51.code==="ENOENT")return fallback;throw error51}}async withLock(operation){for(let attempt=0;attempt<80;attempt+=1){try{await this.filesystem.writeTextExclusive(LOCK_PATH,`${JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()})}
3591
- `);try{return await operation()}finally{await this.filesystem.removeFile(LOCK_PATH)}}catch(error51){if(!isNodeError8(error51)||error51.code!=="EEXIST")throw error51;if(await this.removeStaleLock())continue;await delay4(Math.min(100,10+attempt*2))}}throw new Error("Lifecycle manifest is busy; retry the operation")}async removeStaleLock(){try{const lock2=JSON.parse(await this.filesystem.readText(LOCK_PATH));if(typeof lock2.pid!=="number"||!isProcessAlive2(lock2.pid)){await this.filesystem.removeFile(LOCK_PATH);return true}}catch(error51){if(isNodeError8(error51)&&error51.code==="ENOENT")return true;return false}return false}}}});async function validateAdministrativeClosure(input){const fail=()=>{throw new Error("Terminal Task permits only a verified administrative release-cycle closure")};if(input.paths.length!==1||input.paths[0]!==releaseCyclePath3||!input.productCommit||!/^[a-f0-9]{40}$/.test(input.productCommit)||!["blocked","failed","cancelled"].includes(input.taskStatus)||input.changeStatus!==input.taskStatus||input.executionStatus!==input.taskStatus)fail();const product=input.productCommit;await input.git("merge-base","--is-ancestor",product,input.targetTree);const before=JSON.parse(await input.git("show",`${product}:${releaseCyclePath3}`));const after=JSON.parse(await input.filesystem.readText(releaseCyclePath3));if(before.state!=="frozen"||before.release_task_id!==input.taskId||typeof before.release_run_id!=="string"||!before.release_run_id.startsWith("RUN-")||!/^\d+\.\d+$/.test(before.current_release)||!Array.isArray(before.history)||!Array.isArray(after.history))fail();const tag=(await input.git("rev-parse","--verify",`refs/tags/v${before.current_release}^{commit}`)).trim();if(tag!==product)fail();const[major,minor]=before.current_release.split(".").map(Number);const next=`${major}.${minor+1}`;const entry2=after.history.at(-1);const recoveryDeclared=entry2&&Object.keys(entry2).some(key=>key.startsWith("publisher_recovery_"));const recoveryKeys=recoveryDeclared?["publisher_recovery_ci_run_id","publisher_recovery_paths","publisher_recovery_sha"]:[];if(recoveryDeclared){if(typeof entry2.publisher_recovery_sha!=="string"||!await validatePublisherRecoveryBoundary(input.git,entry2,entry2.publisher_recovery_sha,product))fail();await input.git("merge-base","--is-ancestor",entry2.publisher_recovery_sha,input.targetTree)}if(!entry2||entry2.from!==before.current_release||entry2.to!==next||entry2.sha!==product||!Number.isSafeInteger(entry2.ci_run_id)||entry2.ci_run_id<=0||entry2.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${before.current_release}`||typeof entry2.advanced_at!=="string"||!Number.isFinite(Date.parse(entry2.advanced_at))||Object.keys(entry2).sort().join()!==["advanced_at","ci_run_id","from",...recoveryKeys,"release_url","sha","to"].sort().join())fail();const expected={...before,current_release:next,state:"open",release_task_id:null,release_run_id:null,release_mode:null,history:[...before.history,entry2]};const stable=value=>JSON.stringify(value,(_,item)=>item&&typeof item==="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a.localeCompare(b))):item);if(stable(after)!==stable(expected))fail()}var releaseCyclePath3;var init_commit_policy_closure=__esm({"src/commit-policy-closure.ts"(){"use strict";init_candidate_publisher_recovery();releaseCyclePath3=".agents/config/release-cycle.json"}});import{execFile as execFile13}from"node:child_process";import{promisify as promisify13}from"node:util";function reconciledHistoricalScope(commit,path){return commit==="967ca013240808b727bc7df3fa968213df1d16d8"&&path==="pnpm-workspace.yaml"}async function policyGit(root,...args){return(await exec5("git",["--literal-pathspecs",...args],{cwd:root,encoding:"utf8",windowsHide:true,timeout:15e3,maxBuffer:16*1024*1024})).stdout}function requiresTaskIdentity(path){return!path.startsWith(".agents/records/")&&!path.startsWith(".local/")}function trailers(message2){const result2=new Map;const block2=message2.replace(/\r\n/g,"\n").trimEnd().split(/\n\s*\n/).at(-1)??"";for(const line of block2.split("\n")){const match=/^(ZAIP-[A-Za-z-]+): (\S+)$/.exec(line);if(line.startsWith("ZAIP-")&&(!match||!allowedTrailers.has(match[1]??"")))throw new Error("Unknown or malformed ZAIP trailer");if(!match)continue;const key=match[1];if(result2.has(key))throw new Error(`Duplicate commit trailer: ${key}`);result2.set(key,match[2])}if(message2.split(/\r?\n/).filter(line=>line.startsWith("ZAIP-")).length!==result2.size)throw new Error("ZAIP identity must occur exactly once in the final trailer block");return result2}async function readCanonicalTaskCommit(filesystem,taskId,executionId,agent,administrativeClosure){const layout=await loadWorkspaceLayout(filesystem);const{task}=await new TaskV2Repository(filesystem,layout).read(taskId);const{change}=await new ChangeV2Repository(filesystem,layout).read(task.change_id);const{execution}=await new ExecutionV2Repository(filesystem,layout).read(executionId);if(task.id!==taskId||change.id!==task.change_id||execution.id!==executionId)throw new Error("Commit record ID does not match its requested canonical path");if(task.plan_hash===null)throw new Error("Product commit requires a materialized Task delivery");if(!["executing","verifying","completed"].includes(task.status)){if(!administrativeClosure)throw new Error("Product commit requires a materialized Task delivery");await validateAdministrativeClosure({...administrativeClosure,taskStatus:task.status,changeStatus:change.status,executionStatus:execution.status,changeId:change.id})}if(!change.task_ids.includes(task.id)||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===change.id))throw new Error("Commit Task, Change and delivery Execution are not causally linked");const source=change.source;if(source.type==="task"&&source.task_id!==task.id)throw new Error("Standalone Change belongs to a different Task");const specId=source.type==="task"?null:source.spec_id;let prdId=source.type==="prd"?source.prd_id:null;if(specId!==null){const{spec}=await new DeliverySpecV2Repository(filesystem,layout).read(specId);if(spec.id!==specId)throw new Error("Commit SPEC does not match its canonical path");if(source.type==="prd"&&spec.prd_id!==prdId)throw new Error("SPEC and PRD do not match");prdId=spec.prd_id}if(prdId!==null){const{prd}=await new PrdV2Repository(filesystem,layout).read(prdId);if(prd.id!==prdId)throw new Error("Commit PRD does not match its canonical path")}const identity2={agent,title:task.title,task_id:task.id,change_id:change.id,execution_id:execution.id,prd_id:prdId,spec_id:specId};const recordPaths=[layout.activePath("task",task.id),layout.activePath("change",change.id),layout.activePath("execution",execution.id)];if(specId)recordPaths.push(layout.activePath("spec",specId));if(prdId)recordPaths.push(layout.activePath("prd",prdId));return{identity:identity2,recordPaths,writeScopes:task.write_scopes}}async function validateTaskCommit(input){const paths2=input.paths.filter(requiresTaskIdentity);if(paths2.length===0)return{valid:true,kind:"records-only"};const refs=trailers(input.message);const taskId=refs.get("ZAIP-Task");const executionId=refs.get("ZAIP-Execution");const agent=refs.get("ZAIP-Agent");if(!taskId||!executionId||!["CODEX","CLAUDE"].includes(agent??""))throw new Error("Product commit requires a real Task, Execution and CODEX/CLAUDE agent. Use task commit TASK --run RUN --files PATHS; never select the latest global Task.");const filesystem=input.filesystem??new CommitTreeFileSystem(input.root,input.tree??"");const canonical=await readCanonicalTaskCommit(filesystem,taskId,executionId,agent,{filesystem,git:(...args)=>policyGit(input.root,...args),taskId,executionId,changeId:refs.get("ZAIP-Change")??"",productCommit:refs.get("ZAIP-Product-Commit"),targetTree:input.tree||"HEAD",paths:paths2,taskStatus:"",changeStatus:"",executionStatus:""});const expected=formatAutonomousTaskCommit(canonical.identity);if(input.message.split(/\r?\n/)[0]!==expected.split("\n")[0])throw new Error(`Commit subject must be: ${expected.split("\n")[0]}`);const expectedRefs=trailers(expected);const productCommit=refs.get("ZAIP-Product-Commit");if(productCommit!==void 0){if(!/^[a-f0-9]{40}$/.test(productCommit))throw new Error("Invalid ZAIP-Product-Commit");const productRefs=trailers(await policyGit(input.root,"show","-s","--format=%B",productCommit));if(productRefs.get("ZAIP-Task")!==taskId||productRefs.get("ZAIP-Change")!==refs.get("ZAIP-Change")||productRefs.get("ZAIP-Execution")!==executionId)throw new Error("Product commit belongs to a different Task")}for(const key of["ZAIP-Task","ZAIP-Change","ZAIP-Execution","ZAIP-Agent","ZAIP-PRD","ZAIP-SPEC"])if(refs.get(key)!==expectedRefs.get(key))throw new Error(`Commit trailer does not match canonical records: ${key}`);const outside2=paths2.filter(path=>!canonical.writeScopes.some(scope=>workspaceScopeMatches(scope,path))&&!reconciledHistoricalScope(input.tree,path));if(outside2.length)throw new Error(`Commit paths outside Task write scopes: ${outside2.join(", ")}`);return{valid:true,kind:"task",task_id:canonical.identity.task_id}}async function stagedCommitPaths(root){return(await policyGit(root,"diff","--cached","--name-only","--no-renames","-z","--")).split("\0").filter(Boolean)}async function validateCommitRange(root,base,head){const resolveCommit=async ref=>(await policyGit(root,"rev-parse","--verify",`${ref}^{commit}`)).trim();const[start,end]=await Promise.all([resolveCommit(base),resolveCommit(head)]);await policyGit(root,"merge-base","--is-ancestor",start,end);const commits=(await policyGit(root,"rev-list","--reverse",`${start}..${end}`)).trim().split("\n").filter(Boolean);for(const commit of commits){const parents=(await policyGit(root,"show","-s","--format=%P",commit)).trim().split(" ").filter(Boolean);const paths2=parents.length?(await policyGit(root,"diff","--name-only","--no-renames","-z",parents[0],commit,"--")).split("\0").filter(Boolean):(await policyGit(root,"diff-tree","--root","--no-commit-id","--name-only","--no-renames","-r","-z",commit)).split("\0").filter(Boolean);await validateTaskCommit({root,tree:commit,paths:paths2,message:await policyGit(root,"show","-s","--format=%B",commit)})}return{valid:true,checked:commits.length}}var exec5,allowedTrailers,CommitTreeFileSystem;var init_commit_policy=__esm({"src/commit-policy.ts"(){"use strict";init_src();init_src6();init_src7();init_commit_policy_closure();init_lifecycle_gate_helpers();exec5=promisify13(execFile13);allowedTrailers=new Set(["ZAIP-Task","ZAIP-Change","ZAIP-Execution","ZAIP-Agent","ZAIP-PRD","ZAIP-SPEC","ZAIP-Product-Commit"]);CommitTreeFileSystem=class extends WorkspaceFileSystem{constructor(root,tree){super(root);this.tree=tree}tree;async readText(path){this.resolve(path);return policyGit(this.root,"show",`${this.tree}:${path}`)}async exists(path){this.resolve(path);try{await policyGit(this.root,"cat-file","-e",`${this.tree}:${path}`);return true}catch{return false}}}}});function assertChangedFilesInScope(task,changedFiles){const outside2=changedFilesOutsideTaskScopes(task.write_scopes,changedFiles);if(outside2.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside write scopes: ${outside2.join(", ")}`)}}async function assertChangedFilesInScopeOrCausalRecords(task,changedFiles,filesystem,executionId,repositories){const cycle=await readReleaseCycle(filesystem);if(cycle&&task.target_release==null&&!repositories)throw new LifecycleGateError("Task release inheritance requires canonical repositories");const target=cycle&&repositories?await effectiveTaskRelease(task,repositories):task.target_release;if(target&&cycle&&target!==cycle.current_release){const raw=JSON.parse(await filesystem.readText(".agents/config/release-cycle.json"));if(raw.history?.at(-1)?.from!==target||changedFiles.some(path=>path!==".agents/config/release-cycle.json"&&!path.startsWith(".agents/records/")&&!path.startsWith(".local/")))throw new LifecycleGateError("Post-publication closure permits only exact cycle and metadata files")}const isLifecycleRecord=path=>path.startsWith(".agents/records/")||path.startsWith(".agents/data/");const outside2=changedFilesOutsideTaskScopes(task.write_scopes,changedFiles);const outsideProduct=outside2.filter(path=>!isLifecycleRecord(path));if(outsideProduct.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside write scopes: ${outsideProduct.join(", ")}`)}const records=outside2.filter(isLifecycleRecord);if(records.length===0)return;let causalRecords;try{const canonical=await readCanonicalTaskCommit(filesystem,task.id,executionId,"CODEX");causalRecords=new Set(canonical.recordPaths)}catch{throw new LifecycleGateError(`Task ${task.id} has no validated causal commit records`)}const unrelated=records.filter(path=>!causalRecords.has(path));if(unrelated.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside causal records: ${unrelated.join(", ")}`)}}var init_lifecycle_changed_files=__esm({"src/lifecycle-changed-files.ts"(){"use strict";init_commit_policy();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();init_release_cycle()}});import{execFile as execFile14}from"node:child_process";import{promisify as promisify14}from"node:util";async function assertGitDeliveryReady(root){const git8=async(...args)=>(await exec6("git",args,{cwd:root,windowsHide:true,encoding:"utf8",timeout:1e4})).stdout.trim();await git8("--version").catch(()=>{throw new Error("git-unavailable: Install Git before starting delivery.")});const inside2=await git8("rev-parse","--is-inside-work-tree").catch(()=>"");if(inside2!=="true")throw new Error("git-repository-required: Initialize or open the selected Git repository before starting delivery.");const head=await git8("rev-parse","--verify","HEAD").catch(()=>"");if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(head))throw new Error("git-head-required: Create the initial repository commit before starting delivery.");await git8("var","GIT_AUTHOR_IDENT").catch(()=>{throw new Error("git-identity-required: Configure your Git commit name and email before starting delivery.")})}var exec6;var init_git_delivery_preflight=__esm({"src/git-delivery-preflight.ts"(){"use strict";exec6=promisify14(execFile14)}});async function preflightTaskMacroParents(change,repositories,filesystem,layout){const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){const{spec}=await repositories.specs.read(specId);if(!["ready","blocked","active"].includes(spec.status))throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`);await assertSpecImplementationMatchesProject(spec.implementation,filesystem,layout)}if(prdId!==null){const{prd}=await repositories.prds.read(prdId);if(!["ready","blocked","active"].includes(prd.status))throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}}async function activateTaskMacroParents(change,repositories){const specs=[];const prds=[];const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){let{spec}=await repositories.specs.read(specId);if(spec.status==="ready"||spec.status==="blocked"){spec=await repositories.specs.transition(spec.id,"active")}else if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`)}specs.push(spec)}if(prdId!==null){let{prd}=await repositories.prds.read(prdId);if(prd.status==="ready"||prd.status==="blocked"){prd=await repositories.prds.transition(prd.id,"active")}else if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}prds.push(prd)}return{specs,prds}}var init_lifecycle_parent_activation_v2=__esm({"src/lifecycle-parent-activation-v2.ts"(){"use strict";init_src6();init_lifecycle_assurance_v2()}});async function startTaskWithSnapshot(id,mode,repositories,filesystem,layout,requireGit,postPublication){if(postPublication===void 0)await assertTaskStartRelease(filesystem,repositories,id);else{if(mode!=="resume")throw new LifecycleGateError("Post-publication closure only resumes a blocked Task");await assertPostPublicationTaskStartRelease(filesystem,repositories,id,postPublication)}const{task}=await repositories.tasks.read(id);if(requireGit)await assertGitDeliveryReady(filesystem.root);const expected=mode==="resume"?"blocked":mode==="rework"?"failed":"planned";if(task.status!==expected){throw new LifecycleGateError(`Task ${id} must be ${expected} before ${mode}`)}for(const dependencyId of task.depends_on){const dependency=await repositories.tasks.read(dependencyId).catch(()=>null);if(dependency===null||dependency.task.status!=="completed"){throw new LifecycleGateError(`Task dependency is not completed: ${dependencyId}`)}}let{change}=await repositories.changes.read(task.change_id);let execution=await executionForTask(task,repositories);if(!(mode!=="start"&&["blocked","failed"].includes(change.status))&&change.status!=="executing")throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`);if(!(mode!=="start"&&["blocked","failed"].includes(execution.status))&&execution.status!=="running")throw new LifecycleGateError(`Execution ${execution.id} must be running before Task start`);await preflightTaskMacroParents(change,repositories,filesystem,layout);if(mode!=="start"){if(change.status==="blocked"||change.status==="failed"){change=await repositories.changes.transition(change.id,"executing")}if(execution.status==="blocked"||execution.status==="failed"){execution=await repositories.executions.transition(execution.id,"running")}}if(change.status!=="executing"){throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`)}if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${execution.id} must be running before Task start`)}const parents=await activateTaskMacroParents(change,repositories);const activeTask=await repositories.tasks.transition(id,"executing");return{task:activeTask,changes:[change],execution,...parents}}var init_lifecycle_task_start=__esm({"src/lifecycle-task-start.ts"(){"use strict";init_git_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_parent_activation_v2();init_lifecycle_run_attribution();init_release_cycle()}});function assertAllTerminal(entities,label,terminal="completed"){const incomplete2=entities.filter(entity=>entity.status!==terminal);if(incomplete2.length>0){throw new LifecycleGateError(`${label} is not ${terminal}: ${incomplete2.map(formatLifecycleState).join(", ")}`)}}var init_lifecycle_terminal_state=__esm({"src/lifecycle-terminal-state.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function cancelLifecycleDescendants(repositories,assertCancellable,specs,changes,originExecutions,parent,completedRunId){const changeIds=new Set(changes.map(change=>change.id));const allExecutions=await repositories.executions.list();const executions=[...new Map([...originExecutions,...allExecutions.filter(execution=>execution.dag.nodes.some(node=>changeIds.has(node.change_id)))].map(execution=>[execution.id,execution])).values()];const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const tasks=(await repositories.tasks.list()).filter(task=>taskIds.has(task.id));const reason=`Cancelled automatically because ${parent} was cancelled.`;assertCancellable(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)),["draft","planned","executing","verifying","blocked"],"Task");assertCancellable(changes.filter(change=>!isTerminalLifecycleStatus(change.status)),["draft","planned","executing","verifying","blocked"],"Change");assertCancellable(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)),["planned","running","paused","verifying","blocked"],"Execution");assertCancellable(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)),["draft","ready","active","blocked"],"SPEC");const cancelledTasks=await Promise.all(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)).map(task=>repositories.tasks.transition(task.id,"cancelled",{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:completedRunId})));const cancelledChanges=await Promise.all(changes.filter(change=>!isTerminalLifecycleStatus(change.status)).map(change=>repositories.changes.transition(change.id,"cancelled",reason)));const cancelledExecutions=await Promise.all(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)).map(execution=>repositories.executions.transition(execution.id,"cancelled",reason)));const cancelledSpecs=await Promise.all(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)).map(spec=>repositories.specs.transition(spec.id,"cancelled")));return{specs:cancelledSpecs,tasks:cancelledTasks,changes:cancelledChanges,executions:cancelledExecutions}}var init_lifecycle_v2_cancellation=__esm({"src/lifecycle-v2-cancellation.ts"(){"use strict";init_lifecycle_gate_helpers()}});async function parentalProofTasks(specId,executionId,composition){const[changes,executions]=await Promise.all([composition.changes.list(),composition.executions.list()]);const changeIds=new Set(changes.filter(change=>(change.source.type==="spec"||change.source.type==="prd")&&change.source.spec_id===specId).map(change=>change.id));const related=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===specId||execution.dag.nodes.some(node=>changeIds.has(node.change_id)));const parental=related.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===specId);if(parental.length!==1||parental[0]?.id!==executionId)throw new LifecycleGateError("SPEC requires one exact parental Execution before Gui");const nodes=related.flatMap(execution=>execution.dag.nodes);const tasks=await Promise.all([...new Set(nodes.map(node=>node.task_id))].map(async id=>{const{task}=await composition.tasks.read(id);if(task.status!=="completed"||!changeIds.has(task.change_id)||nodes.some(node=>node.task_id===id&&node.change_id!==task.change_id))throw new LifecycleGateError("Parental Task ownership or completion mismatch");return task}));return{tasks,causal_execution_ids:new Set(related.map(execution=>execution.id))}}async function assertParentDeliveryPreflight(input){const{expected,validations,evidences}=await deliveryCandidateProofs(input.filesystem,input.layout,input.tasks,input.assurance,input.composition);const tasksById=new Map(input.tasks.map(task=>[task.id,task]));if([...validations,...evidences].some(artifact=>{const owner=tasksById.get(artifact.task_id);return!owner||artifact.change_id!==owner.change_id||!input.causal_execution_ids.has(artifact.execution_id)||artifact.acceptance_ids.some(id=>!owner.acceptance_ids.includes(id))}))throw new LifecycleGateError(`SPEC ${input.spec_id} Task proof ownership or AC mismatch`);if(input.selected_evidence_ids){const bundle=await readParentAssuranceBundle(input.filesystem,input.layout,input.spec_id,input.execution_id);if(input.selected_evidence_ids.some(id=>!bundle.evidences.some(evidence=>evidence.id===id&&evidence.status==="passed"&&evidence.commit_sha===expected)))throw new LifecycleGateError("Parental selected Evidence differs from the final candidate")}await assertParentalSpecAssurance({filesystem:input.filesystem,layout:input.layout,repositories:input.repositories,spec_id:input.spec_id,execution_id:input.execution_id,acceptance_ids:input.acceptance_ids,candidate_commit:expected,task_validations:validations,task_evidences:evidences})}var init_parent_delivery_preflight=__esm({"src/parent-delivery-preflight.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_v2_delivery_assurance();init_parent_assurance_v1()}});var LifecycleV2Gate;var init_lifecycle_v2=__esm({"src/lifecycle-v2.ts"(){"use strict";init_src6();init_editorial_delivery_assurance();init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_lifecycle_run_attribution();init_lifecycle_task_start();init_lifecycle_terminal_state();init_lifecycle_v2_cancellation();init_lifecycle_v2_delivery_assurance();init_parent_assurance_v1();init_parent_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();LifecycleV2Gate=class{constructor(filesystem,layout,repositories){this.filesystem=filesystem;this.layout=layout;this.repositories=repositories;if(layout.version===1)throw new TypeError("LifecycleV2Gate requires a modern layout")}filesystem;layout;repositories;async completeTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be verifying before completion`)}try{return await this.completeVerifyingTask(task,result2)}catch(error51){if(error51 instanceof LifecycleGateError){await this.repositories.tasks.transition(id,"executing")}throw error51}}async verifyTask(id,evidenceIds){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before verification`)}const execution=await executionForTask(task,this.repositories);const result2=taskAssurancePreflightResult(evidenceIds);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){await assertTaskAssurancePreflightV1({filesystem:this.filesystem,layout:this.layout,task,evidence_ids:result2.evidence_ids,config:assurance})}return task.status==="verifying"?task:this.repositories.tasks.transition(id,"verifying")}async completeVerifyingTask(task,result2){for(const dependencyId of task.depends_on){const{task:dependency}=await this.repositories.tasks.read(dependencyId).catch(()=>{throw new LifecycleGateError(`Task dependency does not resolve: ${dependencyId}`)});if(dependency.status!=="completed"){throw new LifecycleGateError(`Task dependency must be completed: ${dependencyId} is ${dependency.status}`)}}const{change}=await this.repositories.changes.read(task.change_id);if(!change.task_ids.includes(task.id)){throw new LifecycleGateError(`Change ${change.id} does not own Task ${task.id}`)}if(!new Set(["executing","verifying"]).has(change.status)){throw new LifecycleGateError(`Change ${change.id} is not executing or verifying`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Completed Task ${task.id} requires a completed Run`)}const run=await readRequiredRun(this.repositories,result2.completed_run_id);const canonicalExecution=await executionForTask(task,this.repositories);if(!new Set(["running","verifying"]).has(canonicalExecution.status)){throw new LifecycleGateError(`Execution ${canonicalExecution.id} is not running or verifying`)}const execution=await executionForCompletionRun(task,canonicalExecution,run,this.repositories);if(!new Set(["running","verifying"]).has(execution.status)){throw new LifecycleGateError(`Execution ${execution.id} is not running or verifying`)}assertCompletedRunAttribution(run,task,execution.id);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){const bundle=await readAssuranceBundle(this.filesystem,this.layout,[task],result2.evidence_ids);const effectiveAssurance=effectiveTaskAssurance(task,assurance);const historicalBoundary=effectiveAssurance.require_final_commit?await historicalPublishedBoundaryForTask(task,run,(await Promise.resolve().then(()=>(init_v2_router(),v2_router_exports))).createV2Composition(this.filesystem,this.layout)):null;assertHistoricalRelayChangedFiles(historicalBoundary,result2.changed_files);const expectedCommit=effectiveAssurance.require_final_commit?await requireFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,result2.changed_files,historicalBoundary??void 0):null;if(expectedCommit!==null){await assertEditorialCandidateDiff({root:this.filesystem.root,task,signals:effectiveTaskRiskSignals(task),commit:expectedCommit,changedFiles:result2.changed_files})}assertTaskAssuranceV1({config:assurance,task,risk:task.risk,risk_signals:effectiveTaskRiskSignals(task),write_scopes:task.write_scopes,acceptance_ids:task.acceptance_ids,validations:bundle.validations,evidences:bundle.evidences,verifier:verifierFrom(bundle.validations,run.run.agent,run.run.run_id),mutation:mutationFrom(bundle.metadata,task.id),mutation_acceptance_ids:await readTaskMutationApplicabilityV1(this.filesystem,task,execution.id),rollback_evidence_id:bundle.evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expectedCommit})}await assertChangedFilesInScopeOrCausalRecords(task,result2.changed_files,this.filesystem,execution.id,this.repositories);return this.repositories.tasks.transition(task.id,"completed",result2)}async startTask(id,mode="start"){return(await this.startTaskWithSnapshot(id,mode)).task}async startTaskWithSnapshot(id,mode="start",postPublication){return startTaskWithSnapshot(id,mode,this.repositories,this.filesystem,this.layout,this.assuranceConfig()?.require_final_commit===true,postPublication)}async failTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before failure`)}if(result2.completed_run_id===null)throw new LifecycleGateError(`Failed Task ${id} requires a failed Run`);const execution=await executionForTask(task,this.repositories);const run=await readRequiredRun(this.repositories,result2.completed_run_id);if(run.finished?.status!=="failed")throw new LifecycleGateError(`Run ${result2.completed_run_id} must be failed`);assertRunAttribution(run,task,execution.id);await assertChangedFilesInScopeOrCausalRecords(task,result2.changed_files,this.filesystem,execution.id,this.repositories);return this.repositories.tasks.transition(id,"failed",result2)}async verifyChange(id){const{change}=await this.repositories.changes.read(id);if(change.status!=="executing")throw new LifecycleGateError(`Change ${id} must be executing before verification`);const tasks=await tasksForChange(this.repositories,change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}return this.repositories.changes.transition(id,"verifying")}async completeChange(id,result2){const{change}=await this.repositories.changes.read(id);if(change.status!=="verifying"){throw new LifecycleGateError(`Change ${id} must be verifying before completion`)}const tasks=await tasksForChange(this.repositories,change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}const covered=new Set(tasks.flatMap(task=>task.acceptance_ids));const missing=change.acceptance_ids.filter(acceptanceId=>!covered.has(acceptanceId));if(missing.length>0){throw new LifecycleGateError(`Change ${id} has uncovered Acceptance Criteria: ${missing.join(", ")}`)}for(const task of tasks){if(task.result===null)throw new LifecycleGateError(`Task ${task.id} has no terminal result`);await this.assertEvidenceCoverage(task,task.result)}return this.repositories.changes.transition(id,"completed",result2)}async verifyExecution(id){const{execution}=await this.repositories.executions.read(id);if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${id} must be running before verification`)}await assertExecutionDescendantsComplete(this.repositories,execution.id,execution.dag.nodes);return this.repositories.executions.transition(id,"verifying")}async completeExecution(id,result2){const{execution}=await this.repositories.executions.read(id);let completedExecution;if(execution.status==="verifying"){await assertExecutionDescendantsComplete(this.repositories,execution.id,execution.dag.nodes);const changeIds=[...new Set(execution.dag.nodes.map(node=>node.change_id))];for(const changeId of changeIds){const{change}=await this.repositories.changes.read(changeId);if(change.status!=="completed"){throw new LifecycleGateError(`Execution Change must be completed: ${formatLifecycleState(change)}`)}}completedExecution=await this.repositories.executions.transition(id,"completed",result2)}else if(execution.status==="completed"){completedExecution=execution}else{throw new LifecycleGateError(`Execution ${id} must be verifying before completion`)}await this.reconcileCompletedExecutionOrigin(completedExecution);return completedExecution}async reconcileCompletedExecutionOrigin(execution){if(execution.origin.type==="prd"){const{prd}=await this.repositories.prds.read(execution.origin.prd_id);if(prd.status==="active")await this.deliverPrd(prd.id);else if(prd.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable PRD ${prd.id}: ${prd.status}`)}}else if(execution.origin.type==="spec"){const{spec}=await this.repositories.specs.read(execution.origin.spec_id);if(spec.status==="active")await this.deliverSpec(spec.id);else if(spec.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable SPEC ${spec.id}: ${spec.status}`)}}}async deliverSpec(id){const{spec}=await this.repositories.specs.read(id);if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${id} must be active before delivery`)}const[changes,executions]=await Promise.all([this.repositories.changes.list(),this.repositories.executions.list()]);const descendants=changes.filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const descendantChangeIds=new Set(descendants.map(change=>change.id));const relatedExecutions=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id||execution.dag.nodes.some(node=>descendantChangeIds.has(node.change_id)));if(descendants.length===0||relatedExecutions.length===0){throw new LifecycleGateError(`SPEC ${id} has no materialized Change and Execution`)}assertAllTerminal(descendants,"SPEC Change");assertAllTerminal(relatedExecutions,"SPEC Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(relatedExecutions.flatMap(item=>item.dag.nodes.map(node=>node.task_id)));const parentalExecutions=relatedExecutions.filter(item=>item.origin.type==="spec"&&item.origin.spec_id===id);if(parentalExecutions.length!==1)throw new LifecycleGateError(`SPEC ${id} requires one exact parental Execution`);const parentalExecution=parentalExecutions[0];if(!parentalExecution)throw new LifecycleGateError(`SPEC ${id} parental Execution missing`);if(tasks.some(task=>!descendantChangeIds.has(task.change_id)))throw new LifecycleGateError(`SPEC ${id} Task proof has foreign Change ownership`);const parentBundle=await readParentAssuranceBundle(this.filesystem,this.layout,id,parentalExecution.id);if(parentBundle.validations.length===0&&parentBundle.evidences.length===0){await this.assertDeliveryAssurance("spec",spec.acceptance_ids,[],tasks,assurance)}else{await assertParentDeliveryPreflight({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories,spec_id:id,execution_id:parentalExecution.id,acceptance_ids:spec.acceptance_ids,tasks,assurance,causal_execution_ids:new Set(relatedExecutions.map(item=>item.id))})}}return this.repositories.specs.transition(id,"delivered")}async deliverPrd(id){const{prd}=await this.repositories.prds.read(id);if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${id} must be active before delivery`)}const[specs,changes,executions]=await Promise.all([this.repositories.specs.list(),this.repositories.changes.list(),this.repositories.executions.list()]);const executionId=prd.prepared_plan?.execution_id??prd.plan_ref?.execution_id;if(executionId===void 0){throw new LifecycleGateError(`PRD ${id} has no prepared plan or plan reference`)}const selectedExecution=executions.find(execution=>execution.id===executionId&&execution.origin.type==="prd"&&execution.origin.prd_id===id);if(selectedExecution===void 0){throw new LifecycleGateError(`PRD ${id} plan Execution does not resolve: ${executionId}`)}const selectedChangeIds=new Set(selectedExecution.dag.nodes.map(node=>node.change_id));const directChanges=changes.filter(change=>selectedChangeIds.has(change.id));const selectedSpecIds=prd.prepared_plan===null?new Set(directChanges.flatMap(change=>change.source.type==="prd"&&change.source.prd_id===id?[change.source.spec_id]:[])):new Set(specIdsForPrdPlanV2(prd.prepared_plan,id));const childSpecs=specs.filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));const directExecutions=[selectedExecution];if(childSpecs.length===0){throw new LifecycleGateError(`PRD ${id} requires at least one SPEC`)}for(const spec of childSpecs){if(spec.status==="active")await this.deliverSpec(spec.id)}const refreshedSpecs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));assertAllTerminal(refreshedSpecs,"PRD SPEC","delivered");assertAllTerminal(directChanges,"PRD Change");assertAllTerminal(directExecutions,"PRD Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(selectedExecution.dag.nodes.map(node=>node.task_id));const metadata3=prd;await this.assertDeliveryAssurance("prd",metadata3.acceptance_ids??refreshedSpecs.flatMap(spec=>spec.acceptance_ids),prd.outcome_ids,tasks,assurance)}return this.repositories.prds.transition(id,"delivered")}async cancelTask(id,summary,completedRunId=null){const{task}=await this.repositories.tasks.read(id);this.assertCancellable([task],["draft","planned","executing","verifying","blocked"],"Task");const changes=(await this.repositories.changes.list()).filter(change=>change.id===task.change_id&&change.source.type==="task"&&change.source.task_id===id);const executions=(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="task"&&execution.origin.task_id===id||execution.dag.nodes.some(node=>node.task_id===id&&node.change_id===task.change_id));const cascade=await this.cancelDescendants([],changes,executions,`Task ${id} was cancelled: ${summary}`,completedRunId);const cancelledTask=(await this.repositories.tasks.read(id)).task;return{task:cancelledTask,cascade}}async cancelPrd(id){const{prd}=await this.repositories.prds.read(id);this.assertCancellable([prd],["draft","ready","active","blocked"],"PRD");const specs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id);const specIds=new Set(specs.map(spec=>spec.id));const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="prd"&&change.source.prd_id===id||change.source.type==="spec"&&specIds.has(change.source.spec_id));const cascade=await this.cancelDescendants(specs,changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="prd"&&execution.origin.prd_id===id||execution.origin.type==="spec"&&specIds.has(execution.origin.spec_id)),`PRD ${id}`);const cancelledPrd=prd.status==="cancelled"?prd:await this.repositories.prds.transition(id,"cancelled");return{prd:cancelledPrd,cascade}}async cancelSpec(id){const{spec}=await this.repositories.specs.read(id);this.assertCancellable([spec],["draft","ready","active","blocked"],"SPEC");const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const cascade=await this.cancelDescendants([],changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id),`SPEC ${id}`);const cancelledSpec=spec.status==="cancelled"?spec:await this.repositories.specs.transition(id,"cancelled");return{spec:cancelledSpec,cascade}}async cancelDescendants(specs,changes,originExecutions,parent,completedRunId=null){return cancelLifecycleDescendants(this.repositories,(entities,cancellable,entity)=>this.assertCancellable(entities,cancellable,entity),specs,changes,originExecutions,parent,completedRunId)}assertCancellable(entities,cancellable,entity){for(const item of entities){if(item.status==="cancelled"||cancellable.includes(item.status))continue;throw new LifecycleGateError(`${entity} ${item.id} cannot be cancelled from status ${item.status}`)}}assuranceConfig(){const config2=this.layout.projectConfig?.assurance;return config2?.version===1?config2:null}async readTasks(ids2){return Promise.all([...new Set(ids2)].map(async id=>(await this.repositories.tasks.read(id)).task))}async assertDeliveryAssurance(origin,acceptanceIds,outcomeIds,tasks,config2){const{bundle,expected,validations,evidences}=await deliveryCandidateProofs(this.filesystem,this.layout,tasks,config2);const verifier=await this.deliveryVerifier(validations,tasks);assertDeliveryAssuranceV1({origin,config:config2,acceptance_ids:acceptanceIds,outcome_ids:outcomeIds,validations,evidences,verifier,mutation:deliveryMutationFrom(bundle.metadata,tasks.map(task=>task.id)),rollback_evidence_id:evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expected})}async deliveryVerifier(validations,tasks){for(const review of validations.filter(item=>isReviewKind(item.kind))){const task=tasks.find(item=>item.id===review.task_id);if(task?.result?.completed_run_id==null)continue;const run=await readRequiredRun(this.repositories,task.result.completed_run_id);const approval=verifierFrom([review],run.run.agent,run.run.run_id);if(approval!==null)return approval}return null}async assertEvidenceCoverage(task,result2){await assertTaskEvidenceCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2)}async assertSixStageCoverage(task,result2,executionId,enforceLegacyRiskCounts=true){await assertSixStageDeliveryCoverage(this.filesystem,this.layout,this.repositories,task,result2,executionId,enforceLegacyRiskCounts,this.assuranceConfig())}}}});async function hasPassedParentEvidenceSelection(root,ids2,composition){const r=root.run;if(r.task_id!==null||r.change_id!==null||r.parent_run_id!==null||r.spec_id===null||r.execution_id===null||r.entrypoint!=="spec"||r.agent!=="agent-orchestrator"||!composition.executions||ids2.length<3||new Set(ids2).size!==ids2.length)return false;try{const{execution}=await composition.executions.read(r.execution_id);const ownEvidenceBlock=execution.status==="blocked"&&execution.status_reason===`Finalization barrier evidence_missing; resume after passed typed Evidence linked to the same Task, Change, Execution, and Run (Run ${r.run_id}).`;if(execution.origin.type!=="spec"||execution.origin.spec_id!==r.spec_id||!["verifying","completed"].includes(execution.status)&&!ownEvidenceBlock||execution.dag.nodes.length===0)return false;const tasks=await Promise.all(execution.dag.nodes.map(async({task_id})=>(await composition.tasks.read(task_id)).task));if(tasks.some(task=>task.status!=="completed"))return false;const bundle=await readParentAssuranceBundle(composition.filesystem,composition.layout,r.spec_id,r.execution_id);const selected=ids2.map(id=>bundle.evidences.find(e=>e.id===id));if(selected.some(e=>e?.status!=="passed"||e.run_id!==r.run_id)||new Set(selected.map(e=>e?.commit_sha)).size!==1)return false;const validations=selected.flatMap(e=>e?.validation_artifact_ids.map(id=>bundle.validations.find(v=>v.id===id)));const sha5=selected[0]?.commit_sha;if(validations.some(v=>v?.status!=="passed"||v.commit_sha!==sha5))return false;const runs=await readAssuranceRunAncestry(composition.runs,[r.run_id,...validations.flatMap(v=>v?[v.run_id]:[])]);const descendants=descendantRuns(r.run_id,[...runs.values()]);const reviewRuns=new Set;for(const v of validations){if(v?.kind==="integration"){if(v?.run_id!==r.run_id||v?.candidate_execution?.exit_code!==0||v?.candidate_execution.commit_sha!==sha5)return false}else if(v?.kind==="spec_review"||v?.kind==="quality_review"){const reviewer=descendants.find(child=>child.run.run_id===v?.run_id);if(reviewer?.status!=="completed"||reviewer.run.agent!=="agent-reviewer"||reviewer.run.run_purpose!=="review"||reviewer.run.task_id!==null||reviewer.run.change_id!==null||reviewer.run.execution_id!==r.execution_id||reviewer.run.spec_id!==r.spec_id)return false;reviewRuns.add(reviewer.run.run_id)}}return reviewRuns.size>=2&&["integration","spec_review","quality_review"].every(kind=>validations.some(v=>v?.kind===kind))}catch{return false}}var init_run_parent_evidence_selection=__esm({"src/run-parent-evidence-selection.ts"(){"use strict";init_assurance_run_ancestry();init_parent_assurance_v1();init_run_hierarchy()}});async function hasPassedTypedEvidenceForRun(run,evidenceIds,composition,candidates=[]){if(run.run.execution_kind!=="delivery")return true;if(run.run.execution_id===null||evidenceIds.length===0){return false}if(isParentalRelayShape(run)&&"decisions"in composition){const proof=await authenticatedParentalRelay(run,composition,run.finished===null);return proof!==null&&evidenceIds.length===proof.parentEvidenceIds.length&&evidenceIds.every(id=>proof.parentEvidenceIds.includes(id))}if(await hasPassedParentEvidenceSelection(run,evidenceIds,composition))return true;const tasks=await evidenceTasks(run,composition);if(tasks.length===0)return false;const requested=new Set(evidenceIds);const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,tasks,[...requested]);const historical=await authenticatedHistoricalEvidence(run,composition);const eligible=await Promise.all(bundle.evidences.map(async evidence=>{const task=tasks.find(candidate=>evidence.task_id===candidate.id&&evidence.change_id===candidate.change_id);return requested.has(evidence.id)&&evidence.status==="passed"&&task!==void 0&&evidence.execution_id===run.run.execution_id&&(await completedEvidenceRun(evidence.run_id,run,task,composition,candidates)||historical.has(evidence.id))}));return bundle.evidences.length===requested.size&&eligible.every(Boolean)&&(run.run.task_id===null||sharesCandidate(bundle.evidences))}async function passedTypedEvidenceIdsForRun(run,composition,candidates=[]){if(run.run.execution_kind!=="delivery"||run.run.execution_id===null){return[]}if(isParentalRelayShape(run)){return(await authenticatedParentalRelay(run,composition,run.finished===null))?.parentEvidenceIds??[]}const tasks=await evidenceTasks(run,composition);if(tasks.length===0)return[];const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,tasks);const historical=await authenticatedHistoricalEvidence(run,composition);const eligible=await Promise.all(bundle.evidences.map(async evidence=>{const task=tasks.find(candidate=>evidence.task_id===candidate.id&&evidence.change_id===candidate.change_id);return evidence.status==="passed"&&task!==void 0&&evidence.execution_id===run.run.execution_id&&(await completedEvidenceRun(evidence.run_id,run,task,composition,candidates)||historical.has(evidence.id))?evidence.id:null}));return eligible.filter(id=>id!==null).sort()}async function authenticatedHistoricalEvidence(run,composition){if(run.run.task_id===null||!("decisions"in composition)||!("changes"in composition)||!("specs"in composition)||!("executions"in composition))return new Set;try{if(run.run.parent_run_id===null){const{taskFirstPublishedBoundary:taskFirstPublishedBoundary2}=await Promise.resolve().then(()=>(init_post_publication_task_first(),post_publication_task_first_exports));return new Set((await taskFirstPublishedBoundary2(run,composition))?.evidence_ids??[])}const{historicalRelayEvidenceIds:historicalRelayEvidenceIds3}=await Promise.resolve().then(()=>(init_post_publication_relay(),post_publication_relay_exports));return await historicalRelayEvidenceIds3(run,composition)}catch{return new Set}}async function evidenceTasks(run,composition){if(run.run.task_id!==null)return[(await composition.tasks.read(run.run.task_id)).task];if(run.run.execution_id===null||run.run.spec_id===null&&run.run.prd_id===null)return[];if(composition.executions===void 0)return[];const execution=(await composition.executions.read(run.run.execution_id)).execution;const scopeMatches3=run.run.prd_id!==null?execution.origin.type==="prd"&&execution.origin.prd_id===run.run.prd_id:execution.origin.type==="spec"&&execution.origin.spec_id===run.run.spec_id;if(!["verifying","completed"].includes(execution.status)||!scopeMatches3)return[];const tasks=await Promise.all(execution.dag.nodes.map(async node=>(await composition.tasks.read(node.task_id)).task));return tasks.every(task=>task.status==="completed")?tasks:[]}async function completedEvidenceRun(id,root,task,composition,candidates){if(root.run.task_id===null&&(task.status!=="completed"||task.result?.completed_run_id!==id)){return false}try{const run=await composition.runs.read(id);return(id===root.run.run_id||run.status==="completed")&&run.run.execution_id===root.run.execution_id&&run.run.task_id===task.id&&run.run.change_id===task.change_id&&run.run.conversation_id===root.run.conversation_id&&(root.run.task_id===null||belongsToRoot(id,root.run.run_id,candidates.length?candidates:[...(await readAssuranceRunAncestry(composition.runs,[id])).values()]))}catch{return false}}function belongsToRoot(evidenceRunId,rootRunId,candidates){return evidenceRunId===rootRunId||descendantRuns(rootRunId,candidates).some(candidate=>candidate.run.run_id===evidenceRunId)}function sharesCandidate(evidences){const identities=new Set(evidences.map(evidence=>evidence.commit_sha));if(identities.size>1)return false;return identities.has(null)?evidences.length===1:true}var init_run_finalization_evidence_v2=__esm({"src/run-finalization-evidence-v2.ts"(){"use strict";init_assurance_run_ancestry();init_lifecycle_assurance_v2();init_post_publication_parental();init_run_hierarchy();init_run_parent_evidence_selection()}});async function recoverOwnCompletionGateTask(current,task,composition){const reason=task.status_reason;const runId=current.run.run_id;const executionId=current.run.execution_id;if(task.status!=="blocked"||typeof reason!=="string"||typeof runId!=="string"||typeof executionId!=="string"||current.run.task_id!==task.id||current.run.change_id!==task.change_id||!isOwnCompletionGateBlock(reason,runId)){throw new Error(`Task ${task.id} is not blocked by the current Run completion gate`)}const[persistedRun,persistedTask,change,execution]=await Promise.all([composition.runs.read(runId),composition.tasks.read(task.id),composition.changes.read(task.change_id),composition.executions.read(executionId)]);if(persistedRun.status!=="completed"||persistedRun.finished===null||persistedRun.finalization_decision?.outcome!=="completed"||persistedRun.run.run_id!==runId||persistedRun.run.task_id!==task.id||persistedRun.run.change_id!==task.change_id||persistedRun.run.execution_id!==executionId||persistedTask.task.id!==task.id||persistedTask.task.change_id!==task.change_id||persistedTask.task.status!=="blocked"||persistedTask.task.status_reason!==reason||change.change.id!==task.change_id||change.change.status!=="blocked"||change.change.status_reason!==reason||execution.execution.id!==executionId||execution.execution.status!=="blocked"||execution.execution.status_reason!==reason){throw new Error(`Task ${task.id} completion gate graph does not match Run ${runId}`)}await composition.tasks.recoverOwnCompletionGateBlock(task.id,{runId,executionId,reason})}var init_completion_gate_recovery=__esm({"src/completion-gate-recovery.ts"(){"use strict";init_src7()}});async function assessRunLifecycleClosure(current,composition,candidateRuns){const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyClosure(current.run.run_id)}if(isParentalRelayShape(current))await authenticatedParentalRelay(current,composition);const subjects=(await Promise.all(current.run.entrypoint==="task"?[subject("task",current.run.task_id,composition,role,current)]:[subject("spec",current.run.spec_id,composition,role,current),subject("prd",current.run.prd_id,composition,role,current)])).filter(item=>item!==null);void candidateRuns;const openSubjectIds=subjects.filter(item=>!item.settled).map(item=>item.id);const status=subjects.length===0?"not_applicable":openSubjectIds.length===0?"closed":"action_required";return{status,run_id:current.run.run_id,continuation_run_id:null,subjects,open_subject_ids:openSubjectIds,default_inconclusive_outcome:"blocked",allowed_terminal_outcomes:["completed","blocked","failed","cancelled"],guidance:status==="action_required"?"Start an attributed continuation Run or settle every related work item; use blocked by default, failed only for an execution-preventing error, and cancelled only after an explicit user cancellation.":"Run lifecycle closure is satisfied."}}async function subject(kind,id,composition,role,current){if(id===null)return null;try{const status=kind==="task"?(await composition.tasks.read(id)).task.status:kind==="spec"?(await composition.specs.read(id)).spec.status:(await composition.prds.read(id)).prd.status;return{kind,id,status,settled:isSettled(kind,status,role,current)}}catch{return{kind,id,status:"missing",settled:false}}}function isSettled(kind,status,role,current){if(kind==="task")return["completed","blocked","failed","cancelled"].includes(status);if(role==="orchestrator"&&current.finished?.status==="completed")return status!=="missing";return["delivered","blocked","failed","cancelled"].includes(status)}function emptyClosure(runId){return{status:"not_applicable",run_id:runId,continuation_run_id:null,subjects:[],open_subject_ids:[],default_inconclusive_outcome:"blocked",allowed_terminal_outcomes:["completed","blocked","failed","cancelled"],guidance:"Run lifecycle closure is satisfied."}}var init_run_lifecycle_closure=__esm({"src/run-lifecycle-closure.ts"(){"use strict";init_src5();init_task_attempt();init_post_publication_parental()}});function emptyResult(runId,status){return{run_id:runId,status,outcome:null,fallback_from:null,error:null,tasks:[],changes:[],executions:[],specs:[],prds:[]}}var init_run_lifecycle_result=__esm({"src/run-lifecycle-result.ts"(){"use strict"}});function lifecycleReconciliationOutcome(value){if(value===void 0)return void 0;if(value==="completed"||value==="blocked"||value==="failed"||value==="cancelled"){return value}throw new Error("--task-outcome must be completed, blocked, failed, or cancelled")}function lifecycleOutcomeOption(options){if(options["owner-outcome"]!==void 0){throw new Error("Legacy lifecycle outcome option is no longer supported; use --task-outcome")}return lifecycleReconciliationOutcome(options["task-outcome"])}var init_run_lifecycle_outcome=__esm({"src/run-lifecycle-outcome.ts"(){"use strict"}});function isTaskAttemptRun(current){if(isNativeTaskAttempt(current))return true;return effectiveRunV2Role(current.run)==="orchestrator"&&current.run.parent_run_id===null&&(current.run.entrypoint==="task"||current.run.work_type==="rework"&&current.run.task_id!==null)}async function reconcileFinishedRunLifecycle(current,composition,lifecycle,options={}){if(current.finished===null)throw new Error(`Run is still running: ${current.run.run_id}`);const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyResult(current.run.run_id,"not_applicable")}if(isParentalRelayShape(current)){const state=await composition.executions.read(current.run.execution_id);await authenticatedParentalRelay(current,composition,state.execution.status==="running")}if(current.run.execution_id!==null){const execution=await composition.executions.read(current.run.execution_id).catch(()=>null);if(execution?.execution.kind==="interaction"){return emptyResult(current.run.run_id,"not_applicable")}}if(options.defer===true){throw new Error(`Orchestrator Run closure cannot be deferred for Run ${current.run.run_id}`)}const closure=await assessRunLifecycleClosure(current,composition,options.candidateRuns);if(closure.status==="not_applicable")return emptyResult(current.run.run_id,"not_applicable");const catalog=options.catalog??await loadCatalog(composition);const graph=relatedGraph(current,catalog);const requested=resolveOutcome(current,graph.tasks,options.requestedOutcome,options.forceRequestedOutcome);if(requested==="completed"){try{const resumable=await resumeOwnCompletionGateBlocks(current,graph,composition,lifecycle,options.candidateRuns);const completed=await completeGraph(current,resumable,composition,lifecycle,options);return{...completed,status:"closed",outcome:"completed"}}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);const blocked2=await settleGraph(current,await refreshGraph(graph,composition),composition,lifecycle,"blocked",`Completion gates did not close Run ${current.run.run_id}: ${message2}`);return{...blocked2,status:"closed",outcome:"blocked",fallback_from:"completed",error:message2}}}const settled=await settleGraph(current,graph,composition,lifecycle,requested,options.summary===void 0?defaultReason(current.run.run_id,requested):`${options.summary} (Run ${current.run.run_id}).`);return{...settled,status:"closed",outcome:requested}}async function snapshotRunLifecycle(current,composition,catalog){const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyResult(current.run.run_id,"not_applicable")}if(isParentalRelayShape(current))await authenticatedParentalRelay(current,composition);const graph=relatedGraph(current,catalog??await loadCatalog(composition));return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}async function resumeOwnCompletionGateBlocks(current,graph,composition,lifecycle,candidateRuns){if(current.finalization_decision?.outcome!=="completed")return graph;const eligiblePredecessors=new Set(await completionGatePredecessorIds(current,graph,candidateRuns??await composition.runs.list()));const runId=current.run.run_id;if(typeof runId!=="string")return graph;eligiblePredecessors.add(runId);const isOwnBlock=reason=>reason!==null&&[...eligiblePredecessors].some(runId2=>isOwnCompletionGateBlock(reason,runId2));for(const task of graph.tasks){const latest=(await composition.tasks.read(task.id)).task;if(latest.status==="blocked"&&isOwnBlock(latest.status_reason??null)){if(typeof latest.status_reason==="string"&&isOwnCompletionGateBlock(latest.status_reason,runId)){await recoverOwnCompletionGateTask(current,latest,composition)}else{await lifecycle.startTask(task.id,"resume")}}}for(const change of graph.changes){const latest=(await composition.changes.read(change.id)).change;if(latest.status==="blocked"&&isOwnBlock(latest.status_reason??null)){await composition.changes.transition(latest.id,"executing")}}for(const execution of graph.executions){const latest=(await composition.executions.read(execution.id)).execution;if(latest.status!=="blocked"||!isOwnBlock(latest.status_reason??null))continue;if(latest.dag.nodes.length===0){await composition.executions.transition(latest.id,"cancelled","Superseded empty continuation intake")}else{await composition.executions.transition(latest.id,"running")}}return refreshGraph(graph,composition)}async function completionGatePredecessorIds(current,graph,candidates){const threadId=current.run.client_thread_id;if(current.run.task_id===null||current.run.change_id===null||current.run.execution_id===null){return new Set}const executionIds=new Set(graph.executions.map(execution=>execution.id));const eligible=new Set;for(const predecessor of candidates){if(predecessor.run.run_id===current.run.run_id||predecessor.finished===null||!isTaskAttemptRun(predecessor)||predecessor.run.occurred_at>=current.run.occurred_at||threadId!==null&&predecessor.run.client_thread_id!==threadId||predecessor.run.task_id!==current.run.task_id||predecessor.run.change_id!==current.run.change_id||predecessor.run.execution_id===null||!executionIds.has(predecessor.run.execution_id)){continue}eligible.add(predecessor.run.run_id)}return eligible}function resolveOutcome(current,tasks,requested,forceRequested){if(forceRequested===true&&requested!==void 0)return requested;if(current.finished?.status==="failed")return"failed";if(current.finished?.status==="cancelled")return"cancelled";if(requested!==void 0)return requested;if(!isTaskAttemptRun(current))return"completed";const terminal=tasks.find(task=>["completed","blocked","failed","cancelled"].includes(task.status))?.status;return terminal==="completed"||terminal==="blocked"||terminal==="failed"||terminal==="cancelled"?terminal:"blocked"}async function completeGraph(current,graph,composition,lifecycle,options){const summary=options.summary??`Run ${current.run.run_id} completed.`;const result2={summary,changed_files:[...options.changedFiles??[]],evidence_ids:[...options.evidenceIds??[]],completed_run_id:current.run.run_id};const taskAttempt=isTaskAttemptRun(current);if(taskAttempt){for(const task of graph.tasks){let latest=(await composition.tasks.read(task.id)).task;if(latest.status==="executing")latest=await composition.tasks.transition(task.id,"verifying");if(latest.status==="verifying")await lifecycle.completeTask(task.id,result2)}}else{const unfinished=graph.tasks.filter(task=>task.status!=="completed");if(unfinished.some(task=>["draft","planned","executing","verifying"].includes(task.status))){await keepMacroParentsActive(graph,composition);return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}if(unfinished.length>0){throw new Error(`Macro Tasks did not complete: ${unfinished.map(task=>task.id).join(", ")}`)}}for(const change of graph.changes){let latest=(await composition.changes.read(change.id)).change;const relatedTasks=await Promise.all(latest.task_ids.map(async id=>(await composition.tasks.read(id)).task));if(relatedTasks.some(task=>task.status!=="completed"))continue;if(latest.status==="executing"){await lifecycle.verifyChange(change.id);latest=(await composition.changes.read(change.id)).change}if(latest.status==="verifying")await lifecycle.completeChange(change.id,summary)}for(const execution of graph.executions){let latest=(await composition.executions.read(execution.id)).execution;if(isNativeTaskAttempt(current)&&latest.origin.type!=="task")continue;const relatedTasks=await Promise.all(latest.dag.nodes.map(async node=>(await composition.tasks.read(node.task_id)).task));if(relatedTasks.some(task=>task.status!=="completed"))continue;if(latest.status==="planned"&&latest.dag.nodes.length===0){await composition.executions.transition(execution.id,"cancelled","Superseded empty continuation intake");continue}if(latest.status==="planned"){latest=await composition.executions.transition(execution.id,"running")}if(latest.status==="blocked"&&taskAttempt){latest=await composition.executions.transition(execution.id,"running")}if(latest.status==="running"){await lifecycle.verifyExecution(execution.id);latest=(await composition.executions.read(execution.id)).execution}if(latest.status==="verifying")await lifecycle.completeExecution(execution.id,summary)}if(!taskAttempt){for(const spec of graph.specs.filter(item=>graph.directSpecIds.has(item.id))){if((await composition.specs.read(spec.id)).spec.status==="active")await lifecycle.deliverSpec(spec.id)}for(const prd of graph.prds.filter(item=>graph.directPrdIds.has(item.id))){if((await composition.prds.read(prd.id)).prd.status==="active")await lifecycle.deliverPrd(prd.id)}}else{await aggregateMacroAncestors(graph,composition)}const refreshed=await refreshGraph(graph,composition);assertGraphCompleted(refreshed,taskAttempt);return currentGraphResult(current.run.run_id,refreshed)}function assertGraphCompleted(graph,taskAttempt){const incomplete2=[...graph.tasks.filter(item=>item.status!=="completed").map(item=>item.id),...!taskAttempt?graph.changes.filter(item=>item.status!=="completed").map(item=>item.id):[],...graph.executions.filter(item=>item.status!=="completed"&&!(taskAttempt&&item.origin.type!=="task")&&!(item.dag.nodes.length===0&&item.status==="cancelled")).map(item=>item.id),...graph.specs.filter(item=>!taskAttempt&&graph.directSpecIds.has(item.id)&&item.status!=="delivered").map(item=>item.id),...graph.prds.filter(item=>!taskAttempt&&graph.directPrdIds.has(item.id)&&item.status!=="delivered").map(item=>item.id)];if(incomplete2.length>0){throw new Error(`Completion left related work non-terminal: ${incomplete2.join(", ")}`)}}async function settleGraph(current,graph,composition,lifecycle,outcome,reason){const clock=new SystemClock;const taskAttempt=isTaskAttemptRun(current);const taskResult=outcome==="blocked"?null:{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:current.run.run_id};for(const task of graph.tasks){const latest=(await composition.tasks.read(task.id)).task;if((taskAttempt?SETTLEABLE_TASK:new Set(["executing","verifying"])).has(latest.status)){await composition.tasks.transition(task.id,outcome,taskResult,clock,reason)}}const standalone=graph.executions.some(execution=>execution.origin.type==="task");for(const change of taskAttempt&&!standalone?[]:graph.changes){const latest=(await composition.changes.read(change.id)).change;if((taskAttempt?SETTLEABLE_CHANGE:new Set(["executing","verifying"])).has(latest.status)){await composition.changes.transition(change.id,outcome,outcome==="blocked"?null:reason,clock,reason)}}for(const execution of taskAttempt&&!standalone?[]:graph.executions){const latest=(await composition.executions.read(execution.id)).execution;if((taskAttempt?SETTLEABLE_EXECUTION:new Set(["running","paused","verifying"])).has(latest.status)){await composition.executions.transition(execution.id,outcome,outcome==="blocked"?null:reason,clock,reason)}}const specIdsToSettle=new Set(taskAttempt?[]:specIdsForLifecycleSettlement(graph.specs.map(item=>item.id),graph.directSpecIds,graph.directPrdIds));const specsToSettle=graph.specs.filter(item=>specIdsToSettle.has(item.id));for(const spec of specsToSettle){if(outcome==="cancelled"&&graph.directPrdIds.size>0)break;if((await composition.specs.read(spec.id)).spec.status==="active"){if(outcome==="cancelled")await lifecycle.cancelSpec(spec.id);else await composition.specs.transition(spec.id,outcome,reason)}}for(const prd of graph.prds.filter(item=>!taskAttempt&&graph.directPrdIds.has(item.id))){if((await composition.prds.read(prd.id)).prd.status==="active"){if(outcome==="cancelled")await lifecycle.cancelPrd(prd.id);else await composition.prds.transition(prd.id,outcome,reason)}}if(taskAttempt&&!standalone)await aggregateMacroAncestors(graph,composition);return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}function relatedGraph(current,catalog){const{tasks,changes,executions,specs,prds}=catalog;const taskIds=new Set(current.run.task_id===null?[]:[current.run.task_id]);const changeIds=new Set(current.run.change_id===null?[]:[current.run.change_id]);const executionIds=new Set(current.run.execution_id===null?[]:[current.run.execution_id]);const specIds=new Set(current.run.spec_id===null?[]:[current.run.spec_id]);const prdIds=new Set(current.run.prd_id===null?[]:[current.run.prd_id]);const taskAttempt=isTaskAttemptRun(current);if(!taskAttempt){for(const spec of specs)if(spec.prd_id!==null&&prdIds.has(spec.prd_id))specIds.add(spec.id)}for(const change of changes){const source=change.source;if(changeIds.has(change.id)||source.type==="task"&&taskIds.has(source.task_id)||!taskAttempt&&source.type==="spec"&&specIds.has(source.spec_id)||!taskAttempt&&source.type==="prd"&&prdIds.has(source.prd_id))changeIds.add(change.id)}for(const task of tasks){if(taskIds.has(task.id)||!taskAttempt&&changeIds.has(task.change_id)){taskIds.add(task.id);const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id;if(canonicalExecutionId!==void 0&&canonicalExecutionId!==null)executionIds.add(canonicalExecutionId)}}for(const execution of executions){if(executionIds.has(execution.id)||execution.origin.type==="task"&&taskIds.has(execution.origin.task_id)||execution.dag.nodes.some(node=>taskIds.has(node.task_id))){executionIds.add(execution.id)}}return{tasks:tasks.filter(item=>taskIds.has(item.id)),changes:changes.filter(item=>changeIds.has(item.id)),executions:executions.filter(item=>executionIds.has(item.id)),specs:specs.filter(item=>specIds.has(item.id)),prds:prds.filter(item=>prdIds.has(item.id)),directSpecIds:new Set(current.run.spec_id===null?[]:[current.run.spec_id]),directPrdIds:new Set(current.run.prd_id===null?[]:[current.run.prd_id])}}async function keepMacroParentsActive(graph,composition){for(const spec of graph.specs){const latest=(await composition.specs.read(spec.id)).spec;if(latest.status==="ready"||latest.status==="blocked"){await composition.specs.transition(latest.id,"active")}}for(const prd of graph.prds){const latest=(await composition.prds.read(prd.id)).prd;if(latest.status==="ready"||latest.status==="blocked"){await composition.prds.transition(latest.id,"active")}}}async function aggregateMacroAncestors(graph,composition){await keepMacroParentsActive(graph,composition)}async function loadCatalog(composition){const[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);return{tasks,changes,executions,specs,prds}}async function refreshGraph(graph,composition){const[tasks,changes,executions,specs,prds]=await Promise.all([Promise.all(graph.tasks.map(async item=>(await composition.tasks.read(item.id)).task)),Promise.all(graph.changes.map(async item=>(await composition.changes.read(item.id)).change)),Promise.all(graph.executions.map(async item=>(await composition.executions.read(item.id)).execution)),Promise.all(graph.specs.map(async item=>(await composition.specs.read(item.id)).spec)),Promise.all(graph.prds.map(async item=>(await composition.prds.read(item.id)).prd))]);return{...graph,tasks,changes,executions,specs,prds}}function currentGraphResult(runId,graph){return{run_id:runId,status:"closed",outcome:null,fallback_from:null,error:null,tasks:graph.tasks,changes:graph.changes,executions:graph.executions,specs:graph.specs,prds:graph.prds}}function specIdsForLifecycleSettlement(specIds,directSpecIds,directPrdIds){return directPrdIds.size>0?[...specIds]:specIds.filter(id=>directSpecIds.has(id))}function defaultReason(runId,outcome){if(outcome==="failed")return`Run ${runId} failed and closed its operational lifecycle.`;if(outcome==="cancelled")return`Run ${runId} was explicitly cancelled.`;return`Run ${runId} completed without sufficient closure gates and has no concrete continuation.`}var SETTLEABLE_TASK,SETTLEABLE_CHANGE,SETTLEABLE_EXECUTION;var init_run_lifecycle_reconciliation=__esm({"src/run-lifecycle-reconciliation.ts"(){"use strict";init_src();init_src5();init_src7();init_completion_gate_recovery();init_task_attempt();init_post_publication_parental();init_run_lifecycle_closure();init_run_lifecycle_result();init_run_lifecycle_outcome();SETTLEABLE_TASK=new Set(["draft","planned","executing","verifying"]);SETTLEABLE_CHANGE=new Set(["draft","planned","executing","verifying"]);SETTLEABLE_EXECUTION=new Set(["planned","running","paused","verifying"])}});async function reconcileTerminalOrchestratorRoot(root,candidates,composition,lifecycle){const decision=root.finalization_decision??null;const evidenceIds=decision===null?await passedTypedEvidenceIdsForRun(root,composition,candidates):decision.evidence_ids;const evidenceSatisfied=await hasPassedTypedEvidenceForRun(root,evidenceIds,composition,candidates);const barrier=assessRunFinalizationBarrier(root,candidates,evidenceSatisfied);const blockReason=finalizationBarrierBlockReason(barrier);const decisionEligible=decision!==null&&(decision.outcome!=="completed"||barrier.satisfied);const reconciliation=await reconcileFinishedRunLifecycle(root,composition,lifecycle,{requestedOutcome:decisionEligible?decision.outcome:"blocked",forceRequestedOutcome:!decisionEligible,summary:decisionEligible?decision.summary:blockReason??"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.",evidenceIds:decision?.evidence_ids??evidenceIds,changedFiles:decision?.changed_files??[],candidateRuns:candidates});return{status:"closed",parent_run_id:root.run.run_id,finalization_barrier:barrier,finalization_decision:decision,reconciliation}}var init_orchestrator_stop_reconciliation=__esm({"src/orchestrator-stop-reconciliation.ts"(){"use strict";init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_lifecycle_reconciliation()}});function runClosureView(repository2,current,prospective){const next=prospective.records.at(-1);if(current.finished!==null||prospective.run.run_id!==current.run.run_id||JSON.stringify(prospective.run)!==JSON.stringify(current.run)||prospective.records.length!==current.records.length+1||next?.type!=="run.finished"||next.sequence!==current.records.length+1||current.records.some((record3,index)=>JSON.stringify(record3)!==JSON.stringify(prospective.records[index])))throw new Error("Closure view requires the exact next terminal event for the locked Run");return new Proxy(repository2,{get(target,key){if(["start","appendRecord"].includes(String(key)))return()=>{throw new Error("Closure view cannot persist Run events")};if(key==="read")return id=>id===current.run.run_id?Promise.resolve(prospective):target.read(id);if(key==="list")return async()=>(await target.list()).map(run=>run.run.run_id===current.run.run_id?prospective:run);const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value}})}var init_run_closure_view=__esm({"src/run-closure-view.ts"(){"use strict"}});function assurancePlanning(task,effective){const{contract}=effective;return{schema_version:1,task_id:task.id,phase:"planning",approved:false,requirement_ids:task.requirement_ids,acceptance:task.acceptance_ids.map(acceptance_id=>({acceptance_id,scenario_required:true,expected_outcome_required:true,environment_required:true,modalities:contract.required_modalities,individual_evidence:contract.evidence_per_acceptance})),minimum_validations:contract.minimum_validation_artifacts,independent_review:contract.requires_independent_verifier,mutation_kill_ratio:contract.requires_mutation_discrimination?contract.minimum_mutation_kill_ratio:null,rollback:contract.requires_rollback,final_commit:effective.require_final_commit||contract.requires_final_commit_evidence,before_publication:`task assurance ${task.id} --preflight --evidence EVD-ID --json`,guidance:"Define scenarios and evidence ownership now; collect candidate-bound proof before publication. This plan does not approve evidence or authorize closure."}}var init_assurance_planning=__esm({"src/assurance-planning.ts"(){"use strict"}});function createTaskFirstPreparedPlan(input){const{task}=input;return createPreparedPlanV2({revision:1,source:{type:"task",task_id:task.id},execution_id:input.executionId,prepared_at:input.preparedAt,policy:input.policy,blueprints:{changes:[{key:"task-first-change",id:task.change_id,title:task.title,short_name:task.short_name,risk:task.risk,source:{type:"task",task_id:task.id},requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,requirement_impact:taskFirstRequirementImpact(input)}],tasks:[{key:"task-first",id:task.id,change_id:task.change_id,title:task.title,short_name:task.short_name,objective:task.objective,risk:task.risk,priority:task.priority,owner:task.owner,requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,write_scopes:task.write_scopes,...input.modelSignals===void 0?task.model_profile===void 0?{}:{model_profile:task.model_profile}:{model_signals:input.modelSignals}}]},dag:{nodes:[{task_id:task.id,depends_on:task.depends_on}]}})}function taskModelSignalsOption(raw){if(raw===void 0)return void 0;try{return taskModelSignalsSchema.parse(JSON.parse(raw))}catch{throw new UsageError("--model-signals requires valid structured TaskModelSignals JSON")}}async function runPlanV2Command(action,parsed,filesystem,layout){if(action==="acceptance"){requireOptions(parsed.options,["input"]);return evaluateAcceptanceInput(filesystem,parsed.options.input)}if(action==="build"){requireOptions(parsed.options,["draft"]);const input=JSON.parse(await filesystem.readText(parsed.options.draft));if(input.acceptance_contract!==void 0&&parsed.options.acceptance!==void 0){throw new UsageError("Specify acceptance inside the draft or with --acceptance, not both")}const acceptance=parsed.options.acceptance===void 0?input.acceptance_contract:JSON.parse(await filesystem.readText(parsed.options.acceptance));const complete={...input,...acceptance===void 0?{}:{acceptance_contract:acceptance}};if(complete.source.type!=="task"&&acceptance!==void 0)assertDeclaredLocalHost(acceptance);const plan=complete.source.type==="task"?createPreparedPlanV2(complete):createAdoptedPreparedPlanV2(complete);await assertPreparedPlanReferences(filesystem,plan);const outputPath=parsed.options.output;if(outputPath!==void 0){await filesystem.writeTextAtomic(outputPath,`${JSON.stringify(plan,null,2)}
3591
+ `);try{return await operation()}finally{await this.filesystem.removeFile(LOCK_PATH)}}catch(error51){if(!isNodeError8(error51)||error51.code!=="EEXIST")throw error51;if(await this.removeStaleLock())continue;await delay4(Math.min(100,10+attempt*2))}}throw new Error("Lifecycle manifest is busy; retry the operation")}async removeStaleLock(){try{const lock2=JSON.parse(await this.filesystem.readText(LOCK_PATH));if(typeof lock2.pid!=="number"||!isProcessAlive2(lock2.pid)){await this.filesystem.removeFile(LOCK_PATH);return true}}catch(error51){if(isNodeError8(error51)&&error51.code==="ENOENT")return true;return false}return false}}}});async function validateAdministrativeClosure(input){const fail=()=>{throw new Error("Terminal Task permits only a verified administrative release-cycle closure")};if(input.paths.length!==1||input.paths[0]!==releaseCyclePath3||!input.productCommit||!/^[a-f0-9]{40}$/.test(input.productCommit)||!["blocked","failed","cancelled"].includes(input.taskStatus)||input.changeStatus!==input.taskStatus||input.executionStatus!==input.taskStatus)fail();const product=input.productCommit;await input.git("merge-base","--is-ancestor",product,input.targetTree);const before=JSON.parse(await input.git("show",`${product}:${releaseCyclePath3}`));const after=JSON.parse(await input.filesystem.readText(releaseCyclePath3));if(before.state!=="frozen"||before.release_task_id!==input.taskId||typeof before.release_run_id!=="string"||!before.release_run_id.startsWith("RUN-")||!/^\d+\.\d+$/.test(before.current_release)||!Array.isArray(before.history)||!Array.isArray(after.history))fail();const tag=(await input.git("rev-parse","--verify",`refs/tags/v${before.current_release}^{commit}`)).trim();if(tag!==product)fail();const[major,minor]=before.current_release.split(".").map(Number);const next=`${major}.${minor+1}`;const entry2=after.history.at(-1);const recoveryDeclared=entry2&&Object.keys(entry2).some(key=>key.startsWith("publisher_recovery_"));const recoveryKeys=recoveryDeclared?["publisher_recovery_ci_run_id","publisher_recovery_paths","publisher_recovery_sha"]:[];if(recoveryDeclared){if(typeof entry2.publisher_recovery_sha!=="string"||!await validatePublisherRecoveryBoundary(input.git,entry2,entry2.publisher_recovery_sha,product))fail();await input.git("merge-base","--is-ancestor",entry2.publisher_recovery_sha,input.targetTree)}if(!entry2||entry2.from!==before.current_release||entry2.to!==next||entry2.sha!==product||!Number.isSafeInteger(entry2.ci_run_id)||entry2.ci_run_id<=0||entry2.release_url!==`https://github.com/zaip-ai/zaip-aios/releases/tag/v${before.current_release}`||typeof entry2.advanced_at!=="string"||!Number.isFinite(Date.parse(entry2.advanced_at))||Object.keys(entry2).sort().join()!==["advanced_at","ci_run_id","from",...recoveryKeys,"release_url","sha","to"].sort().join())fail();const expected={...before,current_release:next,state:"open",release_task_id:null,release_run_id:null,release_mode:null,history:[...before.history,entry2]};const stable=value=>JSON.stringify(value,(_,item)=>item&&typeof item==="object"&&!Array.isArray(item)?Object.fromEntries(Object.entries(item).sort(([a],[b])=>a.localeCompare(b))):item);if(stable(after)!==stable(expected))fail()}var releaseCyclePath3;var init_commit_policy_closure=__esm({"src/commit-policy-closure.ts"(){"use strict";init_candidate_publisher_recovery();releaseCyclePath3=".agents/config/release-cycle.json"}});import{execFile as execFile13}from"node:child_process";import{promisify as promisify13}from"node:util";function reconciledHistoricalScope(commit,path){return commit==="967ca013240808b727bc7df3fa968213df1d16d8"&&path==="pnpm-workspace.yaml"}async function policyGit(root,...args){return(await exec5("git",["--literal-pathspecs",...args],{cwd:root,encoding:"utf8",windowsHide:true,timeout:15e3,maxBuffer:16*1024*1024})).stdout}function requiresTaskIdentity(path){return!path.startsWith(".agents/records/")&&!path.startsWith(".local/")}function trailers(message2){const result2=new Map;const block2=message2.replace(/\r\n/g,"\n").trimEnd().split(/\n\s*\n/).at(-1)??"";for(const line of block2.split("\n")){const match=/^(ZAIP-[A-Za-z-]+): (\S+)$/.exec(line);if(line.startsWith("ZAIP-")&&(!match||!allowedTrailers.has(match[1]??"")))throw new Error("Unknown or malformed ZAIP trailer");if(!match)continue;const key=match[1];if(result2.has(key))throw new Error(`Duplicate commit trailer: ${key}`);result2.set(key,match[2])}if(message2.split(/\r?\n/).filter(line=>line.startsWith("ZAIP-")).length!==result2.size)throw new Error("ZAIP identity must occur exactly once in the final trailer block");return result2}async function readCanonicalTaskCommit(filesystem,taskId,executionId,agent,administrativeClosure){const layout=await loadWorkspaceLayout(filesystem);const{task}=await new TaskV2Repository(filesystem,layout).read(taskId);const{change}=await new ChangeV2Repository(filesystem,layout).read(task.change_id);const{execution}=await new ExecutionV2Repository(filesystem,layout).read(executionId);if(task.id!==taskId||change.id!==task.change_id||execution.id!==executionId)throw new Error("Commit record ID does not match its requested canonical path");if(task.plan_hash===null)throw new Error("Product commit requires a materialized Task delivery");if(!["executing","verifying","completed"].includes(task.status)){if(!administrativeClosure)throw new Error("Product commit requires a materialized Task delivery");await validateAdministrativeClosure({...administrativeClosure,taskStatus:task.status,changeStatus:change.status,executionStatus:execution.status,changeId:change.id})}if(!change.task_ids.includes(task.id)||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===change.id))throw new Error("Commit Task, Change and delivery Execution are not causally linked");const source=change.source;if(source.type==="task"&&source.task_id!==task.id)throw new Error("Standalone Change belongs to a different Task");const specId=source.type==="task"?null:source.spec_id;let prdId=source.type==="prd"?source.prd_id:null;if(specId!==null){const{spec}=await new DeliverySpecV2Repository(filesystem,layout).read(specId);if(spec.id!==specId)throw new Error("Commit SPEC does not match its canonical path");if(source.type==="prd"&&spec.prd_id!==prdId)throw new Error("SPEC and PRD do not match");prdId=spec.prd_id}if(prdId!==null){const{prd}=await new PrdV2Repository(filesystem,layout).read(prdId);if(prd.id!==prdId)throw new Error("Commit PRD does not match its canonical path")}const identity2={agent,title:task.title,task_id:task.id,change_id:change.id,execution_id:execution.id,prd_id:prdId,spec_id:specId};const recordPaths=[layout.activePath("task",task.id),layout.activePath("change",change.id),layout.activePath("execution",execution.id)];if(specId)recordPaths.push(layout.activePath("spec",specId));if(prdId)recordPaths.push(layout.activePath("prd",prdId));return{identity:identity2,recordPaths,writeScopes:task.write_scopes}}async function validateTaskCommit(input){const paths2=input.paths.filter(requiresTaskIdentity);if(paths2.length===0)return{valid:true,kind:"records-only"};const refs=trailers(input.message);const taskId=refs.get("ZAIP-Task");const executionId=refs.get("ZAIP-Execution");const agent=refs.get("ZAIP-Agent");if(!taskId||!executionId||!["CODEX","CLAUDE"].includes(agent??""))throw new Error("Product commit requires a real Task, Execution and CODEX/CLAUDE agent. Use task commit TASK --run RUN --files PATHS; never select the latest global Task.");const filesystem=input.filesystem??new CommitTreeFileSystem(input.root,input.tree??"");const canonical=await readCanonicalTaskCommit(filesystem,taskId,executionId,agent,{filesystem,git:(...args)=>policyGit(input.root,...args),taskId,executionId,changeId:refs.get("ZAIP-Change")??"",productCommit:refs.get("ZAIP-Product-Commit"),targetTree:input.tree||"HEAD",paths:paths2,taskStatus:"",changeStatus:"",executionStatus:""});const expected=formatAutonomousTaskCommit(canonical.identity);if(input.message.split(/\r?\n/)[0]!==expected.split("\n")[0])throw new Error(`Commit subject must be: ${expected.split("\n")[0]}`);const expectedRefs=trailers(expected);const productCommit=refs.get("ZAIP-Product-Commit");if(productCommit!==void 0){if(!/^[a-f0-9]{40}$/.test(productCommit))throw new Error("Invalid ZAIP-Product-Commit");const productRefs=trailers(await policyGit(input.root,"show","-s","--format=%B",productCommit));if(productRefs.get("ZAIP-Task")!==taskId||productRefs.get("ZAIP-Change")!==refs.get("ZAIP-Change")||productRefs.get("ZAIP-Execution")!==executionId)throw new Error("Product commit belongs to a different Task")}for(const key of["ZAIP-Task","ZAIP-Change","ZAIP-Execution","ZAIP-Agent","ZAIP-PRD","ZAIP-SPEC"])if(refs.get(key)!==expectedRefs.get(key))throw new Error(`Commit trailer does not match canonical records: ${key}`);const outside2=paths2.filter(path=>!canonical.writeScopes.some(scope=>workspaceScopeMatches(scope,path))&&!reconciledHistoricalScope(input.tree,path));if(outside2.length)throw new Error(`Commit paths outside Task write scopes: ${outside2.join(", ")}`);return{valid:true,kind:"task",task_id:canonical.identity.task_id}}async function stagedCommitPaths(root){return(await policyGit(root,"diff","--cached","--name-only","--no-renames","-z","--")).split("\0").filter(Boolean)}async function validateCommitRange(root,base,head){const resolveCommit=async ref=>(await policyGit(root,"rev-parse","--verify",`${ref}^{commit}`)).trim();const[start,end]=await Promise.all([resolveCommit(base),resolveCommit(head)]);await policyGit(root,"merge-base","--is-ancestor",start,end);const commits=(await policyGit(root,"rev-list","--reverse",`${start}..${end}`)).trim().split("\n").filter(Boolean);for(const commit of commits){const parents=(await policyGit(root,"show","-s","--format=%P",commit)).trim().split(" ").filter(Boolean);const paths2=parents.length?(await policyGit(root,"diff","--name-only","--no-renames","-z",parents[0],commit,"--")).split("\0").filter(Boolean):(await policyGit(root,"diff-tree","--root","--no-commit-id","--name-only","--no-renames","-r","-z",commit)).split("\0").filter(Boolean);await validateTaskCommit({root,tree:commit,paths:paths2,message:await policyGit(root,"show","-s","--format=%B",commit)})}return{valid:true,checked:commits.length}}var exec5,allowedTrailers,CommitTreeFileSystem;var init_commit_policy=__esm({"src/commit-policy.ts"(){"use strict";init_src();init_src6();init_src7();init_commit_policy_closure();init_lifecycle_gate_helpers();exec5=promisify13(execFile13);allowedTrailers=new Set(["ZAIP-Task","ZAIP-Change","ZAIP-Execution","ZAIP-Agent","ZAIP-PRD","ZAIP-SPEC","ZAIP-Product-Commit"]);CommitTreeFileSystem=class extends WorkspaceFileSystem{constructor(root,tree){super(root);this.tree=tree}tree;async readText(path){this.resolve(path);return policyGit(this.root,"show",`${this.tree}:${path}`)}async exists(path){this.resolve(path);try{await policyGit(this.root,"cat-file","-e",`${this.tree}:${path}`);return true}catch{return false}}}}});function assertChangedFilesInScope(task,changedFiles){const outside2=changedFilesOutsideTaskScopes(task.write_scopes,changedFiles);if(outside2.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside write scopes: ${outside2.join(", ")}`)}}async function assertChangedFilesInScopeOrCausalRecords(task,changedFiles,filesystem,executionId,repositories,historicalBoundary=null){const cycle=await readReleaseCycle(filesystem);if(cycle&&task.target_release==null&&!repositories)throw new LifecycleGateError("Task release inheritance requires canonical repositories");const target=cycle&&repositories?await effectiveTaskRelease(task,repositories):task.target_release;if(target&&cycle&&target!==cycle.current_release){const raw=JSON.parse(await filesystem.readText(".agents/config/release-cycle.json"));const matching=raw.history?.filter(row=>row.from===target)??[];const authenticatedHistory=historicalBoundary?.target_task_id===task.id&&matching.length===1&&matching[0]?.sha===historicalBoundary.published_sha;if(!authenticatedHistory&&raw.history?.at(-1)?.from!==target||changedFiles.some(path=>path!==".agents/config/release-cycle.json"&&!path.startsWith(".agents/records/")&&!path.startsWith(".local/")))throw new LifecycleGateError("Post-publication closure permits only exact cycle and metadata files")}const isLifecycleRecord=path=>path.startsWith(".agents/records/")||path.startsWith(".agents/data/");const outside2=changedFilesOutsideTaskScopes(task.write_scopes,changedFiles);const outsideProduct=outside2.filter(path=>!isLifecycleRecord(path));if(outsideProduct.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside write scopes: ${outsideProduct.join(", ")}`)}const records=outside2.filter(isLifecycleRecord);if(records.length===0)return;let causalRecords;try{const canonical=await readCanonicalTaskCommit(filesystem,task.id,executionId,"CODEX");causalRecords=new Set(canonical.recordPaths)}catch{throw new LifecycleGateError(`Task ${task.id} has no validated causal commit records`)}const unrelated=records.filter(path=>!causalRecords.has(path));if(unrelated.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside causal records: ${unrelated.join(", ")}`)}}var init_lifecycle_changed_files=__esm({"src/lifecycle-changed-files.ts"(){"use strict";init_commit_policy();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();init_release_cycle()}});import{execFile as execFile14}from"node:child_process";import{promisify as promisify14}from"node:util";async function assertGitDeliveryReady(root){const git8=async(...args)=>(await exec6("git",args,{cwd:root,windowsHide:true,encoding:"utf8",timeout:1e4})).stdout.trim();await git8("--version").catch(()=>{throw new Error("git-unavailable: Install Git before starting delivery.")});const inside2=await git8("rev-parse","--is-inside-work-tree").catch(()=>"");if(inside2!=="true")throw new Error("git-repository-required: Initialize or open the selected Git repository before starting delivery.");const head=await git8("rev-parse","--verify","HEAD").catch(()=>"");if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(head))throw new Error("git-head-required: Create the initial repository commit before starting delivery.");await git8("var","GIT_AUTHOR_IDENT").catch(()=>{throw new Error("git-identity-required: Configure your Git commit name and email before starting delivery.")})}var exec6;var init_git_delivery_preflight=__esm({"src/git-delivery-preflight.ts"(){"use strict";exec6=promisify14(execFile14)}});async function preflightTaskMacroParents(change,repositories,filesystem,layout){const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){const{spec}=await repositories.specs.read(specId);if(!["ready","blocked","active"].includes(spec.status))throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`);await assertSpecImplementationMatchesProject(spec.implementation,filesystem,layout)}if(prdId!==null){const{prd}=await repositories.prds.read(prdId);if(!["ready","blocked","active"].includes(prd.status))throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}}async function activateTaskMacroParents(change,repositories){const specs=[];const prds=[];const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){let{spec}=await repositories.specs.read(specId);if(spec.status==="ready"||spec.status==="blocked"){spec=await repositories.specs.transition(spec.id,"active")}else if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`)}specs.push(spec)}if(prdId!==null){let{prd}=await repositories.prds.read(prdId);if(prd.status==="ready"||prd.status==="blocked"){prd=await repositories.prds.transition(prd.id,"active")}else if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}prds.push(prd)}return{specs,prds}}var init_lifecycle_parent_activation_v2=__esm({"src/lifecycle-parent-activation-v2.ts"(){"use strict";init_src6();init_lifecycle_assurance_v2()}});async function startTaskWithSnapshot(id,mode,repositories,filesystem,layout,requireGit,postPublication){if(postPublication===void 0)await assertTaskStartRelease(filesystem,repositories,id);else{if(mode!=="resume")throw new LifecycleGateError("Post-publication closure only resumes a blocked Task");await assertPostPublicationTaskStartRelease(filesystem,repositories,id,postPublication)}const{task}=await repositories.tasks.read(id);if(requireGit)await assertGitDeliveryReady(filesystem.root);const expected=mode==="resume"?"blocked":mode==="rework"?"failed":"planned";if(task.status!==expected){throw new LifecycleGateError(`Task ${id} must be ${expected} before ${mode}`)}for(const dependencyId of task.depends_on){const dependency=await repositories.tasks.read(dependencyId).catch(()=>null);if(dependency===null||dependency.task.status!=="completed"){throw new LifecycleGateError(`Task dependency is not completed: ${dependencyId}`)}}let{change}=await repositories.changes.read(task.change_id);let execution=await executionForTask(task,repositories);if(!(mode!=="start"&&["blocked","failed"].includes(change.status))&&change.status!=="executing")throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`);if(!(mode!=="start"&&["blocked","failed"].includes(execution.status))&&execution.status!=="running")throw new LifecycleGateError(`Execution ${execution.id} must be running before Task start`);await preflightTaskMacroParents(change,repositories,filesystem,layout);if(mode!=="start"){if(change.status==="blocked"||change.status==="failed"){change=await repositories.changes.transition(change.id,"executing")}if(execution.status==="blocked"||execution.status==="failed"){execution=await repositories.executions.transition(execution.id,"running")}}if(change.status!=="executing"){throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`)}if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${execution.id} must be running before Task start`)}const parents=await activateTaskMacroParents(change,repositories);const activeTask=await repositories.tasks.transition(id,"executing");return{task:activeTask,changes:[change],execution,...parents}}var init_lifecycle_task_start=__esm({"src/lifecycle-task-start.ts"(){"use strict";init_git_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_parent_activation_v2();init_lifecycle_run_attribution();init_release_cycle()}});function assertAllTerminal(entities,label,terminal="completed"){const incomplete2=entities.filter(entity=>entity.status!==terminal);if(incomplete2.length>0){throw new LifecycleGateError(`${label} is not ${terminal}: ${incomplete2.map(formatLifecycleState).join(", ")}`)}}var init_lifecycle_terminal_state=__esm({"src/lifecycle-terminal-state.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function cancelLifecycleDescendants(repositories,assertCancellable,specs,changes,originExecutions,parent,completedRunId){const changeIds=new Set(changes.map(change=>change.id));const allExecutions=await repositories.executions.list();const executions=[...new Map([...originExecutions,...allExecutions.filter(execution=>execution.dag.nodes.some(node=>changeIds.has(node.change_id)))].map(execution=>[execution.id,execution])).values()];const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const tasks=(await repositories.tasks.list()).filter(task=>taskIds.has(task.id));const reason=`Cancelled automatically because ${parent} was cancelled.`;assertCancellable(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)),["draft","planned","executing","verifying","blocked"],"Task");assertCancellable(changes.filter(change=>!isTerminalLifecycleStatus(change.status)),["draft","planned","executing","verifying","blocked"],"Change");assertCancellable(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)),["planned","running","paused","verifying","blocked"],"Execution");assertCancellable(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)),["draft","ready","active","blocked"],"SPEC");const cancelledTasks=await Promise.all(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)).map(task=>repositories.tasks.transition(task.id,"cancelled",{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:completedRunId})));const cancelledChanges=await Promise.all(changes.filter(change=>!isTerminalLifecycleStatus(change.status)).map(change=>repositories.changes.transition(change.id,"cancelled",reason)));const cancelledExecutions=await Promise.all(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)).map(execution=>repositories.executions.transition(execution.id,"cancelled",reason)));const cancelledSpecs=await Promise.all(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)).map(spec=>repositories.specs.transition(spec.id,"cancelled")));return{specs:cancelledSpecs,tasks:cancelledTasks,changes:cancelledChanges,executions:cancelledExecutions}}var init_lifecycle_v2_cancellation=__esm({"src/lifecycle-v2-cancellation.ts"(){"use strict";init_lifecycle_gate_helpers()}});async function parentalProofTasks(specId,executionId,composition){const[changes,executions]=await Promise.all([composition.changes.list(),composition.executions.list()]);const changeIds=new Set(changes.filter(change=>(change.source.type==="spec"||change.source.type==="prd")&&change.source.spec_id===specId).map(change=>change.id));const related=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===specId||execution.dag.nodes.some(node=>changeIds.has(node.change_id)));const parental=related.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===specId);if(parental.length!==1||parental[0]?.id!==executionId)throw new LifecycleGateError("SPEC requires one exact parental Execution before Gui");const nodes=related.flatMap(execution=>execution.dag.nodes);const tasks=await Promise.all([...new Set(nodes.map(node=>node.task_id))].map(async id=>{const{task}=await composition.tasks.read(id);if(task.status!=="completed"||!changeIds.has(task.change_id)||nodes.some(node=>node.task_id===id&&node.change_id!==task.change_id))throw new LifecycleGateError("Parental Task ownership or completion mismatch");return task}));return{tasks,causal_execution_ids:new Set(related.map(execution=>execution.id))}}async function assertParentDeliveryPreflight(input){const{expected,validations,evidences}=await deliveryCandidateProofs(input.filesystem,input.layout,input.tasks,input.assurance,input.composition);const tasksById=new Map(input.tasks.map(task=>[task.id,task]));if([...validations,...evidences].some(artifact=>{const owner=tasksById.get(artifact.task_id);return!owner||artifact.change_id!==owner.change_id||!input.causal_execution_ids.has(artifact.execution_id)||artifact.acceptance_ids.some(id=>!owner.acceptance_ids.includes(id))}))throw new LifecycleGateError(`SPEC ${input.spec_id} Task proof ownership or AC mismatch`);if(input.selected_evidence_ids){const bundle=await readParentAssuranceBundle(input.filesystem,input.layout,input.spec_id,input.execution_id);if(input.selected_evidence_ids.some(id=>!bundle.evidences.some(evidence=>evidence.id===id&&evidence.status==="passed"&&evidence.commit_sha===expected)))throw new LifecycleGateError("Parental selected Evidence differs from the final candidate")}await assertParentalSpecAssurance({filesystem:input.filesystem,layout:input.layout,repositories:input.repositories,spec_id:input.spec_id,execution_id:input.execution_id,acceptance_ids:input.acceptance_ids,candidate_commit:expected,task_validations:validations,task_evidences:evidences})}var init_parent_delivery_preflight=__esm({"src/parent-delivery-preflight.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_v2_delivery_assurance();init_parent_assurance_v1()}});var LifecycleV2Gate;var init_lifecycle_v2=__esm({"src/lifecycle-v2.ts"(){"use strict";init_src6();init_editorial_delivery_assurance();init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_lifecycle_run_attribution();init_lifecycle_task_start();init_lifecycle_terminal_state();init_lifecycle_v2_cancellation();init_lifecycle_v2_delivery_assurance();init_parent_assurance_v1();init_parent_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();LifecycleV2Gate=class{constructor(filesystem,layout,repositories){this.filesystem=filesystem;this.layout=layout;this.repositories=repositories;if(layout.version===1)throw new TypeError("LifecycleV2Gate requires a modern layout")}filesystem;layout;repositories;async completeTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be verifying before completion`)}try{return await this.completeVerifyingTask(task,result2)}catch(error51){if(error51 instanceof LifecycleGateError){await this.repositories.tasks.transition(id,"executing")}throw error51}}async verifyTask(id,evidenceIds){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before verification`)}const execution=await executionForTask(task,this.repositories);const result2=taskAssurancePreflightResult(evidenceIds);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){await assertTaskAssurancePreflightV1({filesystem:this.filesystem,layout:this.layout,task,evidence_ids:result2.evidence_ids,config:assurance})}return task.status==="verifying"?task:this.repositories.tasks.transition(id,"verifying")}async completeVerifyingTask(task,result2){for(const dependencyId of task.depends_on){const{task:dependency}=await this.repositories.tasks.read(dependencyId).catch(()=>{throw new LifecycleGateError(`Task dependency does not resolve: ${dependencyId}`)});if(dependency.status!=="completed"){throw new LifecycleGateError(`Task dependency must be completed: ${dependencyId} is ${dependency.status}`)}}const{change}=await this.repositories.changes.read(task.change_id);if(!change.task_ids.includes(task.id)){throw new LifecycleGateError(`Change ${change.id} does not own Task ${task.id}`)}if(!new Set(["executing","verifying"]).has(change.status)){throw new LifecycleGateError(`Change ${change.id} is not executing or verifying`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Completed Task ${task.id} requires a completed Run`)}const run=await readRequiredRun(this.repositories,result2.completed_run_id);const canonicalExecution=await executionForTask(task,this.repositories);if(!new Set(["running","verifying"]).has(canonicalExecution.status)){throw new LifecycleGateError(`Execution ${canonicalExecution.id} is not running or verifying`)}const execution=await executionForCompletionRun(task,canonicalExecution,run,this.repositories);if(!new Set(["running","verifying"]).has(execution.status)){throw new LifecycleGateError(`Execution ${execution.id} is not running or verifying`)}assertCompletedRunAttribution(run,task,execution.id);await this.assertEvidenceCoverage(task,result2);const historicalBoundary=await this.historicalBoundary(task,run);assertHistoricalRelayChangedFiles(historicalBoundary,result2.changed_files);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){const bundle=await readAssuranceBundle(this.filesystem,this.layout,[task],result2.evidence_ids);const effectiveAssurance=effectiveTaskAssurance(task,assurance);const expectedCommit=effectiveAssurance.require_final_commit?await requireFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,result2.changed_files,historicalBoundary??void 0):null;if(expectedCommit!==null){await assertEditorialCandidateDiff({root:this.filesystem.root,task,signals:effectiveTaskRiskSignals(task),commit:expectedCommit,changedFiles:result2.changed_files})}assertTaskAssuranceV1({config:assurance,task,risk:task.risk,risk_signals:effectiveTaskRiskSignals(task),write_scopes:task.write_scopes,acceptance_ids:task.acceptance_ids,validations:bundle.validations,evidences:bundle.evidences,verifier:verifierFrom(bundle.validations,run.run.agent,run.run.run_id),mutation:mutationFrom(bundle.metadata,task.id),mutation_acceptance_ids:await readTaskMutationApplicabilityV1(this.filesystem,task,execution.id),rollback_evidence_id:bundle.evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expectedCommit})}await assertChangedFilesInScopeOrCausalRecords(task,result2.changed_files,this.filesystem,execution.id,this.repositories,historicalBoundary);return this.repositories.tasks.transition(task.id,"completed",result2)}async startTask(id,mode="start"){return(await this.startTaskWithSnapshot(id,mode)).task}async startTaskWithSnapshot(id,mode="start",postPublication){return startTaskWithSnapshot(id,mode,this.repositories,this.filesystem,this.layout,this.assuranceConfig()?.require_final_commit===true,postPublication)}async failTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before failure`)}if(result2.completed_run_id===null)throw new LifecycleGateError(`Failed Task ${id} requires a failed Run`);const execution=await executionForTask(task,this.repositories);const run=await readRequiredRun(this.repositories,result2.completed_run_id);if(run.finished?.status!=="failed")throw new LifecycleGateError(`Run ${result2.completed_run_id} must be failed`);assertRunAttribution(run,task,execution.id);const historicalBoundary=await this.historicalBoundary(task,run);assertHistoricalRelayChangedFiles(historicalBoundary,result2.changed_files);await assertChangedFilesInScopeOrCausalRecords(task,result2.changed_files,this.filesystem,execution.id,this.repositories,historicalBoundary);return this.repositories.tasks.transition(id,"failed",result2)}async verifyChange(id){const{change}=await this.repositories.changes.read(id);if(change.status!=="executing")throw new LifecycleGateError(`Change ${id} must be executing before verification`);const tasks=await tasksForChange(this.repositories,change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}return this.repositories.changes.transition(id,"verifying")}async completeChange(id,result2){const{change}=await this.repositories.changes.read(id);if(change.status!=="verifying"){throw new LifecycleGateError(`Change ${id} must be verifying before completion`)}const tasks=await tasksForChange(this.repositories,change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}const covered=new Set(tasks.flatMap(task=>task.acceptance_ids));const missing=change.acceptance_ids.filter(acceptanceId=>!covered.has(acceptanceId));if(missing.length>0){throw new LifecycleGateError(`Change ${id} has uncovered Acceptance Criteria: ${missing.join(", ")}`)}for(const task of tasks){if(task.result===null)throw new LifecycleGateError(`Task ${task.id} has no terminal result`);await this.assertEvidenceCoverage(task,task.result)}return this.repositories.changes.transition(id,"completed",result2)}async verifyExecution(id){const{execution}=await this.repositories.executions.read(id);if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${id} must be running before verification`)}await assertExecutionDescendantsComplete(this.repositories,execution.id,execution.dag.nodes);return this.repositories.executions.transition(id,"verifying")}async completeExecution(id,result2){const{execution}=await this.repositories.executions.read(id);let completedExecution;if(execution.status==="verifying"){await assertExecutionDescendantsComplete(this.repositories,execution.id,execution.dag.nodes);const changeIds=[...new Set(execution.dag.nodes.map(node=>node.change_id))];for(const changeId of changeIds){const{change}=await this.repositories.changes.read(changeId);if(change.status!=="completed"){throw new LifecycleGateError(`Execution Change must be completed: ${formatLifecycleState(change)}`)}}completedExecution=await this.repositories.executions.transition(id,"completed",result2)}else if(execution.status==="completed"){completedExecution=execution}else{throw new LifecycleGateError(`Execution ${id} must be verifying before completion`)}await this.reconcileCompletedExecutionOrigin(completedExecution);return completedExecution}async reconcileCompletedExecutionOrigin(execution){if(execution.origin.type==="prd"){const{prd}=await this.repositories.prds.read(execution.origin.prd_id);if(prd.status==="active")await this.deliverPrd(prd.id);else if(prd.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable PRD ${prd.id}: ${prd.status}`)}}else if(execution.origin.type==="spec"){const{spec}=await this.repositories.specs.read(execution.origin.spec_id);if(spec.status==="active")await this.deliverSpec(spec.id);else if(spec.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable SPEC ${spec.id}: ${spec.status}`)}}}async deliverSpec(id){const{spec}=await this.repositories.specs.read(id);if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${id} must be active before delivery`)}const[changes,executions]=await Promise.all([this.repositories.changes.list(),this.repositories.executions.list()]);const descendants=changes.filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const descendantChangeIds=new Set(descendants.map(change=>change.id));const relatedExecutions=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id||execution.dag.nodes.some(node=>descendantChangeIds.has(node.change_id)));if(descendants.length===0||relatedExecutions.length===0){throw new LifecycleGateError(`SPEC ${id} has no materialized Change and Execution`)}assertAllTerminal(descendants,"SPEC Change");assertAllTerminal(relatedExecutions,"SPEC Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(relatedExecutions.flatMap(item=>item.dag.nodes.map(node=>node.task_id)));const parentalExecutions=relatedExecutions.filter(item=>item.origin.type==="spec"&&item.origin.spec_id===id);if(parentalExecutions.length!==1)throw new LifecycleGateError(`SPEC ${id} requires one exact parental Execution`);const parentalExecution=parentalExecutions[0];if(!parentalExecution)throw new LifecycleGateError(`SPEC ${id} parental Execution missing`);if(tasks.some(task=>!descendantChangeIds.has(task.change_id)))throw new LifecycleGateError(`SPEC ${id} Task proof has foreign Change ownership`);const parentBundle=await readParentAssuranceBundle(this.filesystem,this.layout,id,parentalExecution.id);if(parentBundle.validations.length===0&&parentBundle.evidences.length===0){await this.assertDeliveryAssurance("spec",spec.acceptance_ids,[],tasks,assurance)}else{await assertParentDeliveryPreflight({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories,spec_id:id,execution_id:parentalExecution.id,acceptance_ids:spec.acceptance_ids,tasks,assurance,causal_execution_ids:new Set(relatedExecutions.map(item=>item.id))})}}return this.repositories.specs.transition(id,"delivered")}async deliverPrd(id){const{prd}=await this.repositories.prds.read(id);if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${id} must be active before delivery`)}const[specs,changes,executions]=await Promise.all([this.repositories.specs.list(),this.repositories.changes.list(),this.repositories.executions.list()]);const executionId=prd.prepared_plan?.execution_id??prd.plan_ref?.execution_id;if(executionId===void 0){throw new LifecycleGateError(`PRD ${id} has no prepared plan or plan reference`)}const selectedExecution=executions.find(execution=>execution.id===executionId&&execution.origin.type==="prd"&&execution.origin.prd_id===id);if(selectedExecution===void 0){throw new LifecycleGateError(`PRD ${id} plan Execution does not resolve: ${executionId}`)}const selectedChangeIds=new Set(selectedExecution.dag.nodes.map(node=>node.change_id));const directChanges=changes.filter(change=>selectedChangeIds.has(change.id));const selectedSpecIds=prd.prepared_plan===null?new Set(directChanges.flatMap(change=>change.source.type==="prd"&&change.source.prd_id===id?[change.source.spec_id]:[])):new Set(specIdsForPrdPlanV2(prd.prepared_plan,id));const childSpecs=specs.filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));const directExecutions=[selectedExecution];if(childSpecs.length===0){throw new LifecycleGateError(`PRD ${id} requires at least one SPEC`)}for(const spec of childSpecs){if(spec.status==="active")await this.deliverSpec(spec.id)}const refreshedSpecs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));assertAllTerminal(refreshedSpecs,"PRD SPEC","delivered");assertAllTerminal(directChanges,"PRD Change");assertAllTerminal(directExecutions,"PRD Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(selectedExecution.dag.nodes.map(node=>node.task_id));const metadata3=prd;await this.assertDeliveryAssurance("prd",metadata3.acceptance_ids??refreshedSpecs.flatMap(spec=>spec.acceptance_ids),prd.outcome_ids,tasks,assurance)}return this.repositories.prds.transition(id,"delivered")}async cancelTask(id,summary,completedRunId=null){const{task}=await this.repositories.tasks.read(id);this.assertCancellable([task],["draft","planned","executing","verifying","blocked"],"Task");const changes=(await this.repositories.changes.list()).filter(change=>change.id===task.change_id&&change.source.type==="task"&&change.source.task_id===id);const executions=(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="task"&&execution.origin.task_id===id||execution.dag.nodes.some(node=>node.task_id===id&&node.change_id===task.change_id));const cascade=await this.cancelDescendants([],changes,executions,`Task ${id} was cancelled: ${summary}`,completedRunId);const cancelledTask=(await this.repositories.tasks.read(id)).task;return{task:cancelledTask,cascade}}async cancelPrd(id){const{prd}=await this.repositories.prds.read(id);this.assertCancellable([prd],["draft","ready","active","blocked"],"PRD");const specs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id);const specIds=new Set(specs.map(spec=>spec.id));const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="prd"&&change.source.prd_id===id||change.source.type==="spec"&&specIds.has(change.source.spec_id));const cascade=await this.cancelDescendants(specs,changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="prd"&&execution.origin.prd_id===id||execution.origin.type==="spec"&&specIds.has(execution.origin.spec_id)),`PRD ${id}`);const cancelledPrd=prd.status==="cancelled"?prd:await this.repositories.prds.transition(id,"cancelled");return{prd:cancelledPrd,cascade}}async cancelSpec(id){const{spec}=await this.repositories.specs.read(id);this.assertCancellable([spec],["draft","ready","active","blocked"],"SPEC");const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const cascade=await this.cancelDescendants([],changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id),`SPEC ${id}`);const cancelledSpec=spec.status==="cancelled"?spec:await this.repositories.specs.transition(id,"cancelled");return{spec:cancelledSpec,cascade}}async cancelDescendants(specs,changes,originExecutions,parent,completedRunId=null){return cancelLifecycleDescendants(this.repositories,(entities,cancellable,entity)=>this.assertCancellable(entities,cancellable,entity),specs,changes,originExecutions,parent,completedRunId)}assertCancellable(entities,cancellable,entity){for(const item of entities){if(item.status==="cancelled"||cancellable.includes(item.status))continue;throw new LifecycleGateError(`${entity} ${item.id} cannot be cancelled from status ${item.status}`)}}assuranceConfig(){const config2=this.layout.projectConfig?.assurance;return config2?.version===1?config2:null}async readTasks(ids2){return Promise.all([...new Set(ids2)].map(async id=>(await this.repositories.tasks.read(id)).task))}async assertDeliveryAssurance(origin,acceptanceIds,outcomeIds,tasks,config2){const{bundle,expected,validations,evidences}=await deliveryCandidateProofs(this.filesystem,this.layout,tasks,config2);const verifier=await deliveryVerifier(this.repositories,validations,tasks);assertDeliveryAssuranceV1({origin,config:config2,acceptance_ids:acceptanceIds,outcome_ids:outcomeIds,validations,evidences,verifier,mutation:deliveryMutationFrom(bundle.metadata,tasks.map(task=>task.id)),rollback_evidence_id:evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expected})}async assertEvidenceCoverage(task,result2){await assertTaskEvidenceCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2)}async historicalBoundary(task,run){const{createV2Composition:createV2Composition2}=await Promise.resolve().then(()=>(init_v2_router(),v2_router_exports));return historicalPublishedBoundaryForTask(task,run,createV2Composition2(this.filesystem,this.layout))}async assertSixStageCoverage(task,result2,executionId,enforceLegacyRiskCounts=true){await assertSixStageDeliveryCoverage(this.filesystem,this.layout,this.repositories,task,result2,executionId,enforceLegacyRiskCounts,this.assuranceConfig())}}}});async function hasPassedParentEvidenceSelection(root,ids2,composition){const r=root.run;if(r.task_id!==null||r.change_id!==null||r.parent_run_id!==null||r.spec_id===null||r.execution_id===null||r.entrypoint!=="spec"||r.agent!=="agent-orchestrator"||!composition.executions||ids2.length<3||new Set(ids2).size!==ids2.length)return false;try{const{execution}=await composition.executions.read(r.execution_id);const ownEvidenceBlock=execution.status==="blocked"&&execution.status_reason===`Finalization barrier evidence_missing; resume after passed typed Evidence linked to the same Task, Change, Execution, and Run (Run ${r.run_id}).`;if(execution.origin.type!=="spec"||execution.origin.spec_id!==r.spec_id||!["verifying","completed"].includes(execution.status)&&!ownEvidenceBlock||execution.dag.nodes.length===0)return false;const tasks=await Promise.all(execution.dag.nodes.map(async({task_id})=>(await composition.tasks.read(task_id)).task));if(tasks.some(task=>task.status!=="completed"))return false;const bundle=await readParentAssuranceBundle(composition.filesystem,composition.layout,r.spec_id,r.execution_id);const selected=ids2.map(id=>bundle.evidences.find(e=>e.id===id));if(selected.some(e=>e?.status!=="passed"||e.run_id!==r.run_id)||new Set(selected.map(e=>e?.commit_sha)).size!==1)return false;const validations=selected.flatMap(e=>e?.validation_artifact_ids.map(id=>bundle.validations.find(v=>v.id===id)));const sha5=selected[0]?.commit_sha;if(validations.some(v=>v?.status!=="passed"||v.commit_sha!==sha5))return false;const runs=await readAssuranceRunAncestry(composition.runs,[r.run_id,...validations.flatMap(v=>v?[v.run_id]:[])]);const descendants=descendantRuns(r.run_id,[...runs.values()]);const reviewRuns=new Set;for(const v of validations){if(v?.kind==="integration"){if(v?.run_id!==r.run_id||v?.candidate_execution?.exit_code!==0||v?.candidate_execution.commit_sha!==sha5)return false}else if(v?.kind==="spec_review"||v?.kind==="quality_review"){const reviewer=descendants.find(child=>child.run.run_id===v?.run_id);if(reviewer?.status!=="completed"||reviewer.run.agent!=="agent-reviewer"||reviewer.run.run_purpose!=="review"||reviewer.run.task_id!==null||reviewer.run.change_id!==null||reviewer.run.execution_id!==r.execution_id||reviewer.run.spec_id!==r.spec_id)return false;reviewRuns.add(reviewer.run.run_id)}}return reviewRuns.size>=2&&["integration","spec_review","quality_review"].every(kind=>validations.some(v=>v?.kind===kind))}catch{return false}}var init_run_parent_evidence_selection=__esm({"src/run-parent-evidence-selection.ts"(){"use strict";init_assurance_run_ancestry();init_parent_assurance_v1();init_run_hierarchy()}});async function hasPassedTypedEvidenceForRun(run,evidenceIds,composition,candidates=[]){if(run.run.execution_kind!=="delivery")return true;if(run.run.execution_id===null||evidenceIds.length===0){return false}if(isParentalRelayShape(run)&&"decisions"in composition){const proof=await authenticatedParentalRelay(run,composition,run.finished===null);return proof!==null&&evidenceIds.length===proof.parentEvidenceIds.length&&evidenceIds.every(id=>proof.parentEvidenceIds.includes(id))}if(await hasPassedParentEvidenceSelection(run,evidenceIds,composition))return true;const tasks=await evidenceTasks(run,composition);if(tasks.length===0)return false;const requested=new Set(evidenceIds);const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,tasks,[...requested]);const historical=await authenticatedHistoricalEvidence(run,composition);const eligible=await Promise.all(bundle.evidences.map(async evidence=>{const task=tasks.find(candidate=>evidence.task_id===candidate.id&&evidence.change_id===candidate.change_id);return requested.has(evidence.id)&&evidence.status==="passed"&&task!==void 0&&evidence.execution_id===run.run.execution_id&&(await completedEvidenceRun(evidence.run_id,run,task,composition,candidates)||historical.has(evidence.id))}));return bundle.evidences.length===requested.size&&eligible.every(Boolean)&&(run.run.task_id===null||sharesCandidate(bundle.evidences))}async function passedTypedEvidenceIdsForRun(run,composition,candidates=[]){if(run.run.execution_kind!=="delivery"||run.run.execution_id===null){return[]}if(isParentalRelayShape(run)){return(await authenticatedParentalRelay(run,composition,run.finished===null))?.parentEvidenceIds??[]}const tasks=await evidenceTasks(run,composition);if(tasks.length===0)return[];const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,tasks);const historical=await authenticatedHistoricalEvidence(run,composition);const eligible=await Promise.all(bundle.evidences.map(async evidence=>{const task=tasks.find(candidate=>evidence.task_id===candidate.id&&evidence.change_id===candidate.change_id);return evidence.status==="passed"&&task!==void 0&&evidence.execution_id===run.run.execution_id&&(await completedEvidenceRun(evidence.run_id,run,task,composition,candidates)||historical.has(evidence.id))?evidence.id:null}));return eligible.filter(id=>id!==null).sort()}async function authenticatedHistoricalEvidence(run,composition){if(run.run.task_id===null||!("decisions"in composition)||!("changes"in composition)||!("specs"in composition)||!("executions"in composition))return new Set;try{if(run.run.parent_run_id===null){const{taskFirstPublishedBoundary:taskFirstPublishedBoundary2}=await Promise.resolve().then(()=>(init_post_publication_task_first(),post_publication_task_first_exports));return new Set((await taskFirstPublishedBoundary2(run,composition))?.evidence_ids??[])}const{historicalRelayEvidenceIds:historicalRelayEvidenceIds3}=await Promise.resolve().then(()=>(init_post_publication_relay(),post_publication_relay_exports));return await historicalRelayEvidenceIds3(run,composition)}catch{return new Set}}async function evidenceTasks(run,composition){if(run.run.task_id!==null)return[(await composition.tasks.read(run.run.task_id)).task];if(run.run.execution_id===null||run.run.spec_id===null&&run.run.prd_id===null)return[];if(composition.executions===void 0)return[];const execution=(await composition.executions.read(run.run.execution_id)).execution;const scopeMatches3=run.run.prd_id!==null?execution.origin.type==="prd"&&execution.origin.prd_id===run.run.prd_id:execution.origin.type==="spec"&&execution.origin.spec_id===run.run.spec_id;if(!["verifying","completed"].includes(execution.status)||!scopeMatches3)return[];const tasks=await Promise.all(execution.dag.nodes.map(async node=>(await composition.tasks.read(node.task_id)).task));return tasks.every(task=>task.status==="completed")?tasks:[]}async function completedEvidenceRun(id,root,task,composition,candidates){if(root.run.task_id===null&&(task.status!=="completed"||task.result?.completed_run_id!==id)){return false}try{const run=await composition.runs.read(id);return(id===root.run.run_id||run.status==="completed")&&run.run.execution_id===root.run.execution_id&&run.run.task_id===task.id&&run.run.change_id===task.change_id&&run.run.conversation_id===root.run.conversation_id&&(root.run.task_id===null||belongsToRoot(id,root.run.run_id,candidates.length?candidates:[...(await readAssuranceRunAncestry(composition.runs,[id])).values()]))}catch{return false}}function belongsToRoot(evidenceRunId,rootRunId,candidates){return evidenceRunId===rootRunId||descendantRuns(rootRunId,candidates).some(candidate=>candidate.run.run_id===evidenceRunId)}function sharesCandidate(evidences){const identities=new Set(evidences.map(evidence=>evidence.commit_sha));if(identities.size>1)return false;return identities.has(null)?evidences.length===1:true}var init_run_finalization_evidence_v2=__esm({"src/run-finalization-evidence-v2.ts"(){"use strict";init_assurance_run_ancestry();init_lifecycle_assurance_v2();init_post_publication_parental();init_run_hierarchy();init_run_parent_evidence_selection()}});async function recoverOwnCompletionGateTask(current,task,composition){const reason=task.status_reason;const runId=current.run.run_id;const executionId=current.run.execution_id;if(task.status!=="blocked"||typeof reason!=="string"||typeof runId!=="string"||typeof executionId!=="string"||current.run.task_id!==task.id||current.run.change_id!==task.change_id||!isOwnCompletionGateBlock(reason,runId)){throw new Error(`Task ${task.id} is not blocked by the current Run completion gate`)}const[persistedRun,persistedTask,change,execution]=await Promise.all([composition.runs.read(runId),composition.tasks.read(task.id),composition.changes.read(task.change_id),composition.executions.read(executionId)]);if(persistedRun.status!=="completed"||persistedRun.finished===null||persistedRun.finalization_decision?.outcome!=="completed"||persistedRun.run.run_id!==runId||persistedRun.run.task_id!==task.id||persistedRun.run.change_id!==task.change_id||persistedRun.run.execution_id!==executionId||persistedTask.task.id!==task.id||persistedTask.task.change_id!==task.change_id||persistedTask.task.status!=="blocked"||persistedTask.task.status_reason!==reason||change.change.id!==task.change_id||change.change.status!=="blocked"||change.change.status_reason!==reason||execution.execution.id!==executionId||execution.execution.status!=="blocked"||execution.execution.status_reason!==reason){throw new Error(`Task ${task.id} completion gate graph does not match Run ${runId}`)}await composition.tasks.recoverOwnCompletionGateBlock(task.id,{runId,executionId,reason})}var init_completion_gate_recovery=__esm({"src/completion-gate-recovery.ts"(){"use strict";init_src7()}});async function assessRunLifecycleClosure(current,composition,candidateRuns){const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyClosure(current.run.run_id)}if(isParentalRelayShape(current))await authenticatedParentalRelay(current,composition);const subjects=(await Promise.all(current.run.entrypoint==="task"?[subject("task",current.run.task_id,composition,role,current)]:[subject("spec",current.run.spec_id,composition,role,current),subject("prd",current.run.prd_id,composition,role,current)])).filter(item=>item!==null);void candidateRuns;const openSubjectIds=subjects.filter(item=>!item.settled).map(item=>item.id);const status=subjects.length===0?"not_applicable":openSubjectIds.length===0?"closed":"action_required";return{status,run_id:current.run.run_id,continuation_run_id:null,subjects,open_subject_ids:openSubjectIds,default_inconclusive_outcome:"blocked",allowed_terminal_outcomes:["completed","blocked","failed","cancelled"],guidance:status==="action_required"?"Start an attributed continuation Run or settle every related work item; use blocked by default, failed only for an execution-preventing error, and cancelled only after an explicit user cancellation.":"Run lifecycle closure is satisfied."}}async function subject(kind,id,composition,role,current){if(id===null)return null;try{const status=kind==="task"?(await composition.tasks.read(id)).task.status:kind==="spec"?(await composition.specs.read(id)).spec.status:(await composition.prds.read(id)).prd.status;return{kind,id,status,settled:isSettled(kind,status,role,current)}}catch{return{kind,id,status:"missing",settled:false}}}function isSettled(kind,status,role,current){if(kind==="task")return["completed","blocked","failed","cancelled"].includes(status);if(role==="orchestrator"&&current.finished?.status==="completed")return status!=="missing";return["delivered","blocked","failed","cancelled"].includes(status)}function emptyClosure(runId){return{status:"not_applicable",run_id:runId,continuation_run_id:null,subjects:[],open_subject_ids:[],default_inconclusive_outcome:"blocked",allowed_terminal_outcomes:["completed","blocked","failed","cancelled"],guidance:"Run lifecycle closure is satisfied."}}var init_run_lifecycle_closure=__esm({"src/run-lifecycle-closure.ts"(){"use strict";init_src5();init_task_attempt();init_post_publication_parental()}});function emptyResult(runId,status){return{run_id:runId,status,outcome:null,fallback_from:null,error:null,tasks:[],changes:[],executions:[],specs:[],prds:[]}}var init_run_lifecycle_result=__esm({"src/run-lifecycle-result.ts"(){"use strict"}});function lifecycleReconciliationOutcome(value){if(value===void 0)return void 0;if(value==="completed"||value==="blocked"||value==="failed"||value==="cancelled"){return value}throw new Error("--task-outcome must be completed, blocked, failed, or cancelled")}function lifecycleOutcomeOption(options){if(options["owner-outcome"]!==void 0){throw new Error("Legacy lifecycle outcome option is no longer supported; use --task-outcome")}return lifecycleReconciliationOutcome(options["task-outcome"])}var init_run_lifecycle_outcome=__esm({"src/run-lifecycle-outcome.ts"(){"use strict"}});function isTaskAttemptRun(current){if(isNativeTaskAttempt(current))return true;return effectiveRunV2Role(current.run)==="orchestrator"&&current.run.parent_run_id===null&&(current.run.entrypoint==="task"||current.run.work_type==="rework"&&current.run.task_id!==null)}async function reconcileFinishedRunLifecycle(current,composition,lifecycle,options={}){if(current.finished===null)throw new Error(`Run is still running: ${current.run.run_id}`);const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyResult(current.run.run_id,"not_applicable")}if(isParentalRelayShape(current)){const state=await composition.executions.read(current.run.execution_id);await authenticatedParentalRelay(current,composition,state.execution.status==="running")}if(current.run.execution_id!==null){const execution=await composition.executions.read(current.run.execution_id).catch(()=>null);if(execution?.execution.kind==="interaction"){return emptyResult(current.run.run_id,"not_applicable")}}if(options.defer===true){throw new Error(`Orchestrator Run closure cannot be deferred for Run ${current.run.run_id}`)}const closure=await assessRunLifecycleClosure(current,composition,options.candidateRuns);if(closure.status==="not_applicable")return emptyResult(current.run.run_id,"not_applicable");const catalog=options.catalog??await loadCatalog(composition);const graph=relatedGraph(current,catalog);const requested=resolveOutcome(current,graph.tasks,options.requestedOutcome,options.forceRequestedOutcome);if(requested==="completed"){try{const resumable=await resumeOwnCompletionGateBlocks(current,graph,composition,lifecycle,options.candidateRuns);const completed=await completeGraph(current,resumable,composition,lifecycle,options);return{...completed,status:"closed",outcome:"completed"}}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);const blocked2=await settleGraph(current,await refreshGraph(graph,composition),composition,lifecycle,"blocked",`Completion gates did not close Run ${current.run.run_id}: ${message2}`);return{...blocked2,status:"closed",outcome:"blocked",fallback_from:"completed",error:message2}}}const settled=await settleGraph(current,graph,composition,lifecycle,requested,options.summary===void 0?defaultReason(current.run.run_id,requested):`${options.summary} (Run ${current.run.run_id}).`);return{...settled,status:"closed",outcome:requested}}async function snapshotRunLifecycle(current,composition,catalog){const role=effectiveRunV2Role(current.run);if(role==="intake"||role==="subagent"&&!isNativeTaskAttempt(current)&&!isParentalRelayShape(current)){return emptyResult(current.run.run_id,"not_applicable")}if(isParentalRelayShape(current))await authenticatedParentalRelay(current,composition);const graph=relatedGraph(current,catalog??await loadCatalog(composition));return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}async function resumeOwnCompletionGateBlocks(current,graph,composition,lifecycle,candidateRuns){if(current.finalization_decision?.outcome!=="completed")return graph;const eligiblePredecessors=new Set(await completionGatePredecessorIds(current,graph,candidateRuns??await composition.runs.list()));const runId=current.run.run_id;if(typeof runId!=="string")return graph;eligiblePredecessors.add(runId);const isOwnBlock=reason=>reason!==null&&[...eligiblePredecessors].some(runId2=>isOwnCompletionGateBlock(reason,runId2));for(const task of graph.tasks){const latest=(await composition.tasks.read(task.id)).task;if(latest.status==="blocked"&&isOwnBlock(latest.status_reason??null)){if(typeof latest.status_reason==="string"&&isOwnCompletionGateBlock(latest.status_reason,runId)){await recoverOwnCompletionGateTask(current,latest,composition)}else{await lifecycle.startTask(task.id,"resume")}}}for(const change of graph.changes){const latest=(await composition.changes.read(change.id)).change;if(latest.status==="blocked"&&isOwnBlock(latest.status_reason??null)){await composition.changes.transition(latest.id,"executing")}}for(const execution of graph.executions){const latest=(await composition.executions.read(execution.id)).execution;if(latest.status!=="blocked"||!isOwnBlock(latest.status_reason??null))continue;if(latest.dag.nodes.length===0){await composition.executions.transition(latest.id,"cancelled","Superseded empty continuation intake")}else{await composition.executions.transition(latest.id,"running")}}return refreshGraph(graph,composition)}async function completionGatePredecessorIds(current,graph,candidates){const threadId=current.run.client_thread_id;if(current.run.task_id===null||current.run.change_id===null||current.run.execution_id===null){return new Set}const executionIds=new Set(graph.executions.map(execution=>execution.id));const eligible=new Set;for(const predecessor of candidates){if(predecessor.run.run_id===current.run.run_id||predecessor.finished===null||!isTaskAttemptRun(predecessor)||predecessor.run.occurred_at>=current.run.occurred_at||threadId!==null&&predecessor.run.client_thread_id!==threadId||predecessor.run.task_id!==current.run.task_id||predecessor.run.change_id!==current.run.change_id||predecessor.run.execution_id===null||!executionIds.has(predecessor.run.execution_id)){continue}eligible.add(predecessor.run.run_id)}return eligible}function resolveOutcome(current,tasks,requested,forceRequested){if(forceRequested===true&&requested!==void 0)return requested;if(current.finished?.status==="failed")return"failed";if(current.finished?.status==="cancelled")return"cancelled";if(requested!==void 0)return requested;if(!isTaskAttemptRun(current))return"completed";const terminal=tasks.find(task=>["completed","blocked","failed","cancelled"].includes(task.status))?.status;return terminal==="completed"||terminal==="blocked"||terminal==="failed"||terminal==="cancelled"?terminal:"blocked"}async function completeGraph(current,graph,composition,lifecycle,options){const summary=options.summary??`Run ${current.run.run_id} completed.`;const result2={summary,changed_files:[...options.changedFiles??[]],evidence_ids:[...options.evidenceIds??[]],completed_run_id:current.run.run_id};const taskAttempt=isTaskAttemptRun(current);if(taskAttempt){for(const task of graph.tasks){let latest=(await composition.tasks.read(task.id)).task;if(latest.status==="executing")latest=await composition.tasks.transition(task.id,"verifying");if(latest.status==="verifying")await lifecycle.completeTask(task.id,result2)}}else{const unfinished=graph.tasks.filter(task=>task.status!=="completed");if(unfinished.some(task=>["draft","planned","executing","verifying"].includes(task.status))){await keepMacroParentsActive(graph,composition);return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}if(unfinished.length>0){throw new Error(`Macro Tasks did not complete: ${unfinished.map(task=>task.id).join(", ")}`)}}for(const change of graph.changes){let latest=(await composition.changes.read(change.id)).change;const relatedTasks=await Promise.all(latest.task_ids.map(async id=>(await composition.tasks.read(id)).task));if(relatedTasks.some(task=>task.status!=="completed"))continue;if(latest.status==="executing"){await lifecycle.verifyChange(change.id);latest=(await composition.changes.read(change.id)).change}if(latest.status==="verifying")await lifecycle.completeChange(change.id,summary)}for(const execution of graph.executions){let latest=(await composition.executions.read(execution.id)).execution;if(isNativeTaskAttempt(current)&&latest.origin.type!=="task")continue;const relatedTasks=await Promise.all(latest.dag.nodes.map(async node=>(await composition.tasks.read(node.task_id)).task));if(relatedTasks.some(task=>task.status!=="completed"))continue;if(latest.status==="planned"&&latest.dag.nodes.length===0){await composition.executions.transition(execution.id,"cancelled","Superseded empty continuation intake");continue}if(latest.status==="planned"){latest=await composition.executions.transition(execution.id,"running")}if(latest.status==="blocked"&&taskAttempt){latest=await composition.executions.transition(execution.id,"running")}if(latest.status==="running"){await lifecycle.verifyExecution(execution.id);latest=(await composition.executions.read(execution.id)).execution}if(latest.status==="verifying")await lifecycle.completeExecution(execution.id,summary)}if(!taskAttempt){for(const spec of graph.specs.filter(item=>graph.directSpecIds.has(item.id))){if((await composition.specs.read(spec.id)).spec.status==="active")await lifecycle.deliverSpec(spec.id)}for(const prd of graph.prds.filter(item=>graph.directPrdIds.has(item.id))){if((await composition.prds.read(prd.id)).prd.status==="active")await lifecycle.deliverPrd(prd.id)}}else{await aggregateMacroAncestors(graph,composition)}const refreshed=await refreshGraph(graph,composition);assertGraphCompleted(refreshed,taskAttempt);return currentGraphResult(current.run.run_id,refreshed)}function assertGraphCompleted(graph,taskAttempt){const incomplete2=[...graph.tasks.filter(item=>item.status!=="completed").map(item=>item.id),...!taskAttempt?graph.changes.filter(item=>item.status!=="completed").map(item=>item.id):[],...graph.executions.filter(item=>item.status!=="completed"&&!(taskAttempt&&item.origin.type!=="task")&&!(item.dag.nodes.length===0&&item.status==="cancelled")).map(item=>item.id),...graph.specs.filter(item=>!taskAttempt&&graph.directSpecIds.has(item.id)&&item.status!=="delivered").map(item=>item.id),...graph.prds.filter(item=>!taskAttempt&&graph.directPrdIds.has(item.id)&&item.status!=="delivered").map(item=>item.id)];if(incomplete2.length>0){throw new Error(`Completion left related work non-terminal: ${incomplete2.join(", ")}`)}}async function settleGraph(current,graph,composition,lifecycle,outcome,reason){const clock=new SystemClock;const taskAttempt=isTaskAttemptRun(current);const taskResult=outcome==="blocked"?null:{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:current.run.run_id};for(const task of graph.tasks){const latest=(await composition.tasks.read(task.id)).task;if((taskAttempt?SETTLEABLE_TASK:new Set(["executing","verifying"])).has(latest.status)){await composition.tasks.transition(task.id,outcome,taskResult,clock,reason)}}const standalone=graph.executions.some(execution=>execution.origin.type==="task");for(const change of taskAttempt&&!standalone?[]:graph.changes){const latest=(await composition.changes.read(change.id)).change;if((taskAttempt?SETTLEABLE_CHANGE:new Set(["executing","verifying"])).has(latest.status)){await composition.changes.transition(change.id,outcome,outcome==="blocked"?null:reason,clock,reason)}}for(const execution of taskAttempt&&!standalone?[]:graph.executions){const latest=(await composition.executions.read(execution.id)).execution;if((taskAttempt?SETTLEABLE_EXECUTION:new Set(["running","paused","verifying"])).has(latest.status)){await composition.executions.transition(execution.id,outcome,outcome==="blocked"?null:reason,clock,reason)}}const specIdsToSettle=new Set(taskAttempt?[]:specIdsForLifecycleSettlement(graph.specs.map(item=>item.id),graph.directSpecIds,graph.directPrdIds));const specsToSettle=graph.specs.filter(item=>specIdsToSettle.has(item.id));for(const spec of specsToSettle){if(outcome==="cancelled"&&graph.directPrdIds.size>0)break;if((await composition.specs.read(spec.id)).spec.status==="active"){if(outcome==="cancelled")await lifecycle.cancelSpec(spec.id);else await composition.specs.transition(spec.id,outcome,reason)}}for(const prd of graph.prds.filter(item=>!taskAttempt&&graph.directPrdIds.has(item.id))){if((await composition.prds.read(prd.id)).prd.status==="active"){if(outcome==="cancelled")await lifecycle.cancelPrd(prd.id);else await composition.prds.transition(prd.id,outcome,reason)}}if(taskAttempt&&!standalone)await aggregateMacroAncestors(graph,composition);return currentGraphResult(current.run.run_id,await refreshGraph(graph,composition))}function relatedGraph(current,catalog){const{tasks,changes,executions,specs,prds}=catalog;const taskIds=new Set(current.run.task_id===null?[]:[current.run.task_id]);const changeIds=new Set(current.run.change_id===null?[]:[current.run.change_id]);const executionIds=new Set(current.run.execution_id===null?[]:[current.run.execution_id]);const specIds=new Set(current.run.spec_id===null?[]:[current.run.spec_id]);const prdIds=new Set(current.run.prd_id===null?[]:[current.run.prd_id]);const taskAttempt=isTaskAttemptRun(current);if(!taskAttempt){for(const spec of specs)if(spec.prd_id!==null&&prdIds.has(spec.prd_id))specIds.add(spec.id)}for(const change of changes){const source=change.source;if(changeIds.has(change.id)||source.type==="task"&&taskIds.has(source.task_id)||!taskAttempt&&source.type==="spec"&&specIds.has(source.spec_id)||!taskAttempt&&source.type==="prd"&&prdIds.has(source.prd_id))changeIds.add(change.id)}for(const task of tasks){if(taskIds.has(task.id)||!taskAttempt&&changeIds.has(task.change_id)){taskIds.add(task.id);const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id;if(canonicalExecutionId!==void 0&&canonicalExecutionId!==null)executionIds.add(canonicalExecutionId)}}for(const execution of executions){if(executionIds.has(execution.id)||execution.origin.type==="task"&&taskIds.has(execution.origin.task_id)||execution.dag.nodes.some(node=>taskIds.has(node.task_id))){executionIds.add(execution.id)}}return{tasks:tasks.filter(item=>taskIds.has(item.id)),changes:changes.filter(item=>changeIds.has(item.id)),executions:executions.filter(item=>executionIds.has(item.id)),specs:specs.filter(item=>specIds.has(item.id)),prds:prds.filter(item=>prdIds.has(item.id)),directSpecIds:new Set(current.run.spec_id===null?[]:[current.run.spec_id]),directPrdIds:new Set(current.run.prd_id===null?[]:[current.run.prd_id])}}async function keepMacroParentsActive(graph,composition){for(const spec of graph.specs){const latest=(await composition.specs.read(spec.id)).spec;if(latest.status==="ready"||latest.status==="blocked"){await composition.specs.transition(latest.id,"active")}}for(const prd of graph.prds){const latest=(await composition.prds.read(prd.id)).prd;if(latest.status==="ready"||latest.status==="blocked"){await composition.prds.transition(latest.id,"active")}}}async function aggregateMacroAncestors(graph,composition){await keepMacroParentsActive(graph,composition)}async function loadCatalog(composition){const[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);return{tasks,changes,executions,specs,prds}}async function refreshGraph(graph,composition){const[tasks,changes,executions,specs,prds]=await Promise.all([Promise.all(graph.tasks.map(async item=>(await composition.tasks.read(item.id)).task)),Promise.all(graph.changes.map(async item=>(await composition.changes.read(item.id)).change)),Promise.all(graph.executions.map(async item=>(await composition.executions.read(item.id)).execution)),Promise.all(graph.specs.map(async item=>(await composition.specs.read(item.id)).spec)),Promise.all(graph.prds.map(async item=>(await composition.prds.read(item.id)).prd))]);return{...graph,tasks,changes,executions,specs,prds}}function currentGraphResult(runId,graph){return{run_id:runId,status:"closed",outcome:null,fallback_from:null,error:null,tasks:graph.tasks,changes:graph.changes,executions:graph.executions,specs:graph.specs,prds:graph.prds}}function specIdsForLifecycleSettlement(specIds,directSpecIds,directPrdIds){return directPrdIds.size>0?[...specIds]:specIds.filter(id=>directSpecIds.has(id))}function defaultReason(runId,outcome){if(outcome==="failed")return`Run ${runId} failed and closed its operational lifecycle.`;if(outcome==="cancelled")return`Run ${runId} was explicitly cancelled.`;return`Run ${runId} completed without sufficient closure gates and has no concrete continuation.`}var SETTLEABLE_TASK,SETTLEABLE_CHANGE,SETTLEABLE_EXECUTION;var init_run_lifecycle_reconciliation=__esm({"src/run-lifecycle-reconciliation.ts"(){"use strict";init_src();init_src5();init_src7();init_completion_gate_recovery();init_task_attempt();init_post_publication_parental();init_run_lifecycle_closure();init_run_lifecycle_result();init_run_lifecycle_outcome();SETTLEABLE_TASK=new Set(["draft","planned","executing","verifying"]);SETTLEABLE_CHANGE=new Set(["draft","planned","executing","verifying"]);SETTLEABLE_EXECUTION=new Set(["planned","running","paused","verifying"])}});async function reconcileTerminalOrchestratorRoot(root,candidates,composition,lifecycle){const decision=root.finalization_decision??null;const evidenceIds=decision===null?await passedTypedEvidenceIdsForRun(root,composition,candidates):decision.evidence_ids;const evidenceSatisfied=await hasPassedTypedEvidenceForRun(root,evidenceIds,composition,candidates);const barrier=assessRunFinalizationBarrier(root,candidates,evidenceSatisfied);const blockReason=finalizationBarrierBlockReason(barrier);const decisionEligible=decision!==null&&(decision.outcome!=="completed"||barrier.satisfied);const reconciliation=await reconcileFinishedRunLifecycle(root,composition,lifecycle,{requestedOutcome:decisionEligible?decision.outcome:"blocked",forceRequestedOutcome:!decisionEligible,summary:decisionEligible?decision.summary:blockReason??"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.",evidenceIds:decision?.evidence_ids??evidenceIds,changedFiles:decision?.changed_files??[],candidateRuns:candidates});return{status:"closed",parent_run_id:root.run.run_id,finalization_barrier:barrier,finalization_decision:decision,reconciliation}}var init_orchestrator_stop_reconciliation=__esm({"src/orchestrator-stop-reconciliation.ts"(){"use strict";init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_lifecycle_reconciliation()}});function runClosureView(repository2,current,prospective){const next=prospective.records.at(-1);if(current.finished!==null||prospective.run.run_id!==current.run.run_id||JSON.stringify(prospective.run)!==JSON.stringify(current.run)||prospective.records.length!==current.records.length+1||next?.type!=="run.finished"||next.sequence!==current.records.length+1||current.records.some((record3,index)=>JSON.stringify(record3)!==JSON.stringify(prospective.records[index])))throw new Error("Closure view requires the exact next terminal event for the locked Run");return new Proxy(repository2,{get(target,key){if(["start","appendRecord"].includes(String(key)))return()=>{throw new Error("Closure view cannot persist Run events")};if(key==="read")return id=>id===current.run.run_id?Promise.resolve(prospective):target.read(id);if(key==="list")return async()=>(await target.list()).map(run=>run.run.run_id===current.run.run_id?prospective:run);const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value}})}var init_run_closure_view=__esm({"src/run-closure-view.ts"(){"use strict"}});function assurancePlanning(task,effective){const{contract}=effective;return{schema_version:1,task_id:task.id,phase:"planning",approved:false,requirement_ids:task.requirement_ids,acceptance:task.acceptance_ids.map(acceptance_id=>({acceptance_id,scenario_required:true,expected_outcome_required:true,environment_required:true,modalities:contract.required_modalities,individual_evidence:contract.evidence_per_acceptance})),minimum_validations:contract.minimum_validation_artifacts,independent_review:contract.requires_independent_verifier,mutation_kill_ratio:contract.requires_mutation_discrimination?contract.minimum_mutation_kill_ratio:null,rollback:contract.requires_rollback,final_commit:effective.require_final_commit||contract.requires_final_commit_evidence,before_publication:`task assurance ${task.id} --preflight --evidence EVD-ID --json`,guidance:"Define scenarios and evidence ownership now; collect candidate-bound proof before publication. This plan does not approve evidence or authorize closure."}}var init_assurance_planning=__esm({"src/assurance-planning.ts"(){"use strict"}});function createTaskFirstPreparedPlan(input){const{task}=input;return createPreparedPlanV2({revision:1,source:{type:"task",task_id:task.id},execution_id:input.executionId,prepared_at:input.preparedAt,policy:input.policy,blueprints:{changes:[{key:"task-first-change",id:task.change_id,title:task.title,short_name:task.short_name,risk:task.risk,source:{type:"task",task_id:task.id},requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,requirement_impact:taskFirstRequirementImpact(input)}],tasks:[{key:"task-first",id:task.id,change_id:task.change_id,title:task.title,short_name:task.short_name,objective:task.objective,risk:task.risk,priority:task.priority,owner:task.owner,requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,write_scopes:task.write_scopes,...input.modelSignals===void 0?task.model_profile===void 0?{}:{model_profile:task.model_profile}:{model_signals:input.modelSignals}}]},dag:{nodes:[{task_id:task.id,depends_on:task.depends_on}]}})}function taskModelSignalsOption(raw){if(raw===void 0)return void 0;try{return taskModelSignalsSchema.parse(JSON.parse(raw))}catch{throw new UsageError("--model-signals requires valid structured TaskModelSignals JSON")}}async function runPlanV2Command(action,parsed,filesystem,layout){if(action==="acceptance"){requireOptions(parsed.options,["input"]);return evaluateAcceptanceInput(filesystem,parsed.options.input)}if(action==="build"){requireOptions(parsed.options,["draft"]);const input=JSON.parse(await filesystem.readText(parsed.options.draft));if(input.acceptance_contract!==void 0&&parsed.options.acceptance!==void 0){throw new UsageError("Specify acceptance inside the draft or with --acceptance, not both")}const acceptance=parsed.options.acceptance===void 0?input.acceptance_contract:JSON.parse(await filesystem.readText(parsed.options.acceptance));const complete={...input,...acceptance===void 0?{}:{acceptance_contract:acceptance}};if(complete.source.type!=="task"&&acceptance!==void 0)assertDeclaredLocalHost(acceptance);const plan=complete.source.type==="task"?createPreparedPlanV2(complete):createAdoptedPreparedPlanV2(complete);await assertPreparedPlanReferences(filesystem,plan);const outputPath=parsed.options.output;if(outputPath!==void 0){await filesystem.writeTextAtomic(outputPath,`${JSON.stringify(plan,null,2)}
3592
3592
  `);return{valid:true,plan:preparedPlanSummary(plan),artifact_path:outputPath}}return plan}if(action==="validate"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);return{valid:true,plan:preparedPlanSummary(plan)}}if(action==="normalize"){if(layout===void 0)throw new UsageError("plan normalize requires a modern workspace");const scopes=["task","spec","prd"].filter(scope2=>parsed.options[scope2]!==void 0);if(scopes.length!==1){throw new UsageError("plan normalize requires exactly one of --task, --spec, or --prd")}const scope=scopes[0];const id=parsed.options[scope];if(scope==="task"){const repository3=new TaskV2Repository(filesystem,layout);const current2=(await repository3.read(id)).task;if(current2.plan_ref!==void 0)return{plan_ref:current2.plan_ref};if(current2.prepared_plan===void 0)throw new UsageError(`Task has no plan: ${id}`);const task=await repository3.normalizePreparedPlan(id,current2.prepared_plan);return{plan_ref:task.plan_ref}}if(scope==="spec"){const repository3=new DeliverySpecV2Repository(filesystem,layout);const current2=(await repository3.read(id)).spec;if(current2.plan_ref!==null)return{plan_ref:current2.plan_ref};if(current2.prepared_plan===null)throw new UsageError(`SPEC has no plan: ${id}`);const spec=await repository3.normalizePreparedPlan(id,current2.prepared_plan);return{plan_ref:spec.plan_ref}}const repository2=new PrdV2Repository(filesystem,layout);const current=(await repository2.read(id)).prd;if(current.plan_ref!==null)return{plan_ref:current.plan_ref};if(current.prepared_plan===null)throw new UsageError(`PRD has no plan: ${id}`);const prd=await repository2.normalizePreparedPlan(id,current.prepared_plan);return{plan_ref:prd.plan_ref}}throw new UsageError(`Unknown V2 Plan action: ${action??""}`)}async function evaluateAcceptanceInput(filesystem,path){const input=JSON.parse(await filesystem.readText(path));if(input?.evaluation!=="outcome")throw new UsageError("Standalone acceptance evaluates outcomes only");assertDeclaredLocalHost(input);const result2=evaluateProportionalAcceptance(input);if(result2.unavailable.length===1&&result2.unavailable[0]==="release_proof_unverified")return{...result2,authoritative:false,note:"Release proof locators are self-reported; publication requires the release pipeline receipt."};if(!result2.approved){throw new UsageError(`Acceptance ${result2.state}: ${[...result2.failures,...result2.unavailable].join(", ")}`)}return result2}function assertDeclaredLocalHost(input){if(!Array.isArray(input.local_platforms)||input.local_platforms.some(platform=>platform!==process.platform))throw new UsageError(`Declared local platform must match the active host: ${process.platform}`)}async function readPreparedPlan(filesystem,parsed){requireOptions(parsed.options,["plan"]);const plan=preparedPlanV2Schema.parse(JSON.parse(await filesystem.readText(parsed.options.plan)));if(plan.source.type!=="task"&&plan.acceptance_policy===void 0){throw new UsageError("External PRD/SPEC plans require proportional-acceptance-v1 adoption; historical embedded plans remain readable by their owning record")}return plan}async function assertPreparedPlanReferences(filesystem,plan){const paths2=await filesystem.listFiles(".agents/requirements",".md");if(paths2.length===0){throw new UsageError("PreparedPlan requires a non-empty .agents/requirements catalog")}const catalog=buildRequirementReferenceCatalog(await Promise.all(paths2.map(path=>filesystem.readText(path))));const requirementIds=[...(plan.blueprints.specs??[]).flatMap(spec=>spec.requirement_ids),...plan.blueprints.changes.flatMap(change=>[...change.requirement_ids,...change.requirement_impact.type==="update"?change.requirement_impact.requirement_ids:[]]),...plan.blueprints.tasks.flatMap(task=>task.requirement_ids)];const acceptanceIds=[...(plan.blueprints.specs??[]).flatMap(spec=>spec.acceptance_ids),...plan.blueprints.changes.flatMap(change=>change.acceptance_ids),...plan.blueprints.tasks.flatMap(task=>task.acceptance_ids)];const findings=validateRequirementReferences(catalog,requirementIds,acceptanceIds);if(findings.length>0){throw new UsageError(`PreparedPlan contains unresolved governance references: ${findings.map(finding3=>finding3.id).join(", ")}`)}for(const criterion of plan.acceptance_contract?.criteria??[]){if(criterion.origin.kind==="active_requirement"&&!requirementIds.includes(criterion.origin.reference)){throw new UsageError(`Acceptance ${criterion.id} cites a Requirement outside this plan: ${criterion.origin.reference}`)}}}async function preparedTaskPlan(tasks,materializer,id){const{task}=await tasks.read(id);if(task.status!=="planned")throw new UsageError(`Task is not prepared: ${id}`);if(task.prepared_plan!==void 0)return task.prepared_plan;if(task.plan_ref===void 0)throw new UsageError(`Task is not prepared: ${id}`);const plan=await materializer.readPreparedPlan(task.plan_ref.execution_id);if(plan.hash!==task.plan_ref.hash||plan.revision!==task.plan_ref.revision||plan.execution_id!==task.plan_ref.execution_id||plan.source.type!=="task"||plan.source.task_id!==task.id){throw new UsageError(`Task plan reference cannot be resolved canonically: ${id}`)}return plan}function taskFirstRequirementImpact(input){if(input.requirementImpact?.type==="update"){return{type:"update",requirement_ids:[...input.requirementImpact.requirement_ids]}}return{type:"none",reason:input.requirementImpact?.reason??input.requirementImpactReason??"Implements existing Requirements."}}function preparedPlanSummary(plan){return{schema_version:plan.schema_version,revision:plan.revision,source:plan.source,execution_id:plan.execution_id,prepared_at:plan.prepared_at,hash:plan.hash,change_count:plan.blueprints.changes.length,task_count:plan.blueprints.tasks.length,topological_order:plan.dag.topological_order}}var init_prepared_plan_v22=__esm({"src/prepared-plan-v2.ts"(){"use strict";init_src();init_src6();init_src7();init_cli_arguments()}});function conversationTaskModelProfile(options){const signals=taskModelSignalsOption(options["model-signals"]);const profile=signals===void 0?void 0:createTaskModelProfile(signals);if(profile&&options.risk!==void 0&&riskOption(options.risk)!==profile.risk)throw new UsageError("Explicit risk conflicts with structured model signals");return profile}function assertConversationProfileReplay(options,persisted){const requested=conversationTaskModelProfile(options);if(requested&&JSON.stringify(requested)!==JSON.stringify(persisted))throw new UsageError("Exact-turn replay conflicts with persisted model signals")}function resolveConversationModel(explicitModel,observedModel=null){return explicitModel??observedModel??"unknown"}function resolveConversationReasoningEffort(explicitEffort,observedEffort){if(explicitEffort!==void 0)return runV2ReasoningEffortSchema.parse(explicitEffort);const observed=runV2ReasoningEffortSchema.safeParse(observedEffort);return observed.success?observed.data:null}var init_conversation_model_observation=__esm({"src/conversation-model-observation.ts"(){"use strict";init_src();init_src5();init_cli_arguments();init_prepared_plan_v22()}});async function activeCanonicalTaskExecution(taskId,composition){const task=(await composition.tasks.read(taskId)).task;if(task.status==="draft"||task.status==="planned")return null;const executionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(executionId===null)return null;const execution=(await composition.executions.read(executionId)).execution;const terminal=new Set(["completed","failed","cancelled"]);return!terminal.has(execution.status)&&execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)?execution:null}async function resolveCanonicalMacroExecution(target,composition,explicitExecutionId){const scope=target.specId===void 0?target.prdId===void 0?null:{type:"prd",id:target.prdId}:target.prdId===void 0?{type:"spec",id:target.specId}:null;if(scope===null){throw new UsageError("Macro continuation requires exactly one of SPEC or PRD")}const entity=scope.type==="spec"?(await composition.specs.read(scope.id)).spec:(await composition.prds.read(scope.id)).prd;const executionIds=[entity.prepared_plan?.execution_id,entity.plan_ref?.execution_id].filter(id=>typeof id==="string");const distinctExecutionIds=[...new Set(executionIds)];if(distinctExecutionIds.length!==1){throw new UsageError(distinctExecutionIds.length===0?`${scope.type.toUpperCase()} ${scope.id} has no prepared Execution for continuation`:`${scope.type.toUpperCase()} ${scope.id} has ambiguous prepared Executions`)}const executionId=distinctExecutionIds[0];if(executionId===void 0){throw new UsageError(`Prepared Execution cannot be resolved for ${scope.type.toUpperCase()} ${scope.id}`)}const execution=(await composition.executions.read(executionId)).execution;if(explicitExecutionId!==void 0&&explicitExecutionId!==execution.id){throw new UsageError(`Explicit Execution ${explicitExecutionId} conflicts with prepared Execution ${execution.id}`)}const originMatches=scope.type==="spec"?execution.origin.type==="spec"&&execution.origin.spec_id===scope.id:execution.origin.type==="prd"&&execution.origin.prd_id===scope.id;if(execution.kind!=="delivery"||execution.plan_hash===null||execution.dag.nodes.length===0||!originMatches){throw new UsageError(`Prepared Execution ${execution.id} is incompatible with ${scope.type.toUpperCase()} ${scope.id}`)}if(!new Set(["planned","running","verifying"]).has(execution.status)){throw new UsageError(`Prepared Execution ${execution.id} cannot continue from status ${execution.status}`)}return execution}function conversationCapturePhase(intent,isActiveTaskContinuation=false){if(intent==="new_work"||intent==="continue"&&isActiveTaskContinuation)return"execution";return intent==="refine"||intent==="rework"?"planning":"conversation"}var init_conversation_canonical_execution=__esm({"src/conversation-canonical-execution.ts"(){"use strict";init_cli_arguments()}});import{randomUUID as randomUUID8}from"node:crypto";async function resolveWriterId(filesystem){const existing=workspaceWriterIds.get(filesystem.root);if(existing!==void 0)return existing;const created=(async()=>{const path=".local/telemetry-writer-id.json";const writerId=`writer-${randomUUID8()}`;try{await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify({schema_version:1,writer_id:writerId})}
3593
3593
  `);return writerId}catch(error51){if(!isNodeError9(error51)||error51.code!=="EEXIST")throw error51;const marker=JSON.parse(await filesystem.readText(path));if(typeof marker!=="object"||marker===null||!("writer_id"in marker)||typeof marker.writer_id!=="string"||!/^writer-[0-9a-f-]{36}$/.test(marker.writer_id)){throw new Error("Invalid local telemetry writer marker")}return marker.writer_id}})();workspaceWriterIds.set(filesystem.root,created);try{return await created}catch(error51){if(workspaceWriterIds.get(filesystem.root)===created)workspaceWriterIds.delete(filesystem.root);throw error51}}function isNodeError9(error51){return typeof error51==="object"&&error51!==null&&"code"in error51}var workspaceWriterIds;var init_codex_telemetry_writer_id=__esm({"src/codex-telemetry-writer-id.ts"(){"use strict";workspaceWriterIds=new Map}});import{randomUUID as randomUUID9}from"node:crypto";async function withWorkspaceCompactionLock(filesystem,operation){const deadline=Date.now()+COMPACTION_LOCK_TIMEOUT_MS;const ownerNonce=randomUUID9();const path=`${COMPACTION_LOCK_ROOT}/${ownerNonce}.json`;const owner=compactionLock(ownerNonce,path);let participantText=`${JSON.stringify({...owner,choosing:true,ticket:0})}
3594
3594
  `;await filesystem.writeTextExclusive(path,participantText);try{const participants=await bakeryParticipants(filesystem);const ticket=Math.max(0,...participants.map(entry2=>entry2.ticket))+1;participantText=`${JSON.stringify({...owner,choosing:false,ticket})}
3595
3595
  `;await filesystem.writeTextAtomic(path,participantText);while(true){const others=await bakeryParticipants(filesystem);const blocked2=others.some(entry2=>entry2.owner_nonce!==owner.owner_nonce&&(entry2.choosing||entry2.ticket>0&&(entry2.ticket<ticket||entry2.ticket===ticket&&entry2.owner_nonce<owner.owner_nonce)));if(!blocked2)break;if(Date.now()>=deadline)throw new Error(`Telemetry compaction bakery lock remained held: ${COMPACTION_LOCK_ROOT}. Verify participant files before manual removal.`);await delay5(COMPACTION_LOCK_WAIT_MS)}return await operation()}finally{await releaseCompactionParticipant(filesystem,path,participantText)}}async function bakeryParticipants(filesystem){const paths2=await filesystem.listFiles(COMPACTION_LOCK_ROOT,".json");const values=[];for(const path of paths2){const text=await readCompactionParticipant(filesystem,path);if(text===null)continue;try{const value=JSON.parse(text);if(!isCompactionParticipant(value,path)){values.push(invalidParticipant(path));continue}if(!compactionParticipantIsAlive(value.pid)){const removed=await filesystem.removeFileIfContentMatches(path,text);if(!removed){const replacement=await readCompactionParticipant(filesystem,path);if(replacement===null)continue;try{const replacementValue=JSON.parse(replacement);values.push(isCompactionParticipant(replacementValue,path)?replacementValue:invalidParticipant(path))}catch{values.push(invalidParticipant(path))}}continue}values.push(value)}catch{values.push(invalidParticipant(path))}}return values}function compactionParticipantIsAlive(pid){try{process.kill(pid,0);return true}catch(error51){return!(isNodeError9(error51)&&error51.code==="ESRCH")}}async function readCompactionParticipant(filesystem,path){for(let attempt=0;attempt<2;attempt+=1){try{return await filesystem.readText(path)}catch(error51){if(isNodeError9(error51)&&error51.code==="ENOENT")return null;if(isConcurrentParticipantRemoval(error51))return null;if(isNodeError9(error51)&&(error51.code==="EPERM"||error51.code==="EBADF")&&attempt===0){await delay5(COMPACTION_LOCK_WAIT_MS);if(!await filesystem.exists(path))return null;continue}throw error51}}return null}function isConcurrentParticipantRemoval(error51){return error51 instanceof WorkspacePathError&&isNodeError9(error51.cause)&&error51.cause.code==="ENOENT"}function isCompactionParticipant(value,path){if(typeof value!=="object"||value===null)return false;const participant=value;return participant.schema_version===1&&participant.purpose==="telemetry-compaction"&&Number.isSafeInteger(participant.pid)&&participant.pid>=1&&typeof participant.owner_nonce==="string"&&participant.owner_nonce.length>0&&participant.path===path&&participant.path===`${COMPACTION_LOCK_ROOT}/${participant.owner_nonce}.json`&&typeof participant.acquired_at==="string"&&!Number.isNaN(Date.parse(participant.acquired_at))&&typeof participant.choosing==="boolean"&&Number.isSafeInteger(participant.ticket)&&participant.ticket>=0}function invalidParticipant(path){return{...compactionLock(`invalid-${path}`,path),choosing:true,ticket:1}}async function releaseCompactionParticipant(filesystem,path,expected){try{if(await filesystem.readText(path)!==expected)return}catch(error51){if(isNodeError9(error51)&&error51.code==="ENOENT")return;throw error51}await filesystem.removeFile(path)}function compactionLock(owner_nonce,path){return{schema_version:1,purpose:"telemetry-compaction",pid:process.pid,owner_nonce,path,acquired_at:new Date().toISOString()}}async function delay5(milliseconds){await new Promise(resolveDelay=>setTimeout(resolveDelay,milliseconds))}var COMPACTION_LOCK_ROOT,COMPACTION_LOCK_WAIT_MS,COMPACTION_LOCK_TIMEOUT_MS;var init_codex_telemetry_compaction_lock=__esm({"src/codex-telemetry-compaction-lock.ts"(){"use strict";init_src();init_codex_telemetry_writer_id();COMPACTION_LOCK_ROOT=".local/telemetry-compaction-locks";COMPACTION_LOCK_WAIT_MS=25;COMPACTION_LOCK_TIMEOUT_MS=12e4}});import{createHash as createHash46}from"node:crypto";async function compactPendingCodexTelemetry(filesystem){return withTelemetrySnapshot(filesystem,(_events,compact)=>compact(),()=>listCodexTelemetrySpoolEvents(filesystem))}async function withPreparedCodexTelemetry(filesystem,operation,options={}){return withTelemetrySnapshot(filesystem,operation,()=>prepareCodexTelemetrySpoolIndex(filesystem,options))}async function withTelemetrySnapshot(filesystem,operation,readSnapshot){return queueWorkspaceCompaction(filesystem.root,()=>withWorkspaceCompactionLock(filesystem,async()=>{const events=await readSnapshot();let active=true;let compacted;const compact=()=>{if(!active)return Promise.reject(new Error("Prepared telemetry snapshot expired outside compaction lock"));compacted??=compactWorkspaceTelemetry(filesystem,events);return compacted};try{return await operation(events,compact)}finally{active=false;if(compacted!==void 0)await compacted}}))}async function compactWorkspaceTelemetry(filesystem,events){const byInvocation=new Map;for(const envelope of events){const source=envelope.event;if(source.event_kind==="response"&&source.tokens===null)continue;const event={event_id:envelope.event_id,source_event_key:source.source_event_key,source_occurred_at:source.source_occurred_at,captured_at:source.captured_at,event_kind:source.event_kind==="response"?"usage":source.event_kind,correlation:{...source.correlation,developer_identity:source.correlation.developer_identity??null},coverage:source.coverage,tokens:source.tokens===null?null:{input:source.tokens.input,cached_input:source.tokens.cached_input,output:source.tokens.output,reasoning:source.tokens.reasoning,total:source.tokens.total},provider:source.provider,model:source.model,runtime:source.runtime,status:source.status,duration_ms:source.event_kind==="terminal"?source.latency_ms:null,latency_ms:null,historical_cost:source.historical_cost??null};byInvocation.set(event.correlation.agent_invocation_id,[...byInvocation.get(event.correlation.agent_invocation_id)??[],event])}const summaries=[...byInvocation.values()].filter(group=>group.some(event=>event.event_kind==="terminal"||event.event_kind==="error")).map(group=>compactInvocationTelemetry(group));const byMonth=new Map;for(const summary of summaries){const date5=new Date(summary.occurred_at);if(Number.isNaN(date5.getTime()))throw new Error(`Invalid compacted occurrence timestamp: ${summary.agent_invocation_id}`);const key=`${date5.getUTCFullYear()}/${String(date5.getUTCMonth()+1).padStart(2,"0")}`;byMonth.set(key,[...byMonth.get(key)??[],summary])}for(const[key,values]of byMonth)await writeMonth(filesystem,key,values);return{summary_count:summaries.length,month_count:byMonth.size}}async function queueWorkspaceCompaction(workspace,work2){const previous=workspaceCompactionQueues.get(workspace)??Promise.resolve();let release;const current=new Promise(resolve32=>{release=resolve32});const queued=previous.catch(()=>void 0).then(()=>current);workspaceCompactionQueues.set(workspace,queued);await previous.catch(()=>void 0);try{return await work2()}finally{release?.();if(workspaceCompactionQueues.get(workspace)===queued){workspaceCompactionQueues.delete(workspace)}}}async function writeMonth(filesystem,key,summaries){const values=[...summaries].sort((left,right)=>left.occurred_at.localeCompare(right.occurred_at)||left.agent_invocation_id.localeCompare(right.agent_invocation_id));const[year,month]=key.split("/");if(year===void 0||month===void 0)throw new Error(`Invalid telemetry month key: ${key}`);const writerId=await resolveWriterId(filesystem);const base=`.agents/records/telemetry/${year}/${month}/writers/${writerId}`;const content=`${values.map(summary=>JSON.stringify(summary)).join("\n")}
3596
3596
  `;const chunkPath=`${base}/chunks/${digest7(content)}.jsonl`;const compact=buildMonthlyManifest(values);const sourceLags=values.map(summary=>summary.time.source_lag_ms);const knownSourceLags=sourceLags.filter(lag=>lag!==null);const dimensions={providers:unique(values.flatMap(summary=>summary.usage_segments.flatMap(segment2=>segment2.provider===null?[]:[segment2.provider]))),models:unique(values.flatMap(summary=>summary.usage_segments.flatMap(segment2=>segment2.model===null?[]:[segment2.model]))),zaip_agents:unique(values.flatMap(summary=>summary.zaip_agent===null?[]:[summary.zaip_agent])),phases:unique(values.flatMap(summary=>summary.phase===null?[]:[summary.phase])),purposes:unique(values.flatMap(summary=>summary.purpose===null?[]:[summary.purpose])),statuses:unique(values.flatMap(summary=>summary.status===null?[]:[summary.status])),executions:unique(values.flatMap(summary=>summary.execution_id===null?[]:[summary.execution_id])),tasks:unique(values.flatMap(summary=>summary.task_id===null?[]:[summary.task_id])),specs:unique(values.flatMap(summary=>summary.spec_id===null?[]:[summary.spec_id])),prds:unique(values.flatMap(summary=>summary.prd_id===null?[]:[summary.prd_id])),changes:unique(values.flatMap(summary=>summary.change_id===null?[]:[summary.change_id]))};const{schema_version:_compactSchemaVersion,manifest_hash:_compactManifestHash,...compactFields}=compact;const manifestUnsigned={schema_version:1,period:{year:Number(year),month:Number(month)},...compactFields,chunks:[{path:chunkPath,from:values[0]?.occurred_at??null,to:values.at(-1)?.occurred_at??null,content_sha256:digest7(content),summary_count:values.length,summary_hashes:values.map(summary=>summary.summary_hash),dimensions}],source_latest_at:values.map(summary=>summary.time.source_latest_at).sort().at(-1)??null,lag_ms:sourceLags.length===0||knownSourceLags.length!==sourceLags.length?null:Math.max(...knownSourceLags)};const manifest={...manifestUnsigned,manifest_hash:digest7(JSON.stringify(manifestUnsigned))};try{await filesystem.writeTextAtomicExclusive(chunkPath,content)}catch(error51){if(!isNodeError9(error51)||error51.code!=="EEXIST")throw error51;if(await filesystem.readText(chunkPath)!==content){throw new Error(`Telemetry chunk ownership conflict: ${chunkPath}`)}}await filesystem.writeTextAtomic(`${base}/manifest.json`,`${JSON.stringify(manifest,null,2)}
3597
3597
  `);await collectSubsumedChunks(filesystem,base,chunkPath,values)}async function collectSubsumedChunks(filesystem,base,activeChunkPath,activeSummaries){const activeHashes=new Map(activeSummaries.map(summary=>[summary.agent_invocation_id,summary.summary_hash]));const chunkPaths=await filesystem.listFiles(`${base}/chunks`,".jsonl");for(const chunkPath of chunkPaths){if(chunkPath===activeChunkPath)continue;const content=await filesystem.readText(chunkPath);try{const filenameDigest=chunkPath.slice(chunkPath.lastIndexOf("/")+1,-".jsonl".length);if(!/^[a-f0-9]{64}$/.test(filenameDigest)||digest7(content)!==filenameDigest){continue}const summaries=content.split(/\r?\n/).filter(Boolean).map(line=>JSON.parse(line));if(summaries.length===0||!summaries.every(summary=>isCanonicalInvocationSummary(summary)&&activeHashes.get(summary.agent_invocation_id)===summary.summary_hash)){continue}}catch{continue}await filesystem.removeFile(chunkPath)}}function unique(values){return[...new Set(values)].sort()}function digest7(value){return createHash46("sha256").update(value).digest("hex")}var workspaceCompactionQueues;var init_codex_telemetry_compaction=__esm({"src/codex-telemetry-compaction.ts"(){"use strict";init_src4();init_src5();init_codex_telemetry_compaction_lock();init_codex_telemetry_writer_id();workspaceCompactionQueues=new Map}});function isCodexTelemetryClient(client){return["codex","codex-desktop","codex-subagent"].includes(client)}function telemetrySourceThreadId(current,allRuns){const runsById=new Map(allRuns.map(fold=>[fold.run.run_id,fold]));let run=current.run;const visited=new Set;while(run.parent_run_id!==null&&!visited.has(run.run_id)){visited.add(run.run_id);const parent=runsById.get(run.parent_run_id);if(parent===void 0)break;run=parent.run}return run.client_thread_id??current.run.client_thread_id??null}function telemetrySource(current,allRuns){const rootThreadId=telemetrySourceThreadId(current,allRuns);if(current.run.client==="codex-subagent"){const identity2=current.run.client_thread_id??null;const nativeThread=identity2!==null&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(identity2);return{agentPath:nativeThread?null:identity2,parentThreadId:null,threadId:nativeThread?identity2:null,turnId:current.run.client_turn_id??null}}return{agentPath:null,parentThreadId:null,threadId:rootThreadId,turnId:current.run.client_turn_id??null}}var init_codex_telemetry_source=__esm({"src/codex-telemetry-source.ts"(){"use strict"}});import{createHash as createHash47}from"node:crypto";async function recordUnavailableCodexTelemetryToSpool(current,filesystem,status,capturedAt=new Date().toISOString()){if(!isCodexTelemetryClient(current.run.client))return null;const correlation=codexTelemetryCorrelationFromRun(current.run);if(correlation===null)return null;return appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"terminal",source:"unavailable",source_event_key:`run:${current.run.run_id}:terminal:unavailable`,source_occurred_at:null,captured_at:capturedAt,coverage:"unavailable",tokens:{input:null,cached_input:null,cache_write_input:null,output:null,reasoning:null,total:null,source:"unavailable"},provider:null,model:null,runtime:{reasoning_effort:null,service_tier:null},status,latency_ms:null,context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}})}function sumObservedUsage(values){const observed=values.filter(value=>value!==null);const sum=component=>{let total=0;for(const usage of observed){const value=usage[component];if(value===null||value===void 0)return null;total+=value}return total};return{input:sum("input"),cached_input:sum("cached_input"),cache_write_input:sum("cache_write_input"),output:sum("output"),reasoning:sum("reasoning"),total:sum("total"),source:"provider_reported"}}function commonObservedValue(values){const observed=[...new Set(values.filter(value=>value!==null))];return observed.length===1?observed[0]??null:null}function latestSourceTimestamp(events){return events.map(event=>event.event.source_occurred_at).filter(value=>value!==null).sort().at(-1)??null}function modelCallId(sourceCallKey){return`MCALL-${digest8(sourceCallKey)}`}function providerInvocationId(sourceCallKey){return`INV-CODEX-${digest8(sourceCallKey)}`}function elapsedMilliseconds(startedAt,finishedAt){const started=Date.parse(startedAt??"");const finished=Date.parse(finishedAt??"");return Number.isFinite(started)&&Number.isFinite(finished)?Math.max(0,finished-started):null}function hasObservedUsage(current){return current.effective_usage_records.some(record3=>record3.tokens.source!=="unavailable")}function unavailableUsageEventId(current){return current.effective_usage_records.findLast(record3=>record3.tokens.source==="unavailable")?.event_id??null}function observedUsageDelta(cumulative,previous){const previousTotal=component=>{let total=0;for(const usage of previous){const value=usage[component];if(value===null||value===void 0)return null;total+=value}return total};const delta=component=>{const observed=cumulative[component];if(observed===null||observed===void 0)return null;const attributed=previousTotal(component);return attributed===null?null:Math.max(0,observed-attributed)};return{input:delta("input"),cached_input:delta("cached_input"),cache_write_input:delta("cache_write_input"),output:delta("output"),reasoning:delta("reasoning"),total:delta("total"),source:cumulative.source}}function latestPhase(current){const latest=current.records.findLast(record3=>"phase"in record3);return latest?.phase??"conversation"}function digest8(sourceCallKey){return createHash47("sha256").update(sourceCallKey).digest("hex").slice(0,32)}var init_codex_telemetry_runtime=__esm({"src/codex-telemetry-runtime.ts"(){"use strict";init_src5();init_codex_telemetry_source()}});function shouldAppendFallbackModelCall(records,sourceCallKey){const callId=modelCallId(sourceCallKey);return!records.some(record3=>record3.source_call_key===sourceCallKey||record3.call_id===callId)}async function collectAvailableNativeUsage(current,composition,filesystem,recordNative){return withPreparedCodexTelemetry(filesystem,async(snapshot,compact)=>{const recorded=await collectNativeUsageFromSnapshot(current,composition,snapshot,recordNative);if(recorded!==null)await compact();return recorded})}async function collectNativeUsageFromSnapshot(current,composition,snapshot,recordNative){const events=snapshot.filter(event=>event.event.source==="codex_app_server"&&event.event.correlation.run_id===current.run.run_id);return events.some(event=>["response_completed","usage_updated","error","turn_completed"].includes(event.event.stream_boundary??""))?recordNative(current,composition,events):null}async function exactTelemetrySource(current,composition){const ancestors=[current];if(current.run.client!=="codex-subagent"){const visited=new Set([current.run.run_id]);let parentId=current.run.parent_run_id;while(parentId!==null&&!visited.has(parentId)){visited.add(parentId);let parent;try{parent=await composition.runs.read(parentId)}catch(error51){if(error51 instanceof Error&&error51.message.startsWith("Run V2 not found:"))break;throw error51}ancestors.push(parent);parentId=parent.run.parent_run_id}}return telemetrySource(current,ancestors)}function rootCorrelationCandidates(correlations,threadId){const roots2=correlations.filter(item=>item.client!=="codex-subagent");const exact=roots2.filter(item=>item.thread_id===threadId);return exact.length>0?exact:roots2.filter(item=>item.thread_id===null)}function parseCodexAppServerNotificationStream(content){const normalized=content.trim();if(normalized.length===0)return[];if(normalized.startsWith("[")){const parsed=JSON.parse(normalized);if(!Array.isArray(parsed))throw new Error("Codex app-server event stream must be an array");return parsed}return normalized.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map(line=>JSON.parse(line))}var init_codex_telemetry_preparation=__esm({"src/codex-telemetry-preparation.ts"(){"use strict";init_codex_telemetry_compaction();init_codex_telemetry_runtime();init_codex_telemetry_source()}});import{createHash as createHash48}from"node:crypto";async function ingestCodexAppServerNotifications(filesystem,notifications,capturedAt=new Date().toISOString()){const persisted=[];for(const notification of notifications){const event=await ingestCodexAppServerNotification(filesystem,notification,capturedAt);if(event!==null)persisted.push(event)}await compactPendingCodexTelemetry(filesystem);return persisted}async function ingestCodexAppServerNotification(filesystem,notification,capturedAt=new Date().toISOString()){const sanitized=sanitizeAppServerNotification(notification,capturedAt);if(sanitized===null)return null;const correlations=await listCodexTelemetryCorrelations(filesystem);const sameTurn=correlations.filter(item=>item.turn_id===sanitized.turnId);const candidates=sanitized.agentPath===null?rootCorrelationCandidates(sameTurn,sanitized.threadId):sameTurn.filter(item=>item.client==="codex-subagent"&&item.agent_path===sanitized.agentPath);if(candidates.length>1){throw new Error(`Ambiguous Codex app-server correlation for turn ${sanitized.turnId}`)}if(candidates[0]===void 0){await quarantineCodexAppServerNotification(filesystem,sanitized);return null}return appendCodexTelemetrySpoolEvent(filesystem,{correlation:candidates[0],...sanitized.event})}async function quarantineCodexAppServerNotification(filesystem,input){const digest14=hostDigest(input.event.source_event_key);const unsigned={schema_version:1,event_id:`QEVT-${digest14}`,thread_id:input.threadId,turn_id:input.turnId,agent_path:input.agentPath,event:input.event};const serialized=`${JSON.stringify({...unsigned,checksum_sha256:hostDigest(JSON.stringify(unsigned))})}
3598
- `;if(Buffer.byteLength(serialized,"utf8")>64*1024)throw new Error("Unmatched Codex telemetry envelope exceeds the 64 KiB sanitized limit");try{await filesystem.writeTextAtomicExclusive(`.local/codex-telemetry-spool/v1/unmatched/${digest14.slice(0,2)}/${digest14}.json`,serialized)}catch(error51){if(!(error51 instanceof Error&&"code"in error51&&error51.code==="EEXIST"))throw error51}}function sanitizeAppServerNotification(input,capturedAt){const notification=hostObject(input,"Codex app-server notification");const method=String(notification.method);if(!["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"].includes(method))return null;const params=hostObject(notification.params,`${method} params`);const threadId=hostString(params.threadId,`${method} threadId`);const rawAgentPath=params.agentPath??params.agent_path;const agentPath=rawAgentPath===void 0?null:hostString(rawAgentPath,`${method} agentPath`);const occurredAt=hostTimestamp(notification.emittedAtMs);const wrap=(turnId2,event)=>({threadId,turnId:turnId2,agentPath,event:{source:"codex_app_server",source_occurred_at:occurredAt,captured_at:capturedAt,coverage:"complete",provider:null,model:null,runtime:{reasoning_effort:null,service_tier:null},latency_ms:null,context_stats:null,...event}});if(method==="item/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);const item=hostObject(params.item,`${method} item`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"item_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:item:${hostString(item.id,`${method} item id`)}`,"item"),source_occurred_at:hostTimestamp(params.completedAtMs)??occurredAt,tokens:null,status:null,discarded_counts:discardedItem(String(item.type??""),item)})}if(method==="rawResponse/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"response_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:raw-response:${hostString(params.responseId,`${method} responseId`)}`,"response"),tokens:params.usage===null?null:hostTokens(params.usage,method),status:null,discarded_counts:{...emptyDiscarded(),response_text:Number(typeof params.output==="string")}})}if(method==="thread/tokenUsage/updated"){const turnId2=hostString(params.turnId,`${method} turnId`);const tokens2=hostTokens(hostObject(params.tokenUsage,`${method} tokenUsage`).total,method);const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify(tokens2)).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"usage",source_method:method,stream_boundary:"usage_updated",source_event_key:hostSourceKey(`${threadId}:${turnId2}:token-usage:${suffix}`,"usage"),tokens:tokens2,status:null,discarded_counts:emptyDiscarded()})}if(method==="error"){const turnId2=hostString(params.turnId,`${method} turnId`);const error52=isHostObject(params.error)?params.error:{};const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify([params.willRetry===true,error52.codexErrorInfo??null])).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"error",source_method:method,stream_boundary:"error",source_event_key:hostSourceKey(`${threadId}:${turnId2}:error:${suffix}`,"error"),tokens:null,status:params.willRetry===true?null:"failed",will_retry:params.willRetry===true,discarded_counts:{...emptyDiscarded(),secrets:Number(typeof error52.message==="string")+Number(typeof error52.additionalDetails==="string")}})}const turn=hostObject(params.turn,"turn/completed turn");const turnId=hostString(turn.id,"turn/completed turn id");if(!["completed","failed","interrupted"].includes(String(turn.status)))throw new Error(`turn/completed has non-terminal status: ${String(turn.status)}`);const discarded=(Array.isArray(turn.items)?turn.items.filter(isHostObject):[]).map(item=>discardedItem(String(item.type??""),item)).reduce(addDiscarded,emptyDiscarded());const error51=isHostObject(turn.error)?turn.error:{};return wrap(turnId,{event_kind:"terminal",source_method:"turn/completed",stream_boundary:"turn_completed",source_event_key:hostSourceKey(`${threadId}:${turnId}:terminal`,"terminal"),source_occurred_at:hostTimestamp(typeof turn.completedAt==="number"?turn.completedAt*1e3:turn.completedAt)??occurredAt,tokens:null,status:turn.status==="interrupted"?"cancelled":turn.status,latency_ms:Number.isSafeInteger(turn.durationMs)&&Number(turn.durationMs)>=0?Number(turn.durationMs):null,discarded_counts:{...discarded,secrets:discarded.secrets+Number(typeof error51.message==="string")+Number(typeof error51.additionalDetails==="string")}})}function hostObject(value,label){if(!isHostObject(value))throw new Error(`${label} must be an object`);return value}function hostString(value,label){if(typeof value!=="string"||value.length===0)throw new Error(`${label} must be a non-empty string`);return value}function hostCount(value,label){if(!Number.isSafeInteger(value)||Number(value)<0)throw new Error(`${label} must be a non-negative safe integer`);return Number(value)}function hostTokens(value,label){const usage=hostObject(value,`${label} usage`);const input=hostCount(usage.inputTokens,`${label} inputTokens`);const cacheWriteInput=usage.cacheWriteInputTokens===void 0?null:hostCount(usage.cacheWriteInputTokens,`${label} cacheWriteInputTokens`);if(cacheWriteInput!==null&&cacheWriteInput>input){throw new Error(`${label} cacheWriteInputTokens cannot exceed inputTokens`)}return{input,cached_input:hostCount(usage.cachedInputTokens,`${label} cachedInputTokens`),cache_write_input:cacheWriteInput,output:hostCount(usage.outputTokens,`${label} outputTokens`),reasoning:hostCount(usage.reasoningOutputTokens,`${label} reasoningOutputTokens`),total:hostCount(usage.totalTokens,`${label} totalTokens`),source:"provider_reported"}}var emptyDiscarded,addDiscarded,discardedItem,isHostObject,hostTimestamp,hostDigest,hostSourceKey;var init_codex_app_server_notifications=__esm({"src/codex-app-server-notifications.ts"(){"use strict";init_src5();init_codex_telemetry_compaction();init_codex_telemetry_preparation();emptyDiscarded=()=>({prompt:0,response_text:0,reasoning:0,secrets:0});addDiscarded=(left,right)=>({prompt:left.prompt+right.prompt,response_text:left.response_text+right.response_text,reasoning:left.reasoning+right.reasoning,secrets:left.secrets+right.secrets});discardedItem=(type,item)=>({prompt:Number(["userMessage","hookPrompt","function_call","custom_tool_call"].includes(type)),response_text:Number(["agentMessage","plan","message","agent_message"].includes(type)),reasoning:Number(type==="reasoning"),secrets:Number(typeof item.encrypted_content==="string")+Number(item.internal_chat_message_metadata_passthrough!==void 0)});isHostObject=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);hostTimestamp=value=>typeof value==="number"&&Number.isFinite(value)&&value>=0?new Date(value).toISOString():null;hostDigest=value=>createHash48("sha256").update(value).digest("hex");hostSourceKey=(value,prefix)=>value.length<=500?value:`${prefix}:${hostDigest(value)}`}});function aggregateEstimatedCallCosts(estimates,fxRate){const sum=values=>{const known2=values.filter(value=>value!==null);if(known2.length!==values.length)return null;return Math.round(known2.reduce((total,value)=>total+value,0)*1e6)/1e6};const usd=sum(estimates.map(estimate=>estimate.estimated_usd));return{usd,brl:usd===null||fxRate===null?null:Math.round(usd*fxRate.rate*1e6)/1e6,fx_rate:fxRate?.rate??null}}var init_codex_telemetry_call_costs=__esm({"src/codex-telemetry-call-costs.ts"(){"use strict"}});function fallbackCallIdentity(sourceCallKey){return[sourceCallKey,modelCallId(sourceCallKey)]}function hasNoObservedTokenDelta(tokens2){return tokens2.total===0&&[tokens2.input,tokens2.cached_input,tokens2.cache_write_input,tokens2.output,tokens2.reasoning].every(value=>value==null||value===0)}var init_codex_telemetry_call_identity=__esm({"src/codex-telemetry-call-identity.ts"(){"use strict";init_codex_telemetry_runtime()}});import{AsyncLocalStorage}from"node:async_hooks";var capturePass;var init_codex_telemetry_capture_pass=__esm({"src/codex-telemetry-capture-pass.ts"(){"use strict";capturePass=new AsyncLocalStorage}});function fallbackUsageLoops(candidate,loops,previous){if(previous.length===0)return loops;const attributed=sumObservedUsage(previous);for(let index=0;index<=loops.length;index+=1){if(sameUsage(aggregateSegmentUsage({...candidate,loops:loops.slice(0,index)}),attributed))return loops.slice(index)}return[]}function sameUsage(left,right){return left.input===right.input&&left.cached_input===right.cached_input&&left.cache_write_input===right.cache_write_input&&left.output===right.output&&left.reasoning===right.reasoning&&left.total===right.total}function validatedTranscriptEnvironmentPath(){const value=process.env.CODEX_TRANSCRIPT_PATH;if(typeof value!=="string")return null;const normalized=value.trim();return normalized.length>0&&normalized.length<=4096?normalized:null}var init_codex_telemetry_fallback_usage=__esm({"src/codex-telemetry-fallback-usage.ts"(){"use strict";init_src4();init_codex_telemetry_runtime()}});async function hookTrackingEnabled(filesystem){if(process.env.ZAIP_HOOK_TRACKING_ENABLED==="false")return false;try{return(await loadWorkspaceLayout(filesystem)).projectConfig?.tracking.enabled===true}catch{return false}}var init_hook_tracking_policy=__esm({"src/hook-tracking-policy.ts"(){"use strict";init_src()}});async function recordNativeCodexUsage(current,composition,events){const exactCalls=events.filter(event=>event.event.stream_boundary==="response_completed"&&event.event.tokens!==null);const latestCumulative=events.findLast(event=>event.event.stream_boundary==="usage_updated"&&event.event.tokens!==null);const terminal=events.findLast(event=>event.event.stream_boundary==="turn_completed"||event.event.stream_boundary==="error"&&event.event.will_retry!==true);const usageEvents=exactCalls.length>0?exactCalls:latestCumulative?[latestCumulative]:[];if(usageEvents.length===0&&terminal===void 0)return current;let fresh=current;let sequence=current.records.length+1;const agentInvocationId=current.run.agent_invocation_id??`AINV-${current.run.run_id.slice("RUN-".length)}`;for(const call of exactCalls){const event=call.event;if(event.tokens===null)continue;const coverage2=terminal===void 0?"partial":"complete";const existing=fresh.model_call_records.find(record3=>record3.source_call_key===event.source_event_key);if(existing===void 0||existing.coverage==="partial"&&coverage2==="complete"){await composition.runs.appendRecord(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:event.captured_at,type:"model.call.observed",call_id:modelCallId(event.source_event_key),agent_invocation_id:agentInvocationId,coverage:coverage2,tokens:event.tokens,cost:{usd:null,brl:null},provider:event.provider,model:event.model,source_call_key:event.source_event_key,...event.source_occurred_at===null?{}:{source_occurred_at:event.source_occurred_at},runtime:event.runtime}));fresh=await composition.runs.read(current.run.run_id)}}const sourceSegmentKey=`codex-app-server:${current.run.run_id}`;if(usageEvents.length>0&&!fresh.effective_usage_records.some(record3=>record3.source_segment_key===sourceSegmentKey)){const tokens2=sumObservedUsage(usageEvents.map(event=>event.event.tokens));await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestPhase(current),activity_kind:"implementation",classification_source:"current_context",tokens:tokens2,cost:{usd:null,brl:null},provider:commonObservedValue(usageEvents.map(event=>event.event.provider)),model:commonObservedValue(usageEvents.map(event=>event.event.model)),source_segment_key:sourceSegmentKey,runtime:{reasoning_effort:commonObservedValue(usageEvents.map(event=>event.event.runtime.reasoning_effort)),service_tier:commonObservedValue(usageEvents.map(event=>event.event.runtime.service_tier))},supersedes_event_id:unavailableUsageEventId(current),...latestSourceTimestamp(usageEvents)===null?{}:{source_occurred_at:latestSourceTimestamp(usageEvents)}}));fresh=await composition.runs.read(current.run.run_id)}if(terminal===void 0||terminal.event.status===null)return fresh;const callKeys=exactCalls.length>0?exactCalls.map(call=>call.event.source_event_key):[terminal.event.source_event_key];for(const callKey of callKeys){const invocationId2=providerInvocationId(callKey);if(!fresh.model_selection_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(modelSelectionRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"model.selection.recorded",invocation_id:invocationId2,requested:{model:current.run.model,reasoning_effort:current.run.reasoning_effort??null,velocity:"standard"},selection:{source:"execution-override",policy_version:1,reasons:["host-run-header"]}}));fresh=await composition.runs.read(current.run.run_id)}if(!fresh.provider_invocation_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(providerInvocationFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"provider.invocation.finished",invocation_id:invocationId2,status:terminal.event.status,effective:{provider:terminal.event.provider,model:terminal.event.model,reasoning_effort:terminal.event.runtime.reasoning_effort,service_tier:terminal.event.runtime.service_tier},latency_ms:terminal.event.latency_ms}));fresh=await composition.runs.read(current.run.run_id)}}return fresh}var init_codex_telemetry_native=__esm({"src/codex-telemetry-native.ts"(){"use strict";init_src5();init_codex_telemetry_runtime()}});async function recordCodexTelemetryBatch(folds,composition,filesystem,finder=findLatestCodexSegment,options={}){if(folds.length===0)return[];if(!await hookTrackingEnabled(filesystem))return[...folds];const proposals=new Map;const transcriptPath=validatedTranscriptEnvironmentPath();for(const fold of folds){if(fold.finished!==null&&unavailableUsageEventId(fold)===null)continue;const source=await exactTelemetrySource(fold,composition);const key=JSON.stringify(source);if(source.turnId!==null&&!proposals.has(key))proposals.set(key,await finder(filesystem.root,new Set,{...source,startedAfter:fold.run.occurred_at,...transcriptPath===null?{}:{transcriptPath,requireTaskComplete:true}}))}return composition.runs.withUsageAttributionLock(async()=>{const native=await withPreparedCodexTelemetry(filesystem,async events=>events,options);const pass={runs:composition.runs,filesystem,native,compact:false};return capturePass.run(pass,async()=>{const results=[];try{for(const fold of folds){const current=await recordCodexTelemetryIfAvailable(fold,composition,filesystem,null,[],async(_root,_keys,source)=>proposals.get(JSON.stringify({agentPath:source?.agentPath??null,parentThreadId:source?.parentThreadId??null,threadId:source?.threadId??null,turnId:source?.turnId??null}))??null);results.push(current);if(pass.owners!==void 0)pass.owners=pass.owners.map(owner=>owner.run.run_id===current.run.run_id?current:owner)}return results}finally{if(pass.compact)await compactPendingCodexTelemetry(filesystem)}})})}async function recordCodexTelemetryIfAvailable(current,composition,filesystem,sourceOverride=null,appServerNotifications=[],fallbackSegmentFinder=findLatestCodexSegment){if(!await hookTrackingEnabled(filesystem))return current;if(!isCodexTelemetryClient(current.run.client)||current.run.client_thread_id===null&&current.run.client_turn_id===null){return current}const transcriptPath=validatedTranscriptEnvironmentPath();const pass=capturePass.getStore();const batch=pass?.runs===composition.runs&&pass.filesystem===filesystem?pass:void 0;const lock2=operation=>batch===void 0?composition.runs.withUsageAttributionLock(operation):operation();const collect=fresh=>batch===void 0?collectAvailableNativeUsage(fresh,composition,filesystem,recordNativeCodexUsage):collectNativeUsageFromSnapshot(fresh,composition,batch.native,recordNativeCodexUsage);const preparation=await lock2(async()=>{const fresh=await composition.runs.read(current.run.run_id);if(appServerNotifications.length>0){await ingestCodexAppServerNotifications(filesystem,appServerNotifications)}const observed=await collect(fresh);if(batch!==void 0&&observed!==null)batch.compact=true;if(observed!==null)return{kind:"done",fold:observed};if(fresh.finished!==null&&unavailableUsageEventId(fresh)===null)return{kind:"done",fold:fresh};if(sourceOverride===null&&fresh.run.client_turn_id===null)return{kind:"done",fold:fresh};const source=sourceOverride??await exactTelemetrySource(fresh,composition);if(source.turnId===null)return{kind:"done",fold:fresh};return{kind:"fallback",fold:fresh,source}});if(preparation.kind==="done")return preparation.fold;const candidate=await fallbackSegmentFinder(filesystem.root,new Set,{startedAfter:preparation.fold.run.occurred_at,...preparation.source,...transcriptPath===null?{}:{transcriptPath,requireTaskComplete:true}});return lock2(async()=>{const freshCurrent=await composition.runs.read(current.run.run_id);const observed=await collect(freshCurrent);if(batch!==void 0&&observed!==null)batch.compact=true;if(observed!==null)return observed;const source=sourceOverride??await exactTelemetrySource(freshCurrent,composition);const exactTurn=source.turnId;const timestamp13=Date.parse(candidate?.finishedAt??candidate?.loops.at(-1)?.timestamp??"");if(candidate===null||!Number.isFinite(timestamp13)||exactTurn===null||candidate.turnId!==exactTurn||JSON.stringify(source)!==JSON.stringify(preparation.source))return freshCurrent;const postTerminalPhase=freshCurrent.finished?.phase??null;const postTerminal=postTerminalPhase!==null;const supersededUnavailableUsageId=unavailableUsageEventId(freshCurrent);if(postTerminal&&supersededUnavailableUsageId===null)return freshCurrent;const candidateLoops=Array.from(new Map(candidate.loops.map(loop=>[`${candidate.segmentKey}:loop:${loop.cycleIndex}`,loop])).values());const newCandidateLoops=candidateLoops.filter(loop=>shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`));const localPrevious=freshCurrent.effective_usage_records.filter(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true);if(localPrevious.some(record3=>record3.source_segment_key===candidate.segmentKey))return freshCurrent;const localDelta=observedUsageDelta(aggregateSegmentUsage({...candidate,loops:candidateLoops}),localPrevious.map(record3=>record3.tokens));if(candidate.finishedAt===null&&newCandidateLoops.length===0&&hasNoObservedTokenDelta(localDelta))return freshCurrent;const allRuns=batch?.owners??await composition.runs.list();if(batch!==void 0)batch.owners=allRuns;const existingOwner=allRuns.find(fold=>fold.run.run_id!==freshCurrent.run.run_id&&fold.effective_usage_records.some(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true));if(existingOwner!==void 0)return freshCurrent;const model=candidate.model??freshCurrent.run.model;const provider=inferProvider(model,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const correlation=codexTelemetryCorrelationFromRun(freshCurrent.run);if(correlation===null)return freshCurrent;const capturedAt=new Date().toISOString();const pricing=new PricingRepository(filesystem);const catalog=await pricing.readCatalog();const fxRate=await pricing.readLatestFxRate();const spooledLoops=[];if(batch!==void 0&&(newCandidateLoops.length>0||candidate.finishedAt!==null))batch.compact=true;for(const loop of candidateLoops){if(!shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`))continue;const loopModel=loop.model??model;const loopProvider=inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const historical_cost=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null});spooledLoops.push(await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"usage",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:loop:${loop.cycleIndex}`,source_occurred_at:loop.timestamp,captured_at:capturedAt,coverage:"partial",tokens:loop.usage,provider:loopProvider,model:loopModel,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:null,latency_ms:null,historical_cost,context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}}))}if(candidate.finishedAt!==null){await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"terminal",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:terminal`,source_occurred_at:candidate.finishedAt,captured_at:capturedAt,coverage:"partial",tokens:null,provider,model,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:"completed",latency_ms:elapsedMilliseconds(candidate.startedAt,candidate.finishedAt),context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}})}const cumulative=aggregateSegmentUsage({...candidate,loops:candidateLoops});const previous=allRuns.filter(fold=>fold.run.run_id===freshCurrent.run.run_id||exactTurn!==null&&fold.run.client_turn_id===exactTurn).flatMap(fold=>fold.effective_usage_records).filter(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true);const usageLoops=fallbackUsageLoops(candidate,candidateLoops,previous.map(record3=>record3.tokens));if(candidate.finishedAt!==null&&previous.some(record3=>record3.source_segment_key===candidate.segmentKey))return freshCurrent;const tokens2=observedUsageDelta(cumulative,previous.map(record3=>record3.tokens));const usageSourceSegmentKey=candidate.finishedAt===null?`${candidate.segmentKey}@active:${hostDigest(JSON.stringify(cumulative))}`:candidate.segmentKey;const zeroTokenDelta=hasNoObservedTokenDelta(tokens2);const activeUsageToClose=candidate.finishedAt===null||!zeroTokenDelta?null:previous.findLast(record3=>record3.source_segment_key?.startsWith(`${candidate.segmentKey}@active:`)===true)??null;if(zeroTokenDelta&&activeUsageToClose===null){return freshCurrent}if(candidate.finishedAt===null&&usageLoops.length===0)return freshCurrent;const estimated=aggregateEstimatedCallCosts(usageLoops.map(loop=>{const loopModel=loop.model??model;return estimateUsageCost({provider:inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent),model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null})}),fxRate);const agentInvocationId=freshCurrent.run.agent_invocation_id??`AINV-${freshCurrent.run.run_id.slice("RUN-".length)}`;let sequence=freshCurrent.records.length+1;const fallbackCallIdentities=new Set(freshCurrent.model_call_records.flatMap(record3=>[record3.source_call_key,record3.call_id].filter(value=>typeof value==="string")));const pendingRecords=[];for(const spooled of spooledLoops){const loop=spooled.event;if(loop.tokens===null)continue;const loopModel=loop.model??freshCurrent.run.model;const loopProvider=inferProvider(loopModel,loop.provider??freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const loopEstimated=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.tokens,catalog,fxRate,serviceTier:candidate.serviceTier??null});const sourceCallKey=loop.source_event_key;const identities=fallbackCallIdentity(sourceCallKey);if(postTerminal||!shouldAppendFallbackModelCall(freshCurrent.model_call_records,sourceCallKey)||identities.some(identity2=>fallbackCallIdentities.has(identity2))){continue}pendingRecords.push(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"model.call.observed",call_id:modelCallId(sourceCallKey),agent_invocation_id:agentInvocationId,coverage:"partial",tokens:loop.tokens,cost:{usd:loopEstimated.estimated_usd,brl:loopEstimated.estimated_brl,fx_rate:loopEstimated.fx_rate},provider:loopProvider,model:loopModel,source_call_key:sourceCallKey,...loop.source_occurred_at===null?{}:{source_occurred_at:loop.source_occurred_at},runtime:loop.runtime}));for(const identity2 of identities)fallbackCallIdentities.add(identity2)}const usage=usageRecordedV2Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:postTerminal?postTerminalPhase:latestPhase(freshCurrent),activity_kind:postTerminal?"retrospective_local_remeasurement":"implementation",classification_source:"current_context",tokens:activeUsageToClose?.tokens??tokens2,cost:activeUsageToClose!==null?activeUsageToClose.cost:{usd:estimated.usd,brl:estimated.brl,fx_rate:estimated.fx_rate},provider,model,source_segment_key:usageSourceSegmentKey,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},supersedes_event_id:activeUsageToClose?.event_id??supersededUnavailableUsageId,...postTerminal?{retrospective_correction:true}:{},source_occurred_at:candidate.finishedAt??candidate.startedAt??void 0,source_started_at:candidate.startedAt??void 0,source_finished_at:candidate.finishedAt??void 0});pendingRecords.push(usage);await composition.runs.appendRecords(pendingRecords);if(batch===void 0)await compactPendingCodexTelemetry(filesystem);else batch.compact=true;return composition.runs.read(freshCurrent.run.run_id)})}var init_record_codex_telemetry=__esm({"src/record-codex-telemetry.ts"(){"use strict";init_src4();init_src5();init_codex_app_server_notifications();init_codex_telemetry_call_costs();init_codex_telemetry_call_identity();init_codex_telemetry_capture_pass();init_codex_telemetry_compaction();init_codex_telemetry_fallback_usage();init_hook_tracking_policy();init_codex_app_server_notifications();init_codex_telemetry_native();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source()}});async function openThreadIntakes(composition,client,clientThreadId,currentTurnId,candidates){if(clientThreadId===null)return[];const availableRuns=candidates??await composition.runs.list();return availableRuns.filter(fold=>fold.finished===null&&fold.run.client===client&&fold.run.client_thread_id===clientThreadId&&fold.run.parent_run_id===null&&fold.run.intake!=null&&!runV2RequiresFinalizer(fold.run)&&descendantRuns(fold.run.run_id,availableRuns).length===0&&fold.run.client_turn_id!==currentTurnId)}async function finishOpenThreadIntakes(openIntakes2,composition,filesystem,parsed,lifecycle){const settled=[];for(const intake2 of openIntakes2){const candidateRuns=await composition.runs.list();if(descendantRuns(intake2.run.run_id,candidateRuns).length>0||activeDescendantRuns(intake2.run.run_id,candidateRuns).length>0){continue}let current=intake2;current=await recordCodexTelemetryIfAvailable(current,composition,filesystem,null,await codexAppServerNotifications(parsed,filesystem));if(current.effective_usage_records.length===0){await recordUnavailableCodexTelemetryToSpool(current,filesystem,"completed");await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,current.records.length+1),run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"completed"}));const run=await composition.runs.read(current.run.run_id);settled.push({run,reconciliation:await reconcileFinishedRunLifecycle(run,composition,lifecycle,{candidateRuns})})}return settled}function settledIntakesForView(settled,view){if(view==="full")return settled;return settled.map(({run,reconciliation})=>({run_id:run.run.run_id,status:run.status,phase:latestRunV2Phase(run.records),execution_id:run.run.execution_id,task_id:run.run.task_id,change_id:run.run.change_id,record_count:run.records.length,usage_record_count:run.effective_usage_records.length,model_call_count:run.model_call_records.length,reconciliation:{status:reconciliation.status,outcome:reconciliation.outcome,task_count:reconciliation.tasks.length,change_count:reconciliation.changes.length,execution_count:reconciliation.executions.length,spec_count:reconciliation.specs.length,prd_count:reconciliation.prds.length}}))}async function codexAppServerNotifications(parsed,filesystem){const path=parsed.options["codex-app-server-events"];return path===void 0?[]:parseCodexAppServerNotificationStream(await filesystem.readText(path))}function runMatchesTarget(fold,target){return target.taskId!==void 0&&fold.run.task_id===target.taskId||target.specId!==void 0&&fold.run.spec_id===target.specId||target.prdId!==void 0&&fold.run.prd_id===target.prdId}async function recordContextPackUsage(runId,initialPackTokens,composition){const current=await composition.runs.read(runId);if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${runId}`);const sequence=current.records.length+1;await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(runId,sequence),run_id:runId,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"context_build",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:`context-pack:${runId}:${sequence}`,supersedes_event_id:null,source_occurred_at:new Date().toISOString(),context_stats:{initial_pack_tokens:initialPackTokens,tool_output_tokens:null,files_opened:null,snippets_opened:null}}))}function unavailableUsageRecord(current,parsed,sequence){const occurredAt=new Date().toISOString();return usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,sequence),run_id:current.run.run_id,sequence,occurred_at:occurredAt,type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"run_finalize",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:null,supersedes_event_id:null,...runUsageMetadataOptions(parsed.options,occurredAt)})}function latestRunV2Phase(records){const latest=records.findLast(record3=>"phase"in record3);return latest?.phase??"conversation"}function runV2EventId(runId,sequence){return`${runId}:${String(sequence).padStart(6,"0")}`}var init_conversation_intake_settlement=__esm({"src/conversation-intake-settlement.ts"(){"use strict";init_src5();init_cli_arguments();init_record_codex_telemetry();init_run_hierarchy();init_run_lifecycle_reconciliation()}});function continuationPredecessor(candidates,target){const responsible=candidates.filter(fold=>runMatchesTarget(fold,target)&&fold.run.agent==="agent-orchestrator"&&(target.taskId!==void 0?fold.run.task_id===target.taskId:fold.run.task_id===null));const active=responsible.filter(fold=>fold.finished===null&&(fold.run.requires_finalizer===true||fold.run.execution_kind==="delivery"));if(active.length>0)throw new UsageError(`Continuation still has an active responsible Run: ${active.map(fold=>fold.run.run_id).join(", ")}; reconcile its observed terminal event and Gui before a new root`);return responsible.filter(fold=>fold.finished!==null&&fold.finished!==void 0).sort((left,right)=>(right.finished?.occurred_at??"").localeCompare(left.finished?.occurred_at??""))[0]?.run.run_id??null}function resolveContinuationPredecessor(candidates,openIntakes2,target){if(target===null)return null;return continuationPredecessor(candidates,target)??openIntakes2.find(fold=>runMatchesTarget(fold,target))?.run.run_id??null}var init_conversation_continuation_owner=__esm({"src/conversation-continuation-owner.ts"(){"use strict";init_cli_arguments();init_conversation_intake_settlement()}});async function findIntakeForExactTurn(composition,client,invocation2,candidates){if(invocation2.clientThreadId===null||invocation2.clientTurnId===null)return null;const matches=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&(fold.run.intake!=null||fold.run.phase==="conversation"&&fold.run.execution_id===null)&&fold.run.client_thread_id===invocation2.clientThreadId&&fold.run.client_turn_id===invocation2.clientTurnId);if(matches.length>1){throw new UsageError(`Exact client turn already has multiple intake Runs: ${matches.map(fold=>fold.run.run_id).join(", ")}`)}return matches[0]??null}async function findRootRunForExactTurn(composition,client,invocation2,candidates){if(invocation2.clientThreadId===null||invocation2.clientTurnId===null)return null;const matches=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&fold.run.parent_run_id===null&&fold.run.client_thread_id===invocation2.clientThreadId&&fold.run.client_turn_id===invocation2.clientTurnId);if(matches.length>1){const sequence=await composition.executions.readPostPublicationSequence(invocation2.clientTurnId);if(sequence!==null){const byId2=new Map(matches.map(fold=>[fold.run.run_id,fold]));const maintenance=sequence.schema_version===7?byId2.get(sequence.maintenance_run_id):await composition.runs.read(sequence.maintenance_run_id);const steps=sequence.steps;if(maintenance!==void 0&&matches.length===steps.length+(sequence.schema_version===7?1:0)&&maintenance.finished?.status==="completed"&&maintenance.finalization_decision?.outcome==="completed"&&maintenance.run.client_thread_id===invocation2.clientThreadId&&steps.every((step,index)=>{const predecessor=index===0?maintenance:byId2.get(step.predecessor_run_id);const successor=byId2.get(step.successor_run_id);return predecessor!==void 0&&successor!==void 0&&predecessor.finished?.status==="completed"&&predecessor.finalization_decision?.outcome==="completed"&&successor.run.continuation_of_run_id===predecessor.run.run_id&&successor.run.execution_id===step.execution_id&&(index===0&&sequence.schema_version===8?successor.run.same_turn_handoff===void 0&&successor.run.intake?.reason_codes.includes(`post-publication-${step.authorization_sha256.slice(0,16)}`):successor.run.same_turn_handoff?.authorization_sha256===step.authorization_sha256&&successor.run.same_turn_handoff.predecessor_run_id===predecessor.run.run_id)&&successor.run.spec_id===(step.origin.type==="spec"?step.origin.spec_id:null)&&(step.origin.type!=="task"||successor.run.task_id===step.target_task_id)&&(index===0&&sequence.schema_version===8||successor.run.agent_invocation_id===predecessor.run.agent_invocation_id)&&(index!==steps.length-1||successor.status==="running")}))return byId2.get(steps.at(-1)?.successor_run_id??"")??null}if(matches.length===2){const successor=matches.find(fold=>fold.run.same_turn_handoff!==void 0);const predecessor=matches.find(fold=>fold.run.run_id===successor?.run.same_turn_handoff?.predecessor_run_id);const handoff=successor?.run.same_turn_handoff;const postPublication=handoff!==void 0&&"kind"in handoff;const claim=postPublication?await composition.executions.readPostPublicationHandoff(invocation2.clientTurnId):await composition.executions.readSpecHandoff(invocation2.clientTurnId);if(predecessor?.finished?.status==="completed"&&predecessor.finalization_decision?.outcome==="completed"&&successor?.status==="running"&&claim?.predecessor_run_id===predecessor.run.run_id&&claim.successor_run_id===successor.run.run_id&&claim.execution_id===successor.run.execution_id&&(claim.origin.type==="spec"?claim.origin.spec_id===successor.run.spec_id:claim.origin.task_id===successor.run.task_id&&successor.run.spec_id===null)&&claim.authorization_sha256===successor.run.same_turn_handoff?.authorization_sha256&&(postPublication?(claim.schema_version===3||claim.schema_version===5)&&handoff!==void 0&&"target_task_id"in handoff&&claim.target_task_id===handoff.target_task_id&&claim.maintenance_execution_id===predecessor.run.execution_id&&predecessor.run.execution_kind==="delivery"&&predecessor.run.entrypoint==="task":claim.schema_version===2&&predecessor.run.execution_kind==="interaction")&&successor.run.continuation_of_run_id===predecessor.run.run_id&&successor.run.agent_invocation_id===predecessor.run.agent_invocation_id&&successor.run.execution_kind==="delivery"&&successor.run.spec_id===successor.run.same_turn_handoff?.target_spec_id)return successor}throw new UsageError(`Exact client turn already has multiple root Runs: ${matches.map(fold=>fold.run.run_id).join(", ")}`)}return matches[0]??null}function sameClientCorrelation(left,right){const normalizedLeft=left==="codex-desktop"?"codex":left;const normalizedRight=right==="codex-desktop"?"codex":right;return normalizedLeft===normalizedRight}var init_conversation_intake_root_turn=__esm({"src/conversation-intake-root-turn.ts"(){"use strict";init_cli_arguments()}});function conversationObjective(userMessage){const fallback="Capture the current client turn";if(userMessage===null)return fallback;const normalized=userMessage.replace(/\r\n?/g,"\n").trim();const requestHeading=/^##\s+My request for Codex:\s*$/im;const match=requestHeading.exec(normalized);const request=match===null?normalized:normalized.slice(match.index+match[0].length);return request.replace(/<image\b[\s\S]*$/i,"").replace(/\s+/g," ").trim()||fallback}function semanticTerms(value){return new Set(normalizeWorkKey(value).split(" ").map(term=>singularizeSemanticTerm(term)).filter(term=>term.length>=3&&!semanticStopWords.has(term)))}function normalizeWorkKey(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function singularizeSemanticTerm(term){if(term.length>4&&term.endsWith("s")&&!term.endsWith("ss"))return term.slice(0,-1);return term}var semanticStopWords;var init_conversation_semantic_terms=__esm({"src/conversation-semantic-terms.ts"(){"use strict";semanticStopWords=new Set(["a","an","and","as","at","by","com","da","das","de","do","dos","e","em","for","from","in","into","na","nas","no","nos","of","on","or","para","per","por","que","that","the","this","to","um","uma","with"])}});function definitionAuthorizations(parsed){const values=csvOption(parsed.options.definition);const definitions=[...new Set(values.map(value=>value.toLocaleLowerCase()))];if(definitions.some(value=>value!=="prd"&&value!=="spec")){throw new UsageError("--definition must be prd, spec, or prd,spec")}return definitions}function definitionAuthorizationsFromExplicitCreate(userMessage){const request=directUserRequest(userMessage);if(request.length===0)return[];const targets=new Set;for(const definition of["prd","spec"]){const target=`(?:a |an |uma? |the |new )?${definition}`;const negated=new RegExp(`\\b(?:nao|nunca|jamais|sem|do not|don t|never)\\s+(?:quero\\s+)?(?:crie|create|criar)\\s+${target}\\b`);if(negated.test(request))return[];const directImperative=new RegExp(`^(?:por favor,?\\s+)?(?:crie|create)\\s+${target}\\b`);const statedIntent=new RegExp(`^(?:quero|preciso|vamos|pode)\\s+(?:criar|create)\\s+${target}\\b`);const commandForm=new RegExp(`^(?:criar|create)\\s+${target}\\b`);if(directImperative.test(request)||statedIntent.test(request)||commandForm.test(request)){targets.add(definition)}}if(targets.has("prd"))targets.add("spec");return[...targets]}function assertDefinitionConversationIntake(parsed,intent){if(definitionAuthorizations(parsed).length===0)return;if(intent!=="conversation"||parsed.options.intent!=="conversation"){throw new UsageError("--definition requires --intent conversation")}if(parsed.options["classification-source"]!=="explicit"){throw new UsageError("--definition requires --classification-source explicit")}if(parsed.options.title!==void 0||parsed.flags.has("title")){throw new UsageError("--title is invalid for conversation start --definition; supply it to spec or prd create after intake")}if(["task","spec","prd","change","short-name","objective"].some(option=>parsed.options[option]!==void 0)){throw new UsageError("--definition requires a root interaction without Task, Change, or target")}}function conversationRequestOptions(userMessage){const objective=conversationObjective(userMessage);return{objective,risk:inferredConversationRisk(objective)}}function resolveConversationIntent(parsed,userMessage=null){const value=parsed.options.intent;if(value===void 0){if(hasCompleteNewWorkMetadata(parsed))return"new_work";return inferConversationIntent(userMessage)}const normalized=value.toLocaleLowerCase().replaceAll("-","_");if(normalized==="conversation"||normalized==="continue"||normalized==="refine"||normalized==="rework"||normalized==="new_work"||normalized==="git_only"){return normalized}throw new UsageError("--intent must be conversation, continue, refine, rework, new-work, or git-only")}function inferConversationIntent(userMessage){if(definitionAuthorizationsFromExplicitCreate(userMessage).length>0)return"conversation";const normalized=normalizeWorkKey(userMessage??"");if(normalized.length===0)return"conversation";if(/\b(rework|retrabalh\w*)\b/.test(normalized))return"rework";if(/\b(refine|refinar|refinamento|desenvolv\w*|melhor\w*|aprimor\w*)\b/.test(normalized)){return"refine"}if(/\b(continue|continuar|retome|retomar|implement\w*|execut\w*|finaliz\w*|conclu\w*)\b/.test(normalized)){return"continue"}return"conversation"}function intakeDecision(parsed,intent,userMessage=null){const intentWasProvided=parsed.options.intent!==void 0;const explicitMetadata=!intentWasProvided&&hasCompleteNewWorkMetadata(parsed);const source=parsed.options["classification-source"];const declaredDefinitions=definitionAuthorizations(parsed);const recoveredDefinitions=declaredDefinitions.length===0&&intent==="conversation"&&(source===void 0||source==="explicit")&&!["task","spec","prd","change","title","short-name","objective"].some(option=>parsed.options[option]!==void 0)?definitionAuthorizationsFromExplicitCreate(userMessage):[];const definitions=[...declaredDefinitions,...recoveredDefinitions];const classificationSource=source===void 0?recoveredDefinitions.length>0?"explicit":intentWasProvided?"agent":explicitMetadata?"explicit":"fallback":source;if(!new Set(["agent","explicit","fallback"]).has(classificationSource)){throw new UsageError("--classification-source must be agent, explicit, or fallback")}const defaultConfidence=classificationSource==="fallback"?"0":"0.9";const reasonCodes=csvOption(parsed.options["reason-codes"]);if(reasonCodes.some(code=>/^definition-(prd|spec)-authorized$/.test(code))){throw new UsageError("--reason-codes cannot supply definition authorization")}if(reasonCodes.length+definitions.length>12){throw new UsageError("--reason-codes leaves no room for definition authorization")}const derivedReasonCodes=definitions.map(definition=>`definition-${definition}-authorized`);return{intent,classification_source:classificationSource,confidence:confidenceOption(parsed.options.confidence??defaultConfidence),reason_codes:[...reasonCodes.length>0?reasonCodes:[classificationSource==="fallback"?"safe-conversation-fallback":explicitMetadata?"complete-task-metadata":"agent-classified"],...derivedReasonCodes]}}function requireSemanticNewWorkMetadata(parsed){const title=parsed.options.title;const shortName=parsed.options["short-name"];const objective=parsed.options.objective;if(title===void 0||shortName===void 0||objective===void 0){throw new UsageError("new-work intake requires --title, --short-name, and --objective")}const wordCount=title.trim().split(/\s+/).filter(Boolean).length;if(wordCount<4||wordCount>10){throw new UsageError("new-work --title must contain 4 to 10 words")}return{title:title.trim(),shortName:shortName.trim(),objective:objective.trim()}}function describesEquivalentWork(requested,current){const requestedShortName=normalizeWorkKey(requested.shortName);if(requestedShortName.length>0&&requestedShortName===normalizeWorkKey(current.short_name)){return true}const requestedTerms=semanticTerms(`${requested.title} ${requested.objective}`);const currentTerms=semanticTerms(`${current.title} ${current.objective}`);if(requestedTerms.size<5||currentTerms.size<5)return false;let shared=0;for(const term of requestedTerms){if(currentTerms.has(term))shared+=1}return shared>=5&&shared/Math.min(requestedTerms.size,currentTerms.size)>=.7}function assertExactIntakeRequestCompatible(existing,parsed,requestedIntent){const conflicts=[];for(const[option,captured]of[["run",existing.run.run_id],["conversation",existing.run.conversation_id],["provider",existing.run.provider],["work-type",existing.run.work_type],["direct-authorization",existing.run.direct_execution_authorization]]){if(parsed.options[option]!==void 0&&parsed.options[option]!==captured){conflicts.push(`${option}=${captured??"unavailable"}`)}}if(parsed.options.execution!==void 0&&existing.run.execution_id!==parsed.options.execution){conflicts.push(`execution=${existing.run.execution_id??"none"}`)}if(parsed.options.intent!==void 0&&existing.run.intake?.intent!==requestedIntent){conflicts.push(`intent=${existing.run.intake?.intent??"unknown"}`)}const target=explicitIntakeTarget(parsed);if(target!==null&&!matchesTarget(existing,target)){conflicts.push(`target=${existingTarget(existing)} requested=${requestedTarget(target)}`)}if(parsed.options.model!==void 0&&existing.run.model!==parsed.options.model){conflicts.push(`model=${existing.run.model}`)}if(parsed.options["reasoning-effort"]!==void 0&&existing.run.reasoning_effort!==parsed.options["reasoning-effort"]){conflicts.push(`reasoning-effort=${existing.run.reasoning_effort??"unavailable"}`)}if(conflicts.length===0)return;throw new UsageError(`Exact client turn is already captured by Run ${existing.run.run_id} (${conflicts.join(", ")}). Use the matching retry, or start the requested delivery from a new observed client turn.`)}async function latestThreadContext(composition,client,clientThreadId,candidates){if(clientThreadId===null)return{conversationId:null,implicitTarget:null};const runs=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&fold.run.parent_run_id===null&&fold.run.client_thread_id===clientThreadId);const targetRun=runs.find(fold=>targetFromRun(fold)!==null);return{conversationId:runs[0]?.run.conversation_id??null,implicitTarget:targetRun===void 0?null:targetFromRun(targetRun)}}function explicitIntakeTarget(parsed){const candidates=[parsed.options.task===void 0?null:{entrypoint:"task",taskId:parsed.options.task},parsed.options.spec===void 0?null:{entrypoint:"spec",specId:parsed.options.spec},parsed.options.prd===void 0?null:{entrypoint:"prd",prdId:parsed.options.prd}];const targets=candidates.filter(target=>target!==null);if(targets.length>1){throw new UsageError("continue/refine/rework intake accepts only one of --task, --spec, or --prd")}return targets[0]??null}function isImplicitConversationCapture(parsed){return["intent","title","short-name","objective","requirements","acceptance","task","spec","prd","change","run"].every(option=>parsed.options[option]===void 0)}function isGitOnlyPublicationRequest(userMessage){if(userMessage===null)return false;const normalized=userMessage.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(normalized.length===0||normalized.split(/\s+/).length>12)return false;if(/\b(corrig|consert|repar|fix|falh|erro|ci|teste|codigo|implement|alter|qual|quando|como|status|atual)\w*\b/.test(normalized)){return false}return/\b(deploy|push|publicar|publique|publica|publish)\b/.test(normalized)}function hasCompleteNewWorkMetadata(parsed){return["title","short-name","objective"].every(option=>parsed.options[option]!==void 0)}function targetFromRun(fold){if(fold.run.entrypoint==="task"&&fold.run.task_id!==null){return{entrypoint:"task",taskId:fold.run.task_id}}if(fold.run.entrypoint==="spec"&&fold.run.spec_id!==null){return{entrypoint:"spec",specId:fold.run.spec_id}}if(fold.run.entrypoint==="prd"&&fold.run.prd_id!==null){return{entrypoint:"prd",prdId:fold.run.prd_id}}if(fold.run.task_id!==null)return{entrypoint:"task",taskId:fold.run.task_id};if(fold.run.spec_id!==null)return{entrypoint:"spec",specId:fold.run.spec_id};if(fold.run.prd_id!==null)return{entrypoint:"prd",prdId:fold.run.prd_id};return null}function matchesTarget(fold,target){return fold.run.entrypoint===target.entrypoint&&(target.taskId===void 0||fold.run.task_id===target.taskId)&&(target.specId===void 0||fold.run.spec_id===target.specId)&&(target.prdId===void 0||fold.run.prd_id===target.prdId)}function existingTarget(fold){return fold.run.task_id??fold.run.spec_id??fold.run.prd_id??"none"}function requestedTarget(target){return target.taskId??target.specId??target.prdId??"none"}function directUserRequest(userMessage){if(userMessage===null)return"";const normalized=userMessage.replace(/\r\n?/g,"\n").trim();const requestHeading=/^#{1,6}\s+My request(?:\s+for Codex)?:\s*$/im;const match=requestHeading.exec(normalized);const request=(match===null?normalized:normalized.slice(match.index+match[0].length)).trim();if(/^(?:[>"'`“”‘’]|~~~|<)/.test(request))return"";const attachmentBoundary=request.search(/\n(?:#{1,6}\s*(?:attachment|document|file|arquivo|anexo)\b|<image\b|```|---\s*$)/im);const directRequest=attachmentBoundary===-1?request:request.slice(0,attachmentBoundary);return normalizeWorkKey(directRequest)}function inferredConversationRisk(objective){const normalized=objective.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase();const isSmallFrontendAdjustment=normalized.length<=280&&/\b(ajust|corrig|alter|troqu|mud)\w*\b/.test(normalized)&&/\b(front(?:end)?|interface|ui|visual|css|layout|tela|botao|modal|popup|coluna|aba|card)\w*\b/.test(normalized);const hasElevatedScope=/\b(api|backend|banco|database|schema|migr|auth|segur|deploy|infra|lifecycle|task-first|cli)\w*\b/.test(normalized);return isSmallFrontendAdjustment&&!hasElevatedScope?"lite":"standard"}var init_conversation_intake=__esm({"src/conversation-intake.ts"(){"use strict";init_cli_arguments();init_conversation_intake_root_turn();init_conversation_semantic_terms();init_conversation_intake_root_turn()}});async function resolveConversationContinuation(parsed,composition,filesystem){if(parsed.options.intent!==void 0&&parsed.options.intent!=="continue"){throw new UsageError("conversation resolve supports --intent continue only")}if(parsed.options.definition!==void 0){throw new UsageError("conversation resolve does not authorize definition creation")}const client=parsed.options.client??"codex";const invocation2=await resolveRunClientInvocation(filesystem,client);const context2=await latestThreadContext(composition,client,invocation2.clientThreadId);const target=explicitIntakeTarget(parsed)??context2.implicitTarget;const existing=await findRootRunForExactTurn(composition,client,invocation2);const base={read_only:true,intent:"continue",target,current_run_id:existing?.run.run_id??null,current_execution_id:existing?.run.execution_id??null,start_args:null};if(target===null){return{...base,status:"unresolved",reason:"No root delivery focus in this client thread"}}const id=target.taskId??target.specId??target.prdId;if(id===void 0)throw new UsageError("Continuation target has no canonical ID");const options={...parsed.options,intent:"continue",client,[target.entrypoint]:id};const startArgs=["conversation","start",...Object.entries(options).flatMap(([key,value])=>[`--${key}`,value]),...Array.from(parsed.flags,flag=>`--${flag}`)];if(existing!==null){try{assertExactIntakeRequestCompatible(existing,{...parsed,options},"continue")}catch(error51){if(!(error51 instanceof UsageError))throw error51;return{...base,status:"conflict",reason:error51.message}}if(existing.finished!==null){return{...base,status:"closed",reason:"The matching Run is already terminal; do not dispatch new children"}}}if(target.taskId!==void 0){const task=(await composition.tasks.read(target.taskId)).task;if(["completed","cancelled","failed"].includes(task.status)){return{...base,status:"blocked",task_status:task.status,reason:"This Task cannot continue; completed/cancelled are immutable and failed requires explicit rework"}}return{...base,status:"resolved",task_status:task.status,execution_id:task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null,reused:existing!==null,start_args:startArgs}}const execution=await resolveCanonicalMacroExecution(target,composition,parsed.options.execution);return{...base,status:"resolved",execution_id:execution.id,execution_status:execution.status,task_ids:execution.dag.nodes.map(node=>node.task_id),reused:existing!==null,start_args:startArgs}}var init_conversation_resolution=__esm({"src/conversation-resolution.ts"(){"use strict";init_cli_arguments();init_conversation_intake();init_run_client_invocation();init_run_conversation_v2()}});function activeCaptureRunIds(area,parsed,result2){return area==="run"&&parsed.positionals[1]==="usage"&&(parsed.flags.has("active")||parsed.flags.has("recent"))?changedActiveCaptureRunIds(result2):null}function changedActiveCaptureRunIds(result2){const telemetry=result2?.telemetry;if(typeof telemetry!=="object"||telemetry===null||!("mode"in telemetry)||!["active_exact_session","recent_exact_session"].includes(String(telemetry.mode))||!("captured"in telemetry)||!Array.isArray(telemetry.captured))throw new UsageError("Active telemetry capture returned an invalid projection result");const ids2=[];for(const item of telemetry.captured){if(typeof item!=="object"||item===null||typeof item.run_id!=="string"||typeof item.captured!=="boolean"){throw new UsageError("Active telemetry capture returned an invalid Run result")}if(item.captured)ids2.push(item.run_id)}return ids2}var init_lifecycle_manifest_active_capture=__esm({"src/lifecycle-manifest-active-capture.ts"(){"use strict";init_cli_arguments()}});function effectiveRunFinishedAt(fold){const recordedFinish=fold.finished?.occurred_at??null;if(recordedFinish===null)return null;const startedAtMs=Date.parse(fold.run.occurred_at);const recordedFinishMs=Date.parse(recordedFinish);const reconciledFinishMs=fold.records.filter(record3=>"activity_kind"in record3&&record3.activity_kind==="retrospective_local_reconciliation").map(record3=>"source_occurred_at"in record3?record3.source_occurred_at??null:null).map(value=>value===null?Number.NaN:Date.parse(value)).filter(value=>Number.isFinite(value)&&value>=startedAtMs&&value<=recordedFinishMs);if(reconciledFinishMs.length===0)return recordedFinish;return new Date(Math.max(...reconciledFinishMs)).toISOString()}function projectedSourceTiming(runStartedAt,effectiveRecords,allRecords){const startedAtMs=Date.parse(runStartedAt);const timestampOf=value=>{const timestamp13=value===null||value===void 0?Number.NaN:Date.parse(value);return Number.isFinite(timestamp13)?timestamp13:null};const candidates=[];for(const record4 of[...effectiveRecords,...allRecords]){const sourceStartedAt2=record4.source_started_at;const sourceFinishedAt2=record4.source_finished_at;const startMs=timestampOf(sourceStartedAt2);const finishMs=timestampOf(sourceFinishedAt2);if(startMs!==null&&finishMs!==null&&finishMs>=startMs&&finishMs>=startedAtMs){candidates.push(record4);continue}const sourceOccurredAt=timestampOf(record4.source_occurred_at);if(record4.activity_kind==="retrospective_local_reconciliation"&&sourceOccurredAt!==null&&sourceOccurredAt>=startedAtMs)candidates.push({...record4,source_started_at:runStartedAt,source_finished_at:record4.source_occurred_at??void 0})}candidates.sort((left,right)=>Date.parse(left.occurred_at)-Date.parse(right.occurred_at));const record3=candidates.at(-1);const sourceStartedAt=record3?.source_started_at??null;const sourceFinishedAt=record3?.source_finished_at??record3?.source_occurred_at??null;return{source_started_at:sourceStartedAt,source_finished_at:sourceFinishedAt,source_duration_ms:timestampDelta(sourceStartedAt,sourceFinishedAt),capture_lag_ms:timestampDelta(sourceFinishedAt,record3?.occurred_at??null)}}function timestampDelta(start,finish){if(start===null||finish===null)return null;const startMs=Date.parse(start);const finishMs=Date.parse(finish);return Number.isFinite(startMs)&&Number.isFinite(finishMs)?Math.max(0,finishMs-startMs):null}var init_lifecycle_manifest_run_projection=__esm({"src/lifecycle-manifest-run-projection.ts"(){"use strict"}});function canonicalAgentName(agent){return agent.startsWith("agent-")?`zaip-agent-${agent.slice("agent-".length)}`:agent}function effectiveConfiguration(fold){const models=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.model),...fold.model_call_records.map(record3=>record3.model),...fold.effective_usage_records.map(record3=>record3.model)].filter(value=>value!==null));const efforts=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.reasoning_effort),...fold.effective_usage_records.map(record3=>record3.runtime?.reasoning_effort??null),...fold.model_call_records.map(record3=>record3.runtime?.reasoning_effort??null)].filter(value=>value!==null));return{effective_model:models.size===1?[...models][0]??null:null,effective_reasoning_effort:efforts.size===1?[...efforts][0]??null:null,effective_config_mixed:models.size>1||efforts.size>1}}function callSummary(fold){const ids2=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);const base={cli_call_count:ids2.size===0?null:ids2.size,call_count:null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null};if(fold.model_call_records.length>0)return{...base,call_count:fold.model_call_records.length};if(ids2.size===0)return base;return{...base,call_count:ids2.size,terminal_call_count:fold.provider_invocation_records.length,failed_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="failed").length,cancelled_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="cancelled").length}}var init_lifecycle_manifest_run_summary=__esm({"src/lifecycle-manifest-run-summary.ts"(){"use strict"}});function modelCallCoverage(fold){if(fold.model_call_records.length===0)return"unavailable";return fold.model_call_records.every(record3=>record3.coverage==="complete")?"complete":"partial"}function runCostInput(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}var init_lifecycle_manifest_run_usage=__esm({"src/lifecycle-manifest-run-usage.ts"(){"use strict"}});function summarizeRunObservedTiming(fold){return summarizeObservedSourceTiming(fold.effective_usage_records.map(record3=>({phase:record3.phase,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null})))}var init_observed_run_timing=__esm({"src/observed-run-timing.ts"(){"use strict";init_src4()}});async function runLifecycleManifestMaintenance(action,parsed,filesystem,composition){const store=new LifecycleManifestStore(filesystem);if(["neighbors","path","explain","gaps"].includes(action??"")){return runManifestGraphQuery(action,parsed,store)}if(action==="rebuild"){if(!parsed.flags.has("confirm-full-scan")){throw new UsageError("manifest rebuild requires --confirm-full-scan")}const events=await lifecycleManifestBootstrapEvents(composition,filesystem);return{snapshot:await store.replace(events),indexed:events.length}}if(action==="refresh")return store.refresh();if(action==="reconcile"){const id=parsed.options.id??parsed.positionals[2];if(id===void 0)throw new UsageError("manifest reconcile requires --id ID");const event=await lifecycleManifestEventForId(id,composition,filesystem);return{snapshot:await store.appendMany([event]),reconciled:[id]}}if(action==="show"){return parsed.flags.has("active")?store.readActiveWork():store.readSummary()}throw new UsageError("manifest requires rebuild, refresh, reconcile, show, neighbors, path, explain, or gaps")}async function runManifestGraphQuery(action,parsed,store){const entities=await store.readEntities();const byId2=new Map(entities.map(entity=>[entity.id,entity]));const id=parsed.options.id??parsed.positionals[2];if(action==="path"){const from=parsed.options.from??id;const to2=parsed.options.to??parsed.positionals[3];if(from===void 0||to2===void 0)throw new UsageError("manifest path requires --from ID --to ID");const queue=[[from]];const visited=new Set([from]);while(queue.length>0&&visited.size<=GRAPH_VISIT_LIMIT){const route=queue.shift();const current=route.at(-1);if(current===to2)return{path:route,bounded:true,limit:GRAPH_VISIT_LIMIT};for(const neighbor of graphNeighbors(entities,current)){if(!visited.has(neighbor.entity.id)){visited.add(neighbor.entity.id);queue.push([...route,neighbor.entity.id])}}}return{path:null,bounded:true,limit:GRAPH_VISIT_LIMIT}}if(id===void 0||!byId2.has(id))throw new UsageError("manifest graph query requires an existing --id ID");if(action==="neighbors"){const neighbors=graphNeighbors(entities,id);return{id,neighbors:neighbors.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:neighbors.length>GRAPH_RESULT_LIMIT}}if(action==="gaps"){const entity=byId2.get(id);if(entity===void 0)throw new UsageError("manifest graph query requires an existing --id ID");const gaps=relationEdgesFor(entity).filter(edge2=>!byId2.has(edge2.target_id));return{id,gaps:gaps.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:gaps.length>GRAPH_RESULT_LIMIT}}const to=parsed.options.to??parsed.positionals[3];if(to===void 0)throw new UsageError("manifest explain requires --id ID --to ID");const edge=graphNeighbors(entities,id).find(neighbor=>neighbor.entity.id===to)?.edge;return{id,to,relation:edge??null,bounded:true,limit:GRAPH_RESULT_LIMIT}}async function manifestList(area,parsed,filesystem){if(!["prd","spec","change","task","execution","run","decision"].includes(area)){throw new UsageError(`Lifecycle manifest does not support list area: ${area}`)}const store=new LifecycleManifestStore(filesystem);let entities=await store.readEntities(area);if(entities.length===0&&await store.readSummary()===null&&!await filesystem.exists(".agents/records/lifecycle/.gitkeep")){throw new UsageError("Lifecycle manifest is not initialized; run `zaip manifest rebuild --confirm-full-scan` once")}const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);entities=entities.filter(entity=>statuses.size===0||entity.status!==null&&statuses.has(entity.status)).filter(entity=>parsed.options.prd===void 0||entity.relations.includes(parsed.options.prd)).filter(entity=>parsed.options.spec===void 0||entity.relations.includes(parsed.options.spec)).filter(entity=>parsed.options.change===void 0||entity.relations.includes(parsed.options.change)).filter(entity=>parsed.options.task===void 0||entity.relations.includes(parsed.options.task)).filter(entity=>parsed.options.execution===void 0||entity.relations.includes(parsed.options.execution)).filter(entity=>from===null||Date.parse(entity.updated_at)>=from).filter(entity=>to===null||Date.parse(entity.updated_at)<=to).sort((left,right)=>right.updated_at.localeCompare(left.updated_at)||right.id.localeCompare(left.id));const after=parsed.options.after;const start=after===void 0?0:entities.findIndex(entity=>entity.id===after)+1;if(after!==void 0&&start===0)throw new UsageError(`--after id not found: ${after}`);const limit=parsed.flags.has("all")?entities.length:numberOption(parsed.options.limit,20);if(limit>200&&!parsed.flags.has("all")){throw new UsageError("--limit must be at most 200; use --all explicitly")}const view=parsed.options.view??"index";if(view!=="index"&&view!=="summary"&&view!=="full")throw new UsageError("--view must be index, summary, or full");const page=entities.slice(start,start+limit);if(view==="full")return page;if(view==="summary"){return page.map(({data:_data,...entity})=>entity)}return{schema:["id","title","status","risk","priority","updated_at","work_relations"],rows:page.map(entity=>[entity.id,entity.title,entity.status,entity.risk,entity.priority,entity.updated_at,entity.relations.filter(relation=>/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-/.test(relation)).slice(0,2)]),next_after:page.length===limit?page.at(-1)?.id??null:null}}function isLifecycleManifestMutation(action){if(action===void 0||action==="ready-next")return false;return!["list","show","next","validate","aggregate","inspect-local","preflight"].includes(action)}async function syncLifecycleManifestResult(result2,area,parsed,composition,filesystem){const store=new LifecycleManifestStore(filesystem);if(area==="decision"){const decision=findDecision(result2);if(decision!==void 0)await store.append(lifecycleManifestEventFromDecision(decision));return}if(area==="run"||area==="subagent"){const capturedIds=activeCaptureRunIds(area,parsed,result2);const candidate=area==="run"&&capturedIds===null?findRunId(result2)??parsed.options.id??parsed.positionals[2]:void 0;const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);const runIds=new Set(capturedIds??collectRunIds(result2));if(candidate!==void 0)runIds.add(candidate);for(const runId of runIds){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="conversation"){const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="validation"||area==="evidence"){const artifact=findArtifact(result2,area);if(artifact!==void 0)await store.append(lifecycleManifestEventFromEntity(artifact));return}const events=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events.length>0)await store.appendMany(events)}async function syncObservedRunManifest(runId,composition,filesystem){const run=await composition.runs.read(runId);if(run.run.entrypoint!=="observation")return;await new LifecycleManifestStore(filesystem).append(lifecycleManifestEventFromRun(run))}function findArtifact(result2,area){if(typeof result2!=="object"||result2===null)return void 0;const artifact=result2[area];if(typeof artifact!=="object"||artifact===null)return void 0;const record3=artifact;const observedAt=area==="validation"?record3.executed_at:record3.observed_at;if(typeof record3.id!=="string"||typeof observedAt!=="string"||typeof record3.status!=="string"){return void 0}return{...record3,updated_at:observedAt}}async function lifecycleManifestEventForId(id,composition,filesystem){if(id.startsWith("PRD-"))return lifecycleManifestEventFromEntity((await composition.prds.read(id)).prd);if(id.startsWith("SPEC-"))return lifecycleManifestEventFromEntity((await composition.specs.read(id)).spec);if(id.startsWith("CHG-"))return lifecycleManifestEventFromEntity((await composition.changes.read(id)).change);if(id.startsWith("TASK-"))return lifecycleManifestEventFromEntity((await composition.tasks.read(id)).task);if(id.startsWith("EXEC-"))return lifecycleManifestEventFromEntity((await composition.executions.read(id)).execution);if(id.startsWith("RUN-"))return lifecycleManifestEventFromRun(await composition.runs.read(id));if(/^(?:TEST|EVAL|CHECK|REVIEW|MUT|INT|E2E)-/.test(id)||id.startsWith("EVD-")){const artifact=(await lifecycleAssuranceBootstrapEvents(filesystem)).find(event=>event.entity.id===id);if(artifact!==void 0)return artifact;throw new UsageError(`Typed assurance artifact not found: ${id}`)}throw new UsageError(`Unsupported lifecycle manifest reconciliation id: ${id}`)}function collectLifecycleEntities(value){const found=[];const seen=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.id==="string"&&typeof record3.status==="string"&&typeof record3.updated_at==="string"&&/^(PRD|SPEC|CHG|TASK|EXEC)-/.test(record3.id)&&!seen.has(record3.id)){seen.add(record3.id);found.push(record3)}Object.values(record3).forEach(visit)};visit(value);return found}function lifecycleManifestEventFromEntity(entity){const id=entity.id;const kind=id.startsWith("PRD-")?"prd":id.startsWith("SPEC-")?"spec":id.startsWith("CHG-")?"change":id.startsWith("TASK-")?"task":id.startsWith("EVD-")?"evidence":id.startsWith("TEST-")||id.startsWith("EVAL-")||id.startsWith("CHECK-")||id.startsWith("REVIEW-")||id.startsWith("MUT-")||id.startsWith("INT-")||id.startsWith("E2E-")?"validation":"execution";const relations=new Set;collectRelationIds(entity,relations,id);for(const[key,value]of Object.entries(entity)){if(key.endsWith("_id")&&typeof value==="string")relations.add(value);if(key.endsWith("_ids")&&Array.isArray(value))value.filter(item=>typeof item==="string").forEach(item=>{relations.add(item)})}return{schema_version:1,event_id:`${id}:${String(entity.updated_at)}:${String(entity.status)}`,occurred_at:entity.updated_at,operation:"upsert",entity:{kind,id,title:typeof entity.title==="string"?entity.title:null,status:entity.status,risk:typeof entity.risk==="string"?entity.risk:null,priority:typeof entity.priority==="string"?entity.priority:null,updated_at:entity.updated_at,relations:[...relations],relation_edges:relationEdgesFromEntity(entity,[...relations]),usage:null,data:Object.fromEntries(Object.entries(entity).filter(([key])=>key!=="prepared_plan"))}}}function collectRelationIds(value,relations,ownId){if(typeof value==="string"){if(/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN|REQ|AC)-/.test(value)&&value!==ownId){relations.add(value)}return}if(Array.isArray(value)){value.forEach(item=>{collectRelationIds(item,relations,ownId)});return}if(typeof value==="object"&&value!==null){Object.values(value).forEach(item=>{collectRelationIds(item,relations,ownId)})}}function lifecycleManifestEventFromRun(fold){const costInput=runCostInput(fold);const aggregate=aggregateRunV2Usage([costInput],fold.run.run_id);const usage=aggregate.total;const runtime=fold.effective_usage_records.findLast(record3=>record3.runtime)?.runtime;const observedRuntime=fold.effective_usage_records.at(-1);const sourceTiming=projectedSourceTiming(fold.run.occurred_at,fold.effective_usage_records,fold.records);return{schema_version:1,event_id:`${fold.run.run_id}:${fold.records.length}:${fold.status}`,occurred_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,operation:"upsert",entity:{kind:"run",id:fold.run.run_id,title:null,status:fold.status,risk:null,priority:null,updated_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,relations:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null),relation_edges:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null).map(target_id=>({target_id,type:target_id===fold.run.parent_run_id?"parent":"references",direction:"outbound",provenance:"explicit",source_locator:`run:${fold.run.run_id}`})),usage:{input_tokens:usage.tokens.input,output_tokens:usage.tokens.output,cached_input_tokens:usage.tokens.cached_input,total_tokens:usage.tokens.total,cost:usage.cost.brl??usage.cost.usd,currency:usage.cost.brl!==null?"BRL":usage.cost.usd!==null?"USD":null},data:{attribution_status:fold.run.attribution_status,phase:fold.records.findLast(record3=>"phase"in record3)?.phase??fold.run.phase,run_role:effectiveRunV2Role(fold.run),run_kind:effectiveRunV2Kind(fold.run),run_purpose:effectiveRunV2Purpose(fold.run),requires_finalizer:runV2RequiresFinalizer(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,client:fold.run.client,agent:fold.run.agent,agent_name:fold.run.agent==="codex"?"codex":fold.run.agent_name??canonicalAgentName(fold.run.agent),provider:observedRuntime?.provider??fold.run.provider,model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,...effectiveConfiguration(fold),...callSummary(fold),cli_agent_name:fold.run.agent_name??null,call_coverage:modelCallCoverage(fold),service_tier:runtime?.service_tier??null,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,zaip_execution_id:fold.run.execution_id,agent_invocation_id:fold.run.agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,root_agent_invocation_id:fold.run.root_agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,parent_agent_invocation_id:fold.run.parent_agent_invocation_id??null,agent_invocation_kind:fold.run.invocation_kind??(fold.run.parent_run_id===null?"orchestrator":"delegated"),delegation_depth:fold.run.delegation_depth??(fold.run.parent_run_id===null?0:null),conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,intake:fold.run.intake??null,started_at:fold.run.occurred_at,terminal_finished_at:fold.finished?.occurred_at??null,finished_at:effectiveRunFinishedAt(fold),...sourceTiming,observed_source_timing:summarizeRunObservedTiming(fold),pricing_segments:fold.effective_usage_records.map(record3=>({event_id:record3.event_id,attributed_spec_id:record3.attributed_spec_id??null,phase:record3.phase,provider:record3.provider,model:record3.model,service_tier:record3.runtime?.service_tier??runtime?.service_tier??null,input_tokens:record3.tokens.input,cached_input_tokens:record3.tokens.cached_input,output_tokens:record3.tokens.output,reasoning_tokens:record3.tokens.reasoning,total_tokens:record3.tokens.total,recorded_usd:record3.cost.usd,recorded_brl:record3.cost.brl,recorded_fx_rate:record3.cost.fx_rate??null,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null,duration_ms:record3.source_started_at&&record3.source_finished_at?Math.max(0,Date.parse(record3.source_finished_at)-Date.parse(record3.source_started_at)):null})),entrypoint_usage:{conversation:aggregate.conversation,planning:aggregate.planning,execution:aggregate.execution,total:usage}}}}}function lifecycleManifestEventFromDecision(decision){return{schema_version:1,event_id:`${decision.id}:${decision.created_at}`,occurred_at:decision.created_at,operation:"upsert",entity:{kind:"decision",id:decision.id,title:decision.title,status:null,risk:null,priority:null,updated_at:decision.created_at,relations:[decision.scope_id],relation_edges:[{target_id:decision.scope_id,type:"references",direction:"outbound",provenance:"explicit",source_locator:`decision:${decision.id}`}],usage:null,data:{origin:decision.origin,scope_type:decision.scope_type,scope_id:decision.scope_id,category:decision.category,created_at:decision.created_at}}}}function relationEdgesFromEntity(entity,relations){return relations.map(target_id=>{const explicit=Object.entries(entity).some(([key,value])=>key.endsWith("_id")&&value===target_id||key.endsWith("_ids")&&Array.isArray(value)&&value.includes(target_id));return{target_id,type:target_id.startsWith("REQ-")||target_id.startsWith("AC-")?"requirement":"references",direction:"outbound",provenance:explicit?"explicit":"derived",source_locator:`record:${String(entity.id)}`}})}function findRunId(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.run_id==="string")return record3.run_id;for(const child of Object.values(record3)){const result2=findRunId(child);if(result2!==void 0)return result2}return void 0}function collectRunIds(value){const found=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.run_id==="string"&&record3.run_id.startsWith("RUN-")){found.add(record3.run_id)}Object.values(record3).forEach(visit)};visit(value);return[...found]}function findDecision(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.id==="string"&&record3.id.startsWith("DEC-")&&typeof record3.created_at==="string"){return record3}for(const child of Object.values(record3)){const result2=findDecision(child);if(result2!==void 0)return result2}return void 0}async function lifecycleManifestBootstrapEvents(composition,filesystem){const[prds,specs,changes,tasks,executions,runs,decisions,assurance]=await Promise.all([composition.prds.list(),composition.specs.list(),composition.changes.list(),composition.tasks.list(),composition.executions.list(),composition.runs.list(),composition.decisions.list(),lifecycleAssuranceBootstrapEvents(filesystem)]);return[...[...prds,...specs,...changes,...tasks,...executions].map(entity=>lifecycleManifestEventFromEntity(entity)),...runs.map(lifecycleManifestEventFromRun),...decisions.map(lifecycleManifestEventFromDecision),...assurance]}async function lifecycleAssuranceBootstrapEvents(filesystem){const paths2=await filesystem.listFiles(".agents/records/changes",".md");const events=[];for(const path of paths2){const isEvidence=path.includes("/artifacts/evidence/");const isValidation=/\/artifacts\/(?:tests|evals|checks)\//.test(path);if(!isEvidence&&!isValidation)continue;try{const content=await filesystem.readText(path);const artifact=isEvidence?parseMarkdown(content,evidenceArtifactV2Schema).metadata:parseMarkdown(content,validationArtifactV2Schema).metadata;const timestamp13="observed_at"in artifact?artifact.observed_at:artifact.executed_at;events.push(lifecycleManifestEventFromEntity({...artifact,updated_at:timestamp13}))}catch{}}return events}var GRAPH_RESULT_LIMIT,GRAPH_VISIT_LIMIT;var init_lifecycle_manifest_commands=__esm({"src/lifecycle-manifest-commands.ts"(){"use strict";init_src();init_src4();init_src5();init_src8();init_src8();init_src6();init_cli_arguments();init_lifecycle_manifest_active_capture();init_lifecycle_manifest_run_projection();init_lifecycle_manifest_run_summary();init_lifecycle_manifest_run_usage();init_observed_run_timing();GRAPH_RESULT_LIMIT=50;GRAPH_VISIT_LIMIT=200}});import{execFile as execFile15}from"node:child_process";import{createHash as createHash49}from"node:crypto";import{lstat as lstat10,open as open5,realpath as realpath10}from"node:fs/promises";import{isAbsolute as isAbsolute8,resolve as resolve14,toNamespacedPath}from"node:path";import{promisify as promisify15}from"node:util";function stopReceiptPath(session,turn){return`.local/hooks/stop-${hash3(JSON.stringify([session,turn]))}.json`}async function replayStopReceipt(filesystem,session,turn,options={}){const path=stopReceiptPath(session,turn);const source=JSON.parse(await filesystem.readText(path));if(source.schema_version!==1||source.session_id!==session||source.turn_id!==turn||source.event?.session_id!==session||source.event?.turn_id!==turn)throw new Error("Stop replay identity mismatch");const hook=filesystem.resolve(".codex/hooks/zaip-conversation-lifecycle.mjs");const child=promisify15(execFile15)(process.execPath,[hook,options.automatic?"--recover-previous-turn":"--replay-receipt"],{cwd:filesystem.root,windowsHide:true,timeout:options.automatic?9e3:5e4,maxBuffer:262144});child.child.stdin?.end(JSON.stringify({...source.event,stop_hook_active:true}));await child;const result2=JSON.parse(await filesystem.readText(path));return{session_id:session,turn_id:turn,state:result2.state,error:result2.error??null,telemetry:result2.telemetry??null}}async function assertTrustedStopReceipt(filesystem,session,turn){const receipt=stopReceiptSchema.parse(JSON.parse(await filesystem.readText(stopReceiptPath(session,turn))));if(receipt.session_id!==session||receipt.turn_id!==turn)throw new Error("Stop receipt session/turn mismatch");const age=Date.now()-Date.parse(receipt.observed_at);if(age<-5e3||age>7*864e5)throw new Error("Stop receipt requires a fresh transcript observation");const cursor=receipt.cursor;if(!isAbsolute8(cursor.path))throw new Error("Stop transcript path must be absolute");if(/^(?:\\\\|\/\/)/.test(cursor.path)&&!/^\\\\\?\\[a-z]:\\/i.test(cursor.path))throw new Error("Stop transcript cannot use network or device paths");const identity2=path=>process.platform==="win32"?toNamespacedPath(resolve14(path)).toLowerCase():resolve14(path);const info=await lstat10(cursor.path);if(!info.isFile()||info.isSymbolicLink()||identity2(await realpath10(cursor.path))!==identity2(cursor.path))throw new Error("Stop transcript cannot follow links");const handle=await open5(cursor.path,"r");try{const stat5=await handle.stat();if(stat5.dev!==cursor.dev||stat5.ino!==cursor.ino||stat5.birthtimeMs!==cursor.birthtime_ms||stat5.size<cursor.size||cursor.offset>cursor.size||stat5.size===cursor.size&&(stat5.mtimeMs!==cursor.mtime_ms||stat5.ctimeMs!==cursor.ctime_ms))throw new Error("Stop transcript replaced or truncated after observation");const readProof=async proof=>{if(proof.offset+proof.length>cursor.offset)throw new Error("Stop proof exceeds observed transcript");const buffer=Buffer.alloc(proof.length);const read=await handle.read(buffer,0,buffer.length,proof.offset);if(read.bytesRead!==buffer.length||hash3(buffer)!==proof.sha256)throw new Error("Stop transcript proof mismatch");return buffer};const header=await readProof(cursor.session_proof);const terminal=await readProof(cursor.terminal_proof);await readProof(cursor.anchor);if(cursor.session_proof.offset!==0||header.at(-1)!==10||terminal.at(-1)!==10||cursor.terminal_proof.offset<cursor.session_proof.length)throw new Error("Stop proof must identify complete ordered JSONL records");const first=JSON.parse(header.toString("utf8"));const sessionId=first.type==="session_meta"?first.payload?.id??first.payload?.session_id:first.payload?.type==="session_meta"?first.payload.id??first.payload.session_id:null;const last=JSON.parse(terminal.toString("utf8")).payload;if(sessionId!==session||last?.type!=="task_complete"||last.turn_id!==turn)throw new Error("Stop terminal evidence belongs to another session or turn");const status=last.status==="cancelled"?"cancelled":last.status==="failed"||last.error!=null?"failed":"completed";if(status!==cursor.terminal_status)throw new Error("Stop outcome differs from observed terminal event");const after=await handle.stat();if(stat5.size!==after.size||stat5.mtimeMs!==after.mtimeMs||stat5.ctimeMs!==after.ctimeMs)throw new Error("Stop transcript changed during proof verification");return{run_id:receipt.run_id,status}}finally{await handle.close()}}async function reconcileVerifiedStop(parsed,filesystem,composition,lifecycle,reconcile){requireOptions(parsed.options,["session","turn"]);const session=String(parsed.options.session).trim();const turn=String(parsed.options.turn).trim();const proof=await assertTrustedStopReceipt(filesystem,session,turn);const key=createHash49("sha256").update(JSON.stringify(["codex",session,turn,null,null])).digest("hex");const correlation=JSON.parse(await filesystem.readText(`.local/codex-telemetry-spool/v1/correlations/${key}.json`));if(correlation.schema_version!==1||correlation.agent_path!==null||correlation.thread_id!==session||correlation.turn_id!==turn||correlation.run_id!==proof.run_id)throw new UsageError("Stop correlation does not match exact terminal evidence");const root=await composition.runs.read(proof.run_id);if(root.run.parent_run_id!==null||root.run.client_thread_id!==session||root.run.client_turn_id!==turn||root.run.agent!=="agent-orchestrator"||root.run.run_role!=="orchestrator")throw new UsageError("reconcile-stop requires the exact canonical orchestrator root");if(root.run.task_id===null){return runConversationV2Command("finish",{...parsed,options:{...parsed.options,run:root.run.run_id,status:proof.status,summary:root.finalization_decision?.summary??"Codex host turn completed"}},composition,filesystem,lifecycle)}return reconcile(root,composition,lifecycle,proof.status)}var hash3;var init_stop_receipt=__esm({"src/stop-receipt.ts"(){"use strict";init_src();init_cli_arguments();init_run_conversation_v2();hash3=value=>createHash49("sha256").update(value).digest("hex")}});import{createHash as createHash50}from"node:crypto";import{lstat as lstat11,open as open6,realpath as realpath11}from"node:fs/promises";import{isAbsolute as isAbsolute9,resolve as resolve15,toNamespacedPath as toNamespacedPath2}from"node:path";async function verifyStopPersistence(filesystem,composition,session,turn,runId){const proof=await assertTrustedStopReceipt(filesystem,session,turn).catch(()=>{throw new Error("previous_stop_proof_invalid")});const fold=await composition.runs.read(runId);if(proof.run_id!==runId||fold.finished===null||fold.finished.status!==proof.status||fold.run.client_thread_id!==session||fold.run.client_turn_id!==turn||fold.run.parent_run_id!==null||fold.run.run_role!=="orchestrator"||fold.run.agent!=="agent-orchestrator")throw new Error("previous_stop_canonical_not_terminal");if(fold.run.task_id!==null){const task=(await composition.tasks.read(fold.run.task_id)).task;if(!["completed","blocked","failed","cancelled"].includes(task.status))throw new Error("previous_stop_task_not_terminal")}}async function regular(path,limit){if(!isAbsolute9(path)||/^(?:\\\\|\/\/)/.test(path)&&!/^\\\\\?\\[a-z]:\\/i.test(path))throw new Error("previous_stop_unsafe_path");const stat5=await lstat11(path);if(!stat5.isFile()||stat5.isSymbolicLink()||identity(await realpath11(path))!==identity(path)||limit!==void 0&&stat5.size>limit)throw new Error("previous_stop_unsafe_file");return stat5}async function precedingTurn(path,session,current){await regular(path);const handle=await open6(path,"r");try{const stat5=await handle.stat();const read=async(offset,length)=>{const buffer=Buffer.alloc(length);const{bytesRead}=await handle.read(buffer,0,length,offset);if(bytesRead!==length)throw new Error("previous_stop_transcript_changed");return buffer};const header=await read(0,Math.min(stat5.size,1024*1024));const end=header.indexOf(10);if(end<0)throw new Error("previous_stop_header_unavailable");const first=JSON.parse(header.subarray(0,end).toString("utf8"));if(first.type!=="session_meta"||(first.payload?.id??first.payload?.session_id)!==session)throw new Error("previous_stop_session_mismatch");const start=Math.max(0,stat5.size-16*1024*1024);const tail=await read(start,stat5.size-start);const aligned=start===0?tail:tail.subarray(tail.indexOf(10)+1);if(start>0&&tail.indexOf(10)<0)throw new Error("previous_stop_tail_unavailable");const lines2=aligned.toString("utf8").split("\n");lines2.pop();const turns=[];let terminal=false;for(const line of lines2){if(!line.trim())continue;if(Buffer.byteLength(line)>8*1024*1024)throw new Error("previous_stop_line_too_large");const row=JSON.parse(line),payload=row.payload;if((row.type==="turn_context"||payload?.type==="task_started")&&typeof payload?.turn_id==="string"&&payload.turn_id!==turns.at(-1)){turns.push(payload.turn_id);if(turns.length>2)turns.shift();terminal=false}if(["task_complete","turn_aborted"].includes(payload?.type)&&payload.turn_id===current)terminal=true}const after=await handle.stat();if(stat5.size!==after.size||stat5.mtimeMs!==after.mtimeMs||stat5.ctimeMs!==after.ctimeMs)throw new Error("previous_stop_transcript_changed");if(turns.length!==2||turns[1]!==current||terminal)throw new Error("previous_stop_live_turn_unverified");return turns[0]}finally{await handle.close()}}async function recoverPreviousStop(filesystem,invocation2,composition){const session=invocation2.clientThreadId,current=invocation2.clientTurnId,path=invocation2.transcriptPath;if(!session||!current||!path)return{state:"skipped",reason:"previous_stop_identity_unavailable"};let previous,runId;try{previous=await precedingTurn(path,session,current);const receiptFile=filesystem.resolve(stopReceiptPath(session,previous));if(!await filesystem.exists(stopReceiptPath(session,previous)))return{state:"skipped",reason:"previous_stop_receipt_missing",previous_turn_id:previous};await regular(receiptFile,1024*1024);const source=JSON.parse(await filesystem.readText(stopReceiptPath(session,previous)));if(source.schema_version!==1||source.session_id!==session||source.turn_id!==previous||!["pending","persisted"].includes(source.state)||source.event?.hook_event_name!=="Stop"||source.event.session_id!==session||source.event.turn_id!==previous||typeof source.event.cwd!=="string"||identity(source.event.cwd)!==identity(filesystem.root)||typeof source.event.transcript_path!=="string"||identity(source.event.transcript_path)!==identity(path))throw new Error("previous_stop_receipt_invalid");const key=hash4(JSON.stringify(["codex",session,previous,null,null]));const correlationPath=`.local/codex-telemetry-spool/v1/correlations/${key}.json`;await regular(filesystem.resolve(correlationPath),16384);const correlation=JSON.parse(await filesystem.readText(correlationPath));if(correlation.schema_version!==1||correlation.thread_id!==session||correlation.turn_id!==previous||correlation.agent_path!==null||typeof correlation.run_id!=="string")throw new Error("previous_stop_correlation_invalid");const root=(await composition.runs.read(correlation.run_id)).run;if(root.parent_run_id!==null||root.run_role!=="orchestrator"||root.agent!=="agent-orchestrator"||root.client_thread_id!==session||root.client_turn_id!==previous||root.task_id!==correlation.task_id||source.run_id!==void 0&&source.run_id!==root.run_id)throw new Error("previous_stop_root_mismatch");runId=root.run_id;if(source.state==="persisted"){await verifyStopPersistence(filesystem,composition,session,previous,runId);return{state:"persisted",reason:null,previous_turn_id:previous,run_id:runId}}await regular(filesystem.resolve(".codex/hooks/zaip-conversation-lifecycle.mjs"),2*1024*1024);const result2=await replayStopReceipt(filesystem,session,previous,{automatic:true});if(result2.state==="persisted")await verifyStopPersistence(filesystem,composition,session,previous,runId);return{state:result2.state==="persisted"?"persisted":"pending",reason:result2.error,previous_turn_id:previous,run_id:runId}}catch(error51){return{state:"pending",reason:error51 instanceof Error?error51.message:"previous_stop_unavailable",...previous===void 0?{}:{previous_turn_id:previous},...runId===void 0?{}:{run_id:runId}}}}var identity,hash4;var init_previous_stop_recovery=__esm({"src/previous-stop-recovery.ts"(){"use strict";init_stop_receipt();identity=path=>process.platform==="win32"?toNamespacedPath2(resolve15(path)).toLowerCase():resolve15(path);hash4=value=>createHash50("sha256").update(value).digest("hex")}});function preview(parsed,filesystem,layout){return resolveConversationContinuation(parsed,createV2Composition(filesystem,layout),filesystem)}async function capture(parsed,filesystem,layout,write){const invocation2=await resolveRunClientInvocation(filesystem,parsed.options.client??"codex");const recovery=await recoverPreviousStop(filesystem,invocation2,createV2Composition(filesystem,layout));const result2=await withLifecycleCanonicalMutationLock(filesystem,()=>write({invocation:invocation2,recovery}),{timeout_ms:15e3});return{...result2,stop_recovery:recovery}}function command(action,parsed,composition,filesystem,lifecycle,captured){const pending=captured?.recovery.state==="pending"?captured.recovery:void 0;return runConversationV2Command(action,parsed,composition,filesystem,lifecycle,captured===void 0?void 0:{invocation:captured.invocation,pendingRun:pending?.run_id,pendingTurn:pending?.previous_turn_id})}async function invocation(filesystem,client,intake2){return intake2?.invocation??await resolveRunClientInvocation(filesystem,client)}async function openIntakes(composition,client,thread,turn,snapshot,intake2){return(await openThreadIntakes(composition,client,thread,turn,snapshot)).filter(fold=>fold.run.run_id!==intake2?.pendingRun&&fold.run.client_turn_id!==intake2?.pendingTurn)}var init_conversation_stop_intake=__esm({"src/conversation-stop-intake.ts"(){"use strict";init_v2_router();init_conversation_intake_settlement();init_conversation_resolution();init_lifecycle_manifest_commands();init_previous_stop_recovery();init_run_client_invocation();init_run_conversation_v2()}});import{execFile as execFileCallback}from"node:child_process";import{promisify as promisify16}from"node:util";async function runDeveloperIdentityCommand(action,parsed,filesystem){if(action==="identity")action=parsed.positionals[2];if(action==="show")return{identity:await readDeveloperIdentityCache(filesystem)};if(action==="set")action="bootstrap";if(action!=="bootstrap")throw new UsageError("developer identity requires show or bootstrap");return{identity:await resolveDeveloperIdentityForRoot(filesystem,{force:true})}}async function resolveDeveloperIdentityForRoot(filesystem,options={}){const now=options.now??new Date;const cached2=await readDeveloperIdentityCache(filesystem);if(cached2!==null&&!options.force&&!developerIdentityNeedsRevalidation(cached2,now)){return cached2}try{const account=await(options.lookup??authenticatedGithubAccount)();return writeDeveloperIdentityCache(filesystem,verifiedDeveloperIdentity(account,now))}catch(error51){if(cached2!==null)return cachedFallbackDeveloperIdentity(cached2);throw new UsageError(`GitHub bootstrap failed; authenticate with gh and retry (${error51 instanceof Error?error51.message:String(error51)})`)}}async function authenticatedGithubAccount(){try{const{stdout}=await execFile16("gh",["api","user"],{encoding:"utf8"});const parsed=JSON.parse(stdout);if(typeof parsed.id!=="number"||!Number.isSafeInteger(parsed.id)||typeof parsed.login!=="string"||parsed.login.length===0)throw new Error("GitHub user response lacks id/login");return{id:String(parsed.id),login:parsed.login}}catch(error51){throw new Error(`GitHub account lookup failed (${error51 instanceof Error?error51.message:String(error51)})`)}}var execFile16;var init_developer_identity_command=__esm({"src/developer-identity-command.ts"(){"use strict";init_src5();init_cli_arguments();execFile16=promisify16(execFileCallback)}});function validatedDirectAuthorization(parsed,clientInvocation,model){const authorization=parsed.options["direct-authorization"];if(authorization===void 0)return void 0;if(!authorization.trim()||clientInvocation.clientThreadId===null||clientInvocation.clientTurnId===null||clientInvocation.clientTurnId.startsWith("local-")||["unknown","unavailable","manual"].includes(model)){throw new UsageError("Direct execution requires an observed Task-scoped delivery root and explicit authorization")}return authorization}var init_direct_authorization=__esm({"src/direct-authorization.ts"(){"use strict";init_cli_arguments()}});function taskAssuranceRiskSignalsOption(value){if(value===void 0)return void 0;try{if(Buffer.byteLength(value,"utf8")>4096)throw new Error("size");return assuranceRiskSignalsSchema.parse(JSON.parse(value))}catch{throw new UsageError("--assurance-risk-signals requires a valid risk-signals JSON object (max 4 KiB)")}}var init_task_assurance_options=__esm({"src/task-assurance-options.ts"(){"use strict";init_src7();init_cli_arguments()}});async function createTaskAndChangeAtomically(filesystem,composition,taskInput){const created=new Map;try{const task=await composition.tasks.createDraft(taskInput);created.set(composition.tasks.path(task.id),composition.tasks.serialize(task));const change=await composition.changes.createDraft({id:task.change_id,title:task.title,risk:task.risk,taskId:task.id,requirementIds:task.requirement_ids,acceptanceIds:task.acceptance_ids});return{task,change}}catch(error51){await rollbackTaskChangeCreation(filesystem,created);throw error51}}async function rollbackTaskChangeCreation(filesystem,created){for(const[path,content]of[...created].reverse()){await filesystem.removeFileIfContentMatches(path,content)}}var init_task_change_creation=__esm({"src/task-change-creation.ts"(){"use strict"}});function compactRunAggregate(aggregate){const bucket=value=>({usage_event_count:value.usage_event_count,tokens:value.tokens,cost:value.cost,coverage:value.coverage});return{scope_id:aggregate.scope_id,run_count:aggregate.run_count,run_coverage:aggregate.run_coverage,attribution:aggregate.attribution,conversation:bucket(aggregate.conversation),planning:bucket(aggregate.planning),execution:bucket(aggregate.execution),total:bucket(aggregate.total),work_types:{new:bucket(aggregate.work_types.new),rework:bucket(aggregate.work_types.rework)}}}function runV2CostInput(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}function runV2Summary(fold,composition){const usage=aggregateRunV2Usage([runV2CostInput(fold)],fold.run.run_id).total;const callIds=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);return{id:fold.run.run_id,status:fold.status,created_at:fold.run.occurred_at,finished_at:fold.finished?.occurred_at??null,phase:latestRunV2Phase(fold.records),run_role:effectiveRunV2Role(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,intake:fold.run.intake??null,agent:fold.run.agent,agent_name:fold.run.agent_name??(fold.run.agent.startsWith("agent-")?`zaip-agent-${fold.run.agent.slice("agent-".length)}`:fold.run.agent),model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,call_count:callIds.size===0?null:callIds.size,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,usage:{event_count:usage.usage_event_count,tokens:usage.tokens,cost:usage.cost,coverage:usage.coverage},artifact_path:composition.runs.path(fold.run.run_id)}}var init_run_conversation_summary=__esm({"src/run-conversation-summary.ts"(){"use strict";init_src4();init_src5();init_conversation_intake_settlement()}});async function assertFinalizationCandidatePreflight(parent,outcome,evidenceIds,changedFiles,composition){if(parent.run.execution_kind!=="delivery")return;const taskId=parent.run.task_id;if(isParentalRelayShape(parent)){const proof=await authenticatedParentalRelay(parent,composition,true);if(!proof||changedFiles.length!==0||outcome==="completed"&&(evidenceIds.length!==proof.parentEvidenceIds.length||new Set(evidenceIds).size!==proof.parentEvidenceIds.length||evidenceIds.some(id=>!proof.parentEvidenceIds.includes(id))))throw new LifecycleGateError("Parental relay Gui requires exact original Evidence and no product changes");return}if(taskId===null){if(outcome==="completed"&&!await hasPassedTypedEvidenceForRun(parent,evidenceIds,composition))throw new LifecycleGateError("finalization-evidence: macro completion requires its passed typed Evidence before Gui decision");if(outcome==="completed"&&parent.run.spec_id!==null&&parent.run.entrypoint==="spec"){const{execution}=await composition.executions.read(parent.run.execution_id);const{spec}=await composition.specs.read(parent.run.spec_id);const context2=await parentalProofTasks(spec.id,execution.id,composition);const configured2=composition.layout.projectConfig?.assurance;await assertParentDeliveryPreflight({filesystem:composition.filesystem,layout:composition.layout,repositories:composition,spec_id:spec.id,execution_id:execution.id,acceptance_ids:spec.acceptance_ids,...context2,assurance:configured2?.version===1?configured2:{standard_depth:"auto",require_final_commit:true},selected_evidence_ids:evidenceIds,composition})}return}const executionId=parent.run.execution_id;if(executionId===null)throw new LifecycleGateError("Gui Task decision requires a delivery Execution");const{task}=await composition.tasks.read(taskId).catch(()=>{throw new LifecycleGateError(`Gui responsible Task is unavailable: ${taskId}`)});const boundary=await historicalPublishedBoundaryForTask(task,parent,composition);assertHistoricalRelayChangedFiles(boundary,changedFiles);await assertChangedFilesInScopeOrCausalRecords(task,changedFiles,composition.filesystem,executionId,composition);if(outcome!=="completed")return;if(!await hasPassedTypedEvidenceForRun(parent,evidenceIds,composition)){throw new LifecycleGateError("finalization-evidence: completed Gui decision requires passed typed Evidence linked to the same Task, Change, Execution, and Run and one candidate")}const configured=composition.layout.projectConfig?.assurance;const config2=configured?.version===1?configured:{standard_depth:"auto",require_final_commit:false};if(!effectiveTaskAssurance(task,config2).require_final_commit)return;const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,[task],evidenceIds);await requireFinalProductCandidate(composition.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,changedFiles,boundary??void 0)}var init_finalization_candidate_preflight=__esm({"src/finalization-candidate-preflight.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_v2_delivery_assurance();init_parent_delivery_preflight();init_post_publication_parental();init_run_finalization_evidence_v2()}});function assertFinalizationEvidenceInput(ids2){if(ids2.some(id=>!/^EVD-[A-Z0-9-]+$/.test(id))){throw new UsageError("Finalization --evidence accepts comma-separated EVD IDs only, not JSON, Decision IDs or file paths")}return ids2}var init_finalization_evidence_input=__esm({"src/finalization-evidence-input.ts"(){"use strict";init_cli_arguments()}});function activeRunIds(value){if(typeof value!=="object"||value===null||value.schema_version!==1||!Array.isArray(value.items))return[];return value.items.flatMap(item=>{if(typeof item!=="object"||item===null)return[];const candidate=item;return candidate.kind==="run"&&candidate.status==="running"&&typeof candidate.id==="string"?[candidate.id]:[]})}function activeRunWindow(ids2,now=Date.now(),limit=32){if(!Number.isSafeInteger(limit)||limit<1||limit>32)throw new Error("Active telemetry limit must be an integer between 1 and 32");if(ids2.length===0)return ids2;const minute=Math.floor(now/6e4);const start=minute*(ids2.length<=limit?1:limit)%ids2.length;return Array.from({length:Math.min(limit,ids2.length)},(_value,index)=>ids2[(start+index)%ids2.length])}var init_v2_run_active_window=__esm({"src/source-size-cli/v2-run-active-window.ts"(){"use strict"}});import{createHash as createHash51}from"node:crypto";function nextRecentTelemetryWindow(ids2,limit,cursor){if(!Number.isSafeInteger(limit)||limit<1||limit>32)throw new UsageError("Recent telemetry limit must be an integer between 1 and 32");const candidate_sha256=createHash51("sha256").update(JSON.stringify(ids2)).digest("hex");const valid2=cursor?.schema_version===1&&Array.isArray(cursor.visited_ids)&&cursor.visited_ids.length<=512&&cursor.visited_ids.every(id=>typeof id==="string")&&Number.isSafeInteger(cursor.next_offset)&&cursor.next_offset>=0;const known2=new Set(ids2);const visited=new Set(valid2?cursor.visited_ids.filter(id=>known2.has(id)):[]);const pending=ids2.filter(id=>!visited.has(id));const offset=valid2?cursor.next_offset%Math.max(ids2.length,1):0;const selected=pending.length>0?pending.slice(0,limit):ids2.length===0?[]:Array.from({length:Math.min(limit,ids2.length)},(_value,index)=>ids2[(offset+index)%ids2.length]);const prior_visited_ids=[...visited];for(const id of selected)visited.add(id);const complete=visited.size===ids2.length;const next_offset=ids2.length===0?0:(offset+selected.length)%ids2.length;return{selected,prior_visited_ids,complete,pending_count:ids2.length-visited.size,cursor:{schema_version:1,candidate_sha256,visited_ids:[...visited],next_offset,complete}}}function recentTelemetrySegmentFinder(list=listRecentCodexSegments){const sessions=new Map;return async(root,keys2,options={})=>{const key=JSON.stringify([root,options.threadId??null,options.agentPath??null,options.parentThreadId??null,options.transcriptPath??null]);let pending=sessions.get(key);if(pending===void 0){pending=list(root,new Set,{...options,turnId:null,startedAfter:null});sessions.set(key,pending)}return[...await pending].filter(segment2=>!keys2.has(segment2.segmentKey)&&segment2.turnId===options.turnId&&(!options.requireTaskComplete||segment2.terminalType==="task_complete")).sort((left,right)=>(left.finishedAt??left.startedAt??"").localeCompare(right.finishedAt??right.startedAt??"")).at(-1)??null}}async function captureActiveRunTelemetry(parsed,composition,filesystem){if(!parsed.flags.has("disable-codex-raw"))throw new UsageError("run usage --active requires --disable-codex-raw");const activeIds=activeRunIds(await new LifecycleManifestStore(filesystem).readActiveWork());const captured=[];for(const id of activeRunWindow(activeIds,Date.now(),numberOption(parsed.options.limit,32))){const fold=await composition.runs.read(id);if(fold.finished===null&&isCodexTelemetryClient(fold.run.client)&&fold.run.client_turn_id!==null){const current=await recordCodexTelemetryIfAvailable(fold,composition,filesystem);captured.push({run_id:id,captured:current.records.length>fold.records.length})}}return{telemetry:{mode:"active_exact_session",captured},artifact_path:null}}function recentTelemetryRunIds(entities,now=Date.now()){const cutoff=now-72*60*60*1e3;return entities.filter(entity=>{const data2=entity.data;const terminalSourceMeasured=typeof data2?.source_finished_at==="string"&&Number.isFinite(Date.parse(data2.source_finished_at))&&entity.usage?.total_tokens!=null;return entity.kind==="run"&&data2!==null&&!terminalSourceMeasured&&Date.parse(entity.updated_at)>=cutoff&&typeof data2.client==="string"&&isCodexTelemetryClient(data2.client)&&typeof data2.client_thread_id==="string"&&data2.client_thread_id.length>0&&typeof data2.client_turn_id==="string"&&data2.client_turn_id.length>0&&(entity.status==="running"||entity.usage?.total_tokens==null||data2.call_coverage==="unavailable")}).map(entity=>entity.id).sort()}async function captureRecentRunTelemetry(parsed,composition,filesystem,capture2=recordCodexTelemetryIfAvailable,batchCapture=recordCodexTelemetryBatch,clock=Date.now){if(!parsed.flags.has("disable-codex-raw"))throw new UsageError("run usage --recent requires --disable-codex-raw");if(parsed.flags.has("active"))throw new UsageError("Choose only one telemetry window: --active or --recent");const automatic=!parsed.flags.has("drain");const startedAt=clock();let readEntitiesMs=0;let selectionMs=0;let runReadMs=0;let captureMs=0;let lastGroupMs=0;let preparationPending=false;let lastRunId=null;let examined=0;let candidateCount=null;let pendingCount=null;const report=async(phase2,runId=lastRunId)=>{if(!automatic||typeof filesystem.writeTextAtomic!=="function")return;await filesystem.writeTextAtomic(recentProgressPath,`${JSON.stringify({schema_version:1,phase:phase2,last_run_id:runId,candidate_count:candidateCount,processed_count:examined,pending_count:pendingCount,read_entities_ms:readEntitiesMs,selection_ms:selectionMs,run_read_ms:runReadMs,capture_ms:captureMs,elapsed_ms:clock()-startedAt,updated_at:new Date().toISOString()})}
3598
+ `;if(Buffer.byteLength(serialized,"utf8")>64*1024)throw new Error("Unmatched Codex telemetry envelope exceeds the 64 KiB sanitized limit");try{await filesystem.writeTextAtomicExclusive(`.local/codex-telemetry-spool/v1/unmatched/${digest14.slice(0,2)}/${digest14}.json`,serialized)}catch(error51){if(!(error51 instanceof Error&&"code"in error51&&error51.code==="EEXIST"))throw error51}}function sanitizeAppServerNotification(input,capturedAt){const notification=hostObject(input,"Codex app-server notification");const method=String(notification.method);if(!["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"].includes(method))return null;const params=hostObject(notification.params,`${method} params`);const threadId=hostString(params.threadId,`${method} threadId`);const rawAgentPath=params.agentPath??params.agent_path;const agentPath=rawAgentPath===void 0?null:hostString(rawAgentPath,`${method} agentPath`);const occurredAt=hostTimestamp(notification.emittedAtMs);const wrap=(turnId2,event)=>({threadId,turnId:turnId2,agentPath,event:{source:"codex_app_server",source_occurred_at:occurredAt,captured_at:capturedAt,coverage:"complete",provider:null,model:null,runtime:{reasoning_effort:null,service_tier:null},latency_ms:null,context_stats:null,...event}});if(method==="item/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);const item=hostObject(params.item,`${method} item`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"item_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:item:${hostString(item.id,`${method} item id`)}`,"item"),source_occurred_at:hostTimestamp(params.completedAtMs)??occurredAt,tokens:null,status:null,discarded_counts:discardedItem(String(item.type??""),item)})}if(method==="rawResponse/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"response_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:raw-response:${hostString(params.responseId,`${method} responseId`)}`,"response"),tokens:params.usage===null?null:hostTokens(params.usage,method),status:null,discarded_counts:{...emptyDiscarded(),response_text:Number(typeof params.output==="string")}})}if(method==="thread/tokenUsage/updated"){const turnId2=hostString(params.turnId,`${method} turnId`);const tokens2=hostTokens(hostObject(params.tokenUsage,`${method} tokenUsage`).total,method);const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify(tokens2)).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"usage",source_method:method,stream_boundary:"usage_updated",source_event_key:hostSourceKey(`${threadId}:${turnId2}:token-usage:${suffix}`,"usage"),tokens:tokens2,status:null,discarded_counts:emptyDiscarded()})}if(method==="error"){const turnId2=hostString(params.turnId,`${method} turnId`);const error52=isHostObject(params.error)?params.error:{};const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify([params.willRetry===true,error52.codexErrorInfo??null])).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"error",source_method:method,stream_boundary:"error",source_event_key:hostSourceKey(`${threadId}:${turnId2}:error:${suffix}`,"error"),tokens:null,status:params.willRetry===true?null:"failed",will_retry:params.willRetry===true,discarded_counts:{...emptyDiscarded(),secrets:Number(typeof error52.message==="string")+Number(typeof error52.additionalDetails==="string")}})}const turn=hostObject(params.turn,"turn/completed turn");const turnId=hostString(turn.id,"turn/completed turn id");if(!["completed","failed","interrupted"].includes(String(turn.status)))throw new Error(`turn/completed has non-terminal status: ${String(turn.status)}`);const discarded=(Array.isArray(turn.items)?turn.items.filter(isHostObject):[]).map(item=>discardedItem(String(item.type??""),item)).reduce(addDiscarded,emptyDiscarded());const error51=isHostObject(turn.error)?turn.error:{};return wrap(turnId,{event_kind:"terminal",source_method:"turn/completed",stream_boundary:"turn_completed",source_event_key:hostSourceKey(`${threadId}:${turnId}:terminal`,"terminal"),source_occurred_at:hostTimestamp(typeof turn.completedAt==="number"?turn.completedAt*1e3:turn.completedAt)??occurredAt,tokens:null,status:turn.status==="interrupted"?"cancelled":turn.status,latency_ms:Number.isSafeInteger(turn.durationMs)&&Number(turn.durationMs)>=0?Number(turn.durationMs):null,discarded_counts:{...discarded,secrets:discarded.secrets+Number(typeof error51.message==="string")+Number(typeof error51.additionalDetails==="string")}})}function hostObject(value,label){if(!isHostObject(value))throw new Error(`${label} must be an object`);return value}function hostString(value,label){if(typeof value!=="string"||value.length===0)throw new Error(`${label} must be a non-empty string`);return value}function hostCount(value,label){if(!Number.isSafeInteger(value)||Number(value)<0)throw new Error(`${label} must be a non-negative safe integer`);return Number(value)}function hostTokens(value,label){const usage=hostObject(value,`${label} usage`);const input=hostCount(usage.inputTokens,`${label} inputTokens`);const cacheWriteInput=usage.cacheWriteInputTokens===void 0?null:hostCount(usage.cacheWriteInputTokens,`${label} cacheWriteInputTokens`);if(cacheWriteInput!==null&&cacheWriteInput>input){throw new Error(`${label} cacheWriteInputTokens cannot exceed inputTokens`)}return{input,cached_input:hostCount(usage.cachedInputTokens,`${label} cachedInputTokens`),cache_write_input:cacheWriteInput,output:hostCount(usage.outputTokens,`${label} outputTokens`),reasoning:hostCount(usage.reasoningOutputTokens,`${label} reasoningOutputTokens`),total:hostCount(usage.totalTokens,`${label} totalTokens`),source:"provider_reported"}}var emptyDiscarded,addDiscarded,discardedItem,isHostObject,hostTimestamp,hostDigest,hostSourceKey;var init_codex_app_server_notifications=__esm({"src/codex-app-server-notifications.ts"(){"use strict";init_src5();init_codex_telemetry_compaction();init_codex_telemetry_preparation();emptyDiscarded=()=>({prompt:0,response_text:0,reasoning:0,secrets:0});addDiscarded=(left,right)=>({prompt:left.prompt+right.prompt,response_text:left.response_text+right.response_text,reasoning:left.reasoning+right.reasoning,secrets:left.secrets+right.secrets});discardedItem=(type,item)=>({prompt:Number(["userMessage","hookPrompt","function_call","custom_tool_call"].includes(type)),response_text:Number(["agentMessage","plan","message","agent_message"].includes(type)),reasoning:Number(type==="reasoning"),secrets:Number(typeof item.encrypted_content==="string")+Number(item.internal_chat_message_metadata_passthrough!==void 0)});isHostObject=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);hostTimestamp=value=>typeof value==="number"&&Number.isFinite(value)&&value>=0?new Date(value).toISOString():null;hostDigest=value=>createHash48("sha256").update(value).digest("hex");hostSourceKey=(value,prefix)=>value.length<=500?value:`${prefix}:${hostDigest(value)}`}});function aggregateEstimatedCallCosts(estimates,fxRate){const sum=values=>{const known2=values.filter(value=>value!==null);if(known2.length!==values.length)return null;return Math.round(known2.reduce((total,value)=>total+value,0)*1e6)/1e6};const usd=sum(estimates.map(estimate=>estimate.estimated_usd));return{usd,brl:usd===null||fxRate===null?null:Math.round(usd*fxRate.rate*1e6)/1e6,fx_rate:fxRate?.rate??null}}var init_codex_telemetry_call_costs=__esm({"src/codex-telemetry-call-costs.ts"(){"use strict"}});function fallbackCallIdentity(sourceCallKey){return[sourceCallKey,modelCallId(sourceCallKey)]}function hasNoObservedTokenDelta(tokens2){return tokens2.total===0&&[tokens2.input,tokens2.cached_input,tokens2.cache_write_input,tokens2.output,tokens2.reasoning].every(value=>value==null||value===0)}var init_codex_telemetry_call_identity=__esm({"src/codex-telemetry-call-identity.ts"(){"use strict";init_codex_telemetry_runtime()}});import{AsyncLocalStorage}from"node:async_hooks";var capturePass;var init_codex_telemetry_capture_pass=__esm({"src/codex-telemetry-capture-pass.ts"(){"use strict";capturePass=new AsyncLocalStorage}});function fallbackUsageLoops(candidate,loops,previous){if(previous.length===0)return loops;const attributed=sumObservedUsage(previous);for(let index=0;index<=loops.length;index+=1){if(sameUsage(aggregateSegmentUsage({...candidate,loops:loops.slice(0,index)}),attributed))return loops.slice(index)}return[]}function sameUsage(left,right){return left.input===right.input&&left.cached_input===right.cached_input&&left.cache_write_input===right.cache_write_input&&left.output===right.output&&left.reasoning===right.reasoning&&left.total===right.total}function validatedTranscriptEnvironmentPath(){const value=process.env.CODEX_TRANSCRIPT_PATH;if(typeof value!=="string")return null;const normalized=value.trim();return normalized.length>0&&normalized.length<=4096?normalized:null}var init_codex_telemetry_fallback_usage=__esm({"src/codex-telemetry-fallback-usage.ts"(){"use strict";init_src4();init_codex_telemetry_runtime()}});async function prepareFallbackProposals(folds,composition,filesystem,finder){const proposals=new Map;const transcriptPath=validatedTranscriptEnvironmentPath();for(const fold of folds){if(fold.run.same_turn_handoff!==void 0)continue;if(fold.finished!==null&&unavailableUsageEventId(fold)===null)continue;const source=await exactTelemetrySource(fold,composition);const key=JSON.stringify(source);if(source.turnId!==null&&!proposals.has(key))proposals.set(key,await finder(filesystem.root,new Set,{...source,startedAfter:fold.run.occurred_at,...transcriptPath===null?{}:{transcriptPath,requireTaskComplete:true}}))}return proposals}var init_codex_telemetry_proposals=__esm({"src/codex-telemetry-proposals.ts"(){"use strict";init_codex_telemetry_fallback_usage();init_codex_telemetry_preparation();init_codex_telemetry_runtime()}});async function hookTrackingEnabled(filesystem){if(process.env.ZAIP_HOOK_TRACKING_ENABLED==="false")return false;try{return(await loadWorkspaceLayout(filesystem)).projectConfig?.tracking.enabled===true}catch{return false}}var init_hook_tracking_policy=__esm({"src/hook-tracking-policy.ts"(){"use strict";init_src()}});async function recordNativeCodexUsage(current,composition,events){const exactCalls=events.filter(event=>event.event.stream_boundary==="response_completed"&&event.event.tokens!==null);const latestCumulative=events.findLast(event=>event.event.stream_boundary==="usage_updated"&&event.event.tokens!==null);const terminal=events.findLast(event=>event.event.stream_boundary==="turn_completed"||event.event.stream_boundary==="error"&&event.event.will_retry!==true);const usageEvents=exactCalls.length>0?exactCalls:latestCumulative?[latestCumulative]:[];if(usageEvents.length===0&&terminal===void 0)return current;let fresh=current;let sequence=current.records.length+1;const agentInvocationId=current.run.agent_invocation_id??`AINV-${current.run.run_id.slice("RUN-".length)}`;for(const call of exactCalls){const event=call.event;if(event.tokens===null)continue;const coverage2=terminal===void 0?"partial":"complete";const existing=fresh.model_call_records.find(record3=>record3.source_call_key===event.source_event_key);if(existing===void 0||existing.coverage==="partial"&&coverage2==="complete"){await composition.runs.appendRecord(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:event.captured_at,type:"model.call.observed",call_id:modelCallId(event.source_event_key),agent_invocation_id:agentInvocationId,coverage:coverage2,tokens:event.tokens,cost:{usd:null,brl:null},provider:event.provider,model:event.model,source_call_key:event.source_event_key,...event.source_occurred_at===null?{}:{source_occurred_at:event.source_occurred_at},runtime:event.runtime}));fresh=await composition.runs.read(current.run.run_id)}}const sourceSegmentKey=`codex-app-server:${current.run.run_id}`;if(usageEvents.length>0&&!fresh.effective_usage_records.some(record3=>record3.source_segment_key===sourceSegmentKey)){const tokens2=sumObservedUsage(usageEvents.map(event=>event.event.tokens));await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestPhase(current),activity_kind:"implementation",classification_source:"current_context",tokens:tokens2,cost:{usd:null,brl:null},provider:commonObservedValue(usageEvents.map(event=>event.event.provider)),model:commonObservedValue(usageEvents.map(event=>event.event.model)),source_segment_key:sourceSegmentKey,runtime:{reasoning_effort:commonObservedValue(usageEvents.map(event=>event.event.runtime.reasoning_effort)),service_tier:commonObservedValue(usageEvents.map(event=>event.event.runtime.service_tier))},supersedes_event_id:unavailableUsageEventId(current),...latestSourceTimestamp(usageEvents)===null?{}:{source_occurred_at:latestSourceTimestamp(usageEvents)}}));fresh=await composition.runs.read(current.run.run_id)}if(terminal===void 0||terminal.event.status===null)return fresh;const callKeys=exactCalls.length>0?exactCalls.map(call=>call.event.source_event_key):[terminal.event.source_event_key];for(const callKey of callKeys){const invocationId2=providerInvocationId(callKey);if(!fresh.model_selection_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(modelSelectionRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"model.selection.recorded",invocation_id:invocationId2,requested:{model:current.run.model,reasoning_effort:current.run.reasoning_effort??null,velocity:"standard"},selection:{source:"execution-override",policy_version:1,reasons:["host-run-header"]}}));fresh=await composition.runs.read(current.run.run_id)}if(!fresh.provider_invocation_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(providerInvocationFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"provider.invocation.finished",invocation_id:invocationId2,status:terminal.event.status,effective:{provider:terminal.event.provider,model:terminal.event.model,reasoning_effort:terminal.event.runtime.reasoning_effort,service_tier:terminal.event.runtime.service_tier},latency_ms:terminal.event.latency_ms}));fresh=await composition.runs.read(current.run.run_id)}}return fresh}var init_codex_telemetry_native=__esm({"src/codex-telemetry-native.ts"(){"use strict";init_src5();init_codex_telemetry_runtime()}});async function recordCodexTelemetryBatch(folds,composition,filesystem,finder=findLatestCodexSegment,options={}){if(folds.length===0)return[];if(!await hookTrackingEnabled(filesystem))return[...folds];const proposals=await prepareFallbackProposals(folds,composition,filesystem,finder);return composition.runs.withUsageAttributionLock(async()=>{const native=await withPreparedCodexTelemetry(filesystem,async events=>events,options);const pass={runs:composition.runs,filesystem,native,compact:false};return capturePass.run(pass,async()=>{const results=[];try{for(const fold of folds){const current=await recordCodexTelemetryIfAvailable(fold,composition,filesystem,null,[],async(_root,_keys,source)=>proposals.get(JSON.stringify({agentPath:source?.agentPath??null,parentThreadId:source?.parentThreadId??null,threadId:source?.threadId??null,turnId:source?.turnId??null}))??null);results.push(current);if(pass.owners!==void 0)pass.owners=pass.owners.map(owner=>owner.run.run_id===current.run.run_id?current:owner)}return results}finally{if(pass.compact)await compactPendingCodexTelemetry(filesystem)}})})}async function recordCodexTelemetryIfAvailable(current,composition,filesystem,sourceOverride=null,appServerNotifications=[],fallbackSegmentFinder=findLatestCodexSegment){if(!await hookTrackingEnabled(filesystem))return current;if(current.run.same_turn_handoff!==void 0)return current;if(!isCodexTelemetryClient(current.run.client)||current.run.client_thread_id===null&&current.run.client_turn_id===null){return current}const transcriptPath=validatedTranscriptEnvironmentPath();const pass=capturePass.getStore();const batch=pass?.runs===composition.runs&&pass.filesystem===filesystem?pass:void 0;const lock2=operation=>batch===void 0?composition.runs.withUsageAttributionLock(operation):operation();const collect=fresh=>batch===void 0?collectAvailableNativeUsage(fresh,composition,filesystem,recordNativeCodexUsage):collectNativeUsageFromSnapshot(fresh,composition,batch.native,recordNativeCodexUsage);const preparation=await lock2(async()=>{const fresh=await composition.runs.read(current.run.run_id);if(appServerNotifications.length>0){await ingestCodexAppServerNotifications(filesystem,appServerNotifications)}const observed=await collect(fresh);if(batch!==void 0&&observed!==null)batch.compact=true;if(observed!==null)return{kind:"done",fold:observed};if(fresh.finished!==null&&unavailableUsageEventId(fresh)===null)return{kind:"done",fold:fresh};if(sourceOverride===null&&fresh.run.client_turn_id===null)return{kind:"done",fold:fresh};const source=sourceOverride??await exactTelemetrySource(fresh,composition);if(source.turnId===null)return{kind:"done",fold:fresh};return{kind:"fallback",fold:fresh,source}});if(preparation.kind==="done")return preparation.fold;const candidate=await fallbackSegmentFinder(filesystem.root,new Set,{startedAfter:preparation.fold.run.occurred_at,...preparation.source,...transcriptPath===null?{}:{transcriptPath,requireTaskComplete:true}});return lock2(async()=>{const freshCurrent=await composition.runs.read(current.run.run_id);const observed=await collect(freshCurrent);if(batch!==void 0&&observed!==null)batch.compact=true;if(observed!==null)return observed;const source=sourceOverride??await exactTelemetrySource(freshCurrent,composition);const exactTurn=source.turnId;const timestamp13=Date.parse(candidate?.finishedAt??candidate?.loops.at(-1)?.timestamp??"");if(candidate===null||!Number.isFinite(timestamp13)||exactTurn===null||candidate.turnId!==exactTurn||JSON.stringify(source)!==JSON.stringify(preparation.source))return freshCurrent;const postTerminalPhase=freshCurrent.finished?.phase??null;const postTerminal=postTerminalPhase!==null;const supersededUnavailableUsageId=unavailableUsageEventId(freshCurrent);if(postTerminal&&supersededUnavailableUsageId===null)return freshCurrent;const candidateLoops=Array.from(new Map(candidate.loops.map(loop=>[`${candidate.segmentKey}:loop:${loop.cycleIndex}`,loop])).values());const newCandidateLoops=candidateLoops.filter(loop=>shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`));const localPrevious=freshCurrent.effective_usage_records.filter(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true);if(localPrevious.some(record3=>record3.source_segment_key===candidate.segmentKey))return freshCurrent;const localDelta=observedUsageDelta(aggregateSegmentUsage({...candidate,loops:candidateLoops}),localPrevious.map(record3=>record3.tokens));if(candidate.finishedAt===null&&newCandidateLoops.length===0&&hasNoObservedTokenDelta(localDelta))return freshCurrent;const allRuns=batch?.owners??await composition.runs.list();if(batch!==void 0)batch.owners=allRuns;const existingOwner=allRuns.find(fold=>fold.run.run_id!==freshCurrent.run.run_id&&fold.effective_usage_records.some(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true));if(existingOwner!==void 0)return freshCurrent;const model=candidate.model??freshCurrent.run.model;const provider=inferProvider(model,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const correlation=codexTelemetryCorrelationFromRun(freshCurrent.run);if(correlation===null)return freshCurrent;const capturedAt=new Date().toISOString();const pricing=new PricingRepository(filesystem);const catalog=await pricing.readCatalog();const fxRate=await pricing.readLatestFxRate();const spooledLoops=[];if(batch!==void 0&&(newCandidateLoops.length>0||candidate.finishedAt!==null))batch.compact=true;for(const loop of candidateLoops){if(!shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`))continue;const loopModel=loop.model??model;const loopProvider=inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const historical_cost=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null});spooledLoops.push(await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"usage",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:loop:${loop.cycleIndex}`,source_occurred_at:loop.timestamp,captured_at:capturedAt,coverage:"partial",tokens:loop.usage,provider:loopProvider,model:loopModel,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:null,latency_ms:null,historical_cost,context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}}))}if(candidate.finishedAt!==null){await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"terminal",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:terminal`,source_occurred_at:candidate.finishedAt,captured_at:capturedAt,coverage:"partial",tokens:null,provider,model,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:"completed",latency_ms:elapsedMilliseconds(candidate.startedAt,candidate.finishedAt),context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}})}const cumulative=aggregateSegmentUsage({...candidate,loops:candidateLoops});const previous=allRuns.filter(fold=>fold.run.run_id===freshCurrent.run.run_id||exactTurn!==null&&fold.run.client_turn_id===exactTurn).flatMap(fold=>fold.effective_usage_records).filter(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true);const usageLoops=fallbackUsageLoops(candidate,candidateLoops,previous.map(record3=>record3.tokens));if(candidate.finishedAt!==null&&previous.some(record3=>record3.source_segment_key===candidate.segmentKey))return freshCurrent;const tokens2=observedUsageDelta(cumulative,previous.map(record3=>record3.tokens));const usageSourceSegmentKey=candidate.finishedAt===null?`${candidate.segmentKey}@active:${hostDigest(JSON.stringify(cumulative))}`:candidate.segmentKey;const zeroTokenDelta=hasNoObservedTokenDelta(tokens2);const activeUsageToClose=candidate.finishedAt===null||!zeroTokenDelta?null:previous.findLast(record3=>record3.source_segment_key?.startsWith(`${candidate.segmentKey}@active:`)===true)??null;if(zeroTokenDelta&&activeUsageToClose===null){return freshCurrent}if(candidate.finishedAt===null&&usageLoops.length===0)return freshCurrent;const estimated=aggregateEstimatedCallCosts(usageLoops.map(loop=>{const loopModel=loop.model??model;return estimateUsageCost({provider:inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent),model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null})}),fxRate);const agentInvocationId=freshCurrent.run.agent_invocation_id??`AINV-${freshCurrent.run.run_id.slice("RUN-".length)}`;let sequence=freshCurrent.records.length+1;const fallbackCallIdentities=new Set(freshCurrent.model_call_records.flatMap(record3=>[record3.source_call_key,record3.call_id].filter(value=>typeof value==="string")));const pendingRecords=[];for(const spooled of spooledLoops){const loop=spooled.event;if(loop.tokens===null)continue;const loopModel=loop.model??freshCurrent.run.model;const loopProvider=inferProvider(loopModel,loop.provider??freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const loopEstimated=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.tokens,catalog,fxRate,serviceTier:candidate.serviceTier??null});const sourceCallKey=loop.source_event_key;const identities=fallbackCallIdentity(sourceCallKey);if(postTerminal||!shouldAppendFallbackModelCall(freshCurrent.model_call_records,sourceCallKey)||identities.some(identity2=>fallbackCallIdentities.has(identity2))){continue}pendingRecords.push(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"model.call.observed",call_id:modelCallId(sourceCallKey),agent_invocation_id:agentInvocationId,coverage:"partial",tokens:loop.tokens,cost:{usd:loopEstimated.estimated_usd,brl:loopEstimated.estimated_brl,fx_rate:loopEstimated.fx_rate},provider:loopProvider,model:loopModel,source_call_key:sourceCallKey,...loop.source_occurred_at===null?{}:{source_occurred_at:loop.source_occurred_at},runtime:loop.runtime}));for(const identity2 of identities)fallbackCallIdentities.add(identity2)}const usage=usageRecordedV2Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:postTerminal?postTerminalPhase:latestPhase(freshCurrent),activity_kind:postTerminal?"retrospective_local_remeasurement":"implementation",classification_source:"current_context",tokens:activeUsageToClose?.tokens??tokens2,cost:activeUsageToClose!==null?activeUsageToClose.cost:{usd:estimated.usd,brl:estimated.brl,fx_rate:estimated.fx_rate},provider,model,source_segment_key:usageSourceSegmentKey,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},supersedes_event_id:activeUsageToClose?.event_id??supersededUnavailableUsageId,...postTerminal?{retrospective_correction:true}:{},source_occurred_at:candidate.finishedAt??candidate.startedAt??void 0,source_started_at:candidate.startedAt??void 0,source_finished_at:candidate.finishedAt??void 0});pendingRecords.push(usage);await composition.runs.appendRecords(pendingRecords);if(batch===void 0)await compactPendingCodexTelemetry(filesystem);else batch.compact=true;return composition.runs.read(freshCurrent.run.run_id)})}var init_record_codex_telemetry=__esm({"src/record-codex-telemetry.ts"(){"use strict";init_src4();init_src5();init_codex_app_server_notifications();init_codex_telemetry_call_costs();init_codex_telemetry_call_identity();init_codex_telemetry_capture_pass();init_codex_telemetry_compaction();init_codex_telemetry_fallback_usage();init_codex_telemetry_proposals();init_hook_tracking_policy();init_codex_app_server_notifications();init_codex_telemetry_native();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source()}});async function openThreadIntakes(composition,client,clientThreadId,currentTurnId,candidates){if(clientThreadId===null)return[];const availableRuns=candidates??await composition.runs.list();return availableRuns.filter(fold=>fold.finished===null&&fold.run.client===client&&fold.run.client_thread_id===clientThreadId&&fold.run.parent_run_id===null&&fold.run.intake!=null&&!runV2RequiresFinalizer(fold.run)&&descendantRuns(fold.run.run_id,availableRuns).length===0&&fold.run.client_turn_id!==currentTurnId)}async function finishOpenThreadIntakes(openIntakes2,composition,filesystem,parsed,lifecycle){const settled=[];for(const intake2 of openIntakes2){const candidateRuns=await composition.runs.list();if(descendantRuns(intake2.run.run_id,candidateRuns).length>0||activeDescendantRuns(intake2.run.run_id,candidateRuns).length>0){continue}let current=intake2;current=await recordCodexTelemetryIfAvailable(current,composition,filesystem,null,await codexAppServerNotifications(parsed,filesystem));if(current.effective_usage_records.length===0){await recordUnavailableCodexTelemetryToSpool(current,filesystem,"completed");await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,current.records.length+1),run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"completed"}));const run=await composition.runs.read(current.run.run_id);settled.push({run,reconciliation:await reconcileFinishedRunLifecycle(run,composition,lifecycle,{candidateRuns})})}return settled}function settledIntakesForView(settled,view){if(view==="full")return settled;return settled.map(({run,reconciliation})=>({run_id:run.run.run_id,status:run.status,phase:latestRunV2Phase(run.records),execution_id:run.run.execution_id,task_id:run.run.task_id,change_id:run.run.change_id,record_count:run.records.length,usage_record_count:run.effective_usage_records.length,model_call_count:run.model_call_records.length,reconciliation:{status:reconciliation.status,outcome:reconciliation.outcome,task_count:reconciliation.tasks.length,change_count:reconciliation.changes.length,execution_count:reconciliation.executions.length,spec_count:reconciliation.specs.length,prd_count:reconciliation.prds.length}}))}async function codexAppServerNotifications(parsed,filesystem){const path=parsed.options["codex-app-server-events"];return path===void 0?[]:parseCodexAppServerNotificationStream(await filesystem.readText(path))}function runMatchesTarget(fold,target){return target.taskId!==void 0&&fold.run.task_id===target.taskId||target.specId!==void 0&&fold.run.spec_id===target.specId||target.prdId!==void 0&&fold.run.prd_id===target.prdId}async function recordContextPackUsage(runId,initialPackTokens,composition){const current=await composition.runs.read(runId);if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${runId}`);const sequence=current.records.length+1;await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(runId,sequence),run_id:runId,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"context_build",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:`context-pack:${runId}:${sequence}`,supersedes_event_id:null,source_occurred_at:new Date().toISOString(),context_stats:{initial_pack_tokens:initialPackTokens,tool_output_tokens:null,files_opened:null,snippets_opened:null}}))}function unavailableUsageRecord(current,parsed,sequence){const occurredAt=new Date().toISOString();return usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,sequence),run_id:current.run.run_id,sequence,occurred_at:occurredAt,type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"run_finalize",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:null,supersedes_event_id:null,...runUsageMetadataOptions(parsed.options,occurredAt)})}function latestRunV2Phase(records){const latest=records.findLast(record3=>"phase"in record3);return latest?.phase??"conversation"}function runV2EventId(runId,sequence){return`${runId}:${String(sequence).padStart(6,"0")}`}var init_conversation_intake_settlement=__esm({"src/conversation-intake-settlement.ts"(){"use strict";init_src5();init_cli_arguments();init_record_codex_telemetry();init_run_hierarchy();init_run_lifecycle_reconciliation()}});function continuationPredecessor(candidates,target){const responsible=candidates.filter(fold=>runMatchesTarget(fold,target)&&fold.run.agent==="agent-orchestrator"&&(target.taskId!==void 0?fold.run.task_id===target.taskId:fold.run.task_id===null));const active=responsible.filter(fold=>fold.finished===null&&(fold.run.requires_finalizer===true||fold.run.execution_kind==="delivery"));if(active.length>0)throw new UsageError(`Continuation still has an active responsible Run: ${active.map(fold=>fold.run.run_id).join(", ")}; reconcile its observed terminal event and Gui before a new root`);return responsible.filter(fold=>fold.finished!==null&&fold.finished!==void 0).sort((left,right)=>(right.finished?.occurred_at??"").localeCompare(left.finished?.occurred_at??""))[0]?.run.run_id??null}function resolveContinuationPredecessor(candidates,openIntakes2,target){if(target===null)return null;return continuationPredecessor(candidates,target)??openIntakes2.find(fold=>runMatchesTarget(fold,target))?.run.run_id??null}var init_conversation_continuation_owner=__esm({"src/conversation-continuation-owner.ts"(){"use strict";init_cli_arguments();init_conversation_intake_settlement()}});async function findIntakeForExactTurn(composition,client,invocation2,candidates){if(invocation2.clientThreadId===null||invocation2.clientTurnId===null)return null;const matches=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&(fold.run.intake!=null||fold.run.phase==="conversation"&&fold.run.execution_id===null)&&fold.run.client_thread_id===invocation2.clientThreadId&&fold.run.client_turn_id===invocation2.clientTurnId);if(matches.length>1){throw new UsageError(`Exact client turn already has multiple intake Runs: ${matches.map(fold=>fold.run.run_id).join(", ")}`)}return matches[0]??null}async function findRootRunForExactTurn(composition,client,invocation2,candidates){if(invocation2.clientThreadId===null||invocation2.clientTurnId===null)return null;const matches=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&fold.run.parent_run_id===null&&fold.run.client_thread_id===invocation2.clientThreadId&&fold.run.client_turn_id===invocation2.clientTurnId);if(matches.length>1){const sequence=await composition.executions.readPostPublicationSequence(invocation2.clientTurnId);if(sequence!==null){const byId2=new Map(matches.map(fold=>[fold.run.run_id,fold]));const maintenance=sequence.schema_version===7?byId2.get(sequence.maintenance_run_id):await composition.runs.read(sequence.maintenance_run_id);const steps=sequence.steps;if(maintenance!==void 0&&matches.length===steps.length+(sequence.schema_version===7?1:0)&&maintenance.finished?.status==="completed"&&maintenance.finalization_decision?.outcome==="completed"&&maintenance.run.client_thread_id===invocation2.clientThreadId&&steps.every((step,index)=>{const predecessor=index===0?maintenance:byId2.get(step.predecessor_run_id);const successor=byId2.get(step.successor_run_id);return predecessor!==void 0&&successor!==void 0&&predecessor.finished?.status==="completed"&&predecessor.finalization_decision?.outcome==="completed"&&successor.run.continuation_of_run_id===predecessor.run.run_id&&successor.run.execution_id===step.execution_id&&(index===0&&sequence.schema_version===8?successor.run.same_turn_handoff===void 0&&successor.run.intake?.reason_codes.includes(`post-publication-${step.authorization_sha256.slice(0,16)}`):successor.run.same_turn_handoff?.authorization_sha256===step.authorization_sha256&&successor.run.same_turn_handoff.predecessor_run_id===predecessor.run.run_id)&&successor.run.spec_id===(step.origin.type==="spec"?step.origin.spec_id:null)&&(step.origin.type!=="task"||successor.run.task_id===step.target_task_id)&&(index===0&&sequence.schema_version===8||successor.run.agent_invocation_id===predecessor.run.agent_invocation_id)&&(index!==steps.length-1||successor.status==="running")}))return byId2.get(steps.at(-1)?.successor_run_id??"")??null}if(matches.length===2){const successor=matches.find(fold=>fold.run.same_turn_handoff!==void 0);const predecessor=matches.find(fold=>fold.run.run_id===successor?.run.same_turn_handoff?.predecessor_run_id);const handoff=successor?.run.same_turn_handoff;const postPublication=handoff!==void 0&&"kind"in handoff;const claim=postPublication?await composition.executions.readPostPublicationHandoff(invocation2.clientTurnId):await composition.executions.readSpecHandoff(invocation2.clientTurnId);if(predecessor?.finished?.status==="completed"&&predecessor.finalization_decision?.outcome==="completed"&&successor?.status==="running"&&claim?.predecessor_run_id===predecessor.run.run_id&&claim.successor_run_id===successor.run.run_id&&claim.execution_id===successor.run.execution_id&&(claim.origin.type==="spec"?claim.origin.spec_id===successor.run.spec_id:claim.origin.task_id===successor.run.task_id&&successor.run.spec_id===null)&&claim.authorization_sha256===successor.run.same_turn_handoff?.authorization_sha256&&(postPublication?(claim.schema_version===3||claim.schema_version===5)&&handoff!==void 0&&"target_task_id"in handoff&&claim.target_task_id===handoff.target_task_id&&claim.maintenance_execution_id===predecessor.run.execution_id&&predecessor.run.execution_kind==="delivery"&&predecessor.run.entrypoint==="task":claim.schema_version===2&&predecessor.run.execution_kind==="interaction")&&successor.run.continuation_of_run_id===predecessor.run.run_id&&successor.run.agent_invocation_id===predecessor.run.agent_invocation_id&&successor.run.execution_kind==="delivery"&&successor.run.spec_id===successor.run.same_turn_handoff?.target_spec_id)return successor}throw new UsageError(`Exact client turn already has multiple root Runs: ${matches.map(fold=>fold.run.run_id).join(", ")}`)}return matches[0]??null}function sameClientCorrelation(left,right){const normalizedLeft=left==="codex-desktop"?"codex":left;const normalizedRight=right==="codex-desktop"?"codex":right;return normalizedLeft===normalizedRight}var init_conversation_intake_root_turn=__esm({"src/conversation-intake-root-turn.ts"(){"use strict";init_cli_arguments()}});function conversationObjective(userMessage){const fallback="Capture the current client turn";if(userMessage===null)return fallback;const normalized=userMessage.replace(/\r\n?/g,"\n").trim();const requestHeading=/^##\s+My request for Codex:\s*$/im;const match=requestHeading.exec(normalized);const request=match===null?normalized:normalized.slice(match.index+match[0].length);return request.replace(/<image\b[\s\S]*$/i,"").replace(/\s+/g," ").trim()||fallback}function semanticTerms(value){return new Set(normalizeWorkKey(value).split(" ").map(term=>singularizeSemanticTerm(term)).filter(term=>term.length>=3&&!semanticStopWords.has(term)))}function normalizeWorkKey(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function singularizeSemanticTerm(term){if(term.length>4&&term.endsWith("s")&&!term.endsWith("ss"))return term.slice(0,-1);return term}var semanticStopWords;var init_conversation_semantic_terms=__esm({"src/conversation-semantic-terms.ts"(){"use strict";semanticStopWords=new Set(["a","an","and","as","at","by","com","da","das","de","do","dos","e","em","for","from","in","into","na","nas","no","nos","of","on","or","para","per","por","que","that","the","this","to","um","uma","with"])}});function definitionAuthorizations(parsed){const values=csvOption(parsed.options.definition);const definitions=[...new Set(values.map(value=>value.toLocaleLowerCase()))];if(definitions.some(value=>value!=="prd"&&value!=="spec")){throw new UsageError("--definition must be prd, spec, or prd,spec")}return definitions}function definitionAuthorizationsFromExplicitCreate(userMessage){const request=directUserRequest(userMessage);if(request.length===0)return[];const targets=new Set;for(const definition of["prd","spec"]){const target=`(?:a |an |uma? |the |new )?${definition}`;const negated=new RegExp(`\\b(?:nao|nunca|jamais|sem|do not|don t|never)\\s+(?:quero\\s+)?(?:crie|create|criar)\\s+${target}\\b`);if(negated.test(request))return[];const directImperative=new RegExp(`^(?:por favor,?\\s+)?(?:crie|create)\\s+${target}\\b`);const statedIntent=new RegExp(`^(?:quero|preciso|vamos|pode)\\s+(?:criar|create)\\s+${target}\\b`);const commandForm=new RegExp(`^(?:criar|create)\\s+${target}\\b`);if(directImperative.test(request)||statedIntent.test(request)||commandForm.test(request)){targets.add(definition)}}if(targets.has("prd"))targets.add("spec");return[...targets]}function assertDefinitionConversationIntake(parsed,intent){if(definitionAuthorizations(parsed).length===0)return;if(intent!=="conversation"||parsed.options.intent!=="conversation"){throw new UsageError("--definition requires --intent conversation")}if(parsed.options["classification-source"]!=="explicit"){throw new UsageError("--definition requires --classification-source explicit")}if(parsed.options.title!==void 0||parsed.flags.has("title")){throw new UsageError("--title is invalid for conversation start --definition; supply it to spec or prd create after intake")}if(["task","spec","prd","change","short-name","objective"].some(option=>parsed.options[option]!==void 0)){throw new UsageError("--definition requires a root interaction without Task, Change, or target")}}function conversationRequestOptions(userMessage){const objective=conversationObjective(userMessage);return{objective,risk:inferredConversationRisk(objective)}}function resolveConversationIntent(parsed,userMessage=null){const value=parsed.options.intent;if(value===void 0){if(hasCompleteNewWorkMetadata(parsed))return"new_work";return inferConversationIntent(userMessage)}const normalized=value.toLocaleLowerCase().replaceAll("-","_");if(normalized==="conversation"||normalized==="continue"||normalized==="refine"||normalized==="rework"||normalized==="new_work"||normalized==="git_only"){return normalized}throw new UsageError("--intent must be conversation, continue, refine, rework, new-work, or git-only")}function inferConversationIntent(userMessage){if(definitionAuthorizationsFromExplicitCreate(userMessage).length>0)return"conversation";const normalized=normalizeWorkKey(userMessage??"");if(normalized.length===0)return"conversation";if(/\b(rework|retrabalh\w*)\b/.test(normalized))return"rework";if(/\b(refine|refinar|refinamento|desenvolv\w*|melhor\w*|aprimor\w*)\b/.test(normalized)){return"refine"}if(/\b(continue|continuar|retome|retomar|implement\w*|execut\w*|finaliz\w*|conclu\w*)\b/.test(normalized)){return"continue"}return"conversation"}function intakeDecision(parsed,intent,userMessage=null){const intentWasProvided=parsed.options.intent!==void 0;const explicitMetadata=!intentWasProvided&&hasCompleteNewWorkMetadata(parsed);const source=parsed.options["classification-source"];const declaredDefinitions=definitionAuthorizations(parsed);const recoveredDefinitions=declaredDefinitions.length===0&&intent==="conversation"&&(source===void 0||source==="explicit")&&!["task","spec","prd","change","title","short-name","objective"].some(option=>parsed.options[option]!==void 0)?definitionAuthorizationsFromExplicitCreate(userMessage):[];const definitions=[...declaredDefinitions,...recoveredDefinitions];const classificationSource=source===void 0?recoveredDefinitions.length>0?"explicit":intentWasProvided?"agent":explicitMetadata?"explicit":"fallback":source;if(!new Set(["agent","explicit","fallback"]).has(classificationSource)){throw new UsageError("--classification-source must be agent, explicit, or fallback")}const defaultConfidence=classificationSource==="fallback"?"0":"0.9";const reasonCodes=csvOption(parsed.options["reason-codes"]);if(reasonCodes.some(code=>/^definition-(prd|spec)-authorized$/.test(code))){throw new UsageError("--reason-codes cannot supply definition authorization")}if(reasonCodes.length+definitions.length>12){throw new UsageError("--reason-codes leaves no room for definition authorization")}const derivedReasonCodes=definitions.map(definition=>`definition-${definition}-authorized`);return{intent,classification_source:classificationSource,confidence:confidenceOption(parsed.options.confidence??defaultConfidence),reason_codes:[...reasonCodes.length>0?reasonCodes:[classificationSource==="fallback"?"safe-conversation-fallback":explicitMetadata?"complete-task-metadata":"agent-classified"],...derivedReasonCodes]}}function requireSemanticNewWorkMetadata(parsed){const title=parsed.options.title;const shortName=parsed.options["short-name"];const objective=parsed.options.objective;if(title===void 0||shortName===void 0||objective===void 0){throw new UsageError("new-work intake requires --title, --short-name, and --objective")}const wordCount=title.trim().split(/\s+/).filter(Boolean).length;if(wordCount<4||wordCount>10){throw new UsageError("new-work --title must contain 4 to 10 words")}return{title:title.trim(),shortName:shortName.trim(),objective:objective.trim()}}function describesEquivalentWork(requested,current){const requestedShortName=normalizeWorkKey(requested.shortName);if(requestedShortName.length>0&&requestedShortName===normalizeWorkKey(current.short_name)){return true}const requestedTerms=semanticTerms(`${requested.title} ${requested.objective}`);const currentTerms=semanticTerms(`${current.title} ${current.objective}`);if(requestedTerms.size<5||currentTerms.size<5)return false;let shared=0;for(const term of requestedTerms){if(currentTerms.has(term))shared+=1}return shared>=5&&shared/Math.min(requestedTerms.size,currentTerms.size)>=.7}function assertExactIntakeRequestCompatible(existing,parsed,requestedIntent){const conflicts=[];for(const[option,captured]of[["run",existing.run.run_id],["conversation",existing.run.conversation_id],["provider",existing.run.provider],["work-type",existing.run.work_type],["direct-authorization",existing.run.direct_execution_authorization]]){if(parsed.options[option]!==void 0&&parsed.options[option]!==captured){conflicts.push(`${option}=${captured??"unavailable"}`)}}if(parsed.options.execution!==void 0&&existing.run.execution_id!==parsed.options.execution){conflicts.push(`execution=${existing.run.execution_id??"none"}`)}if(parsed.options.intent!==void 0&&existing.run.intake?.intent!==requestedIntent){conflicts.push(`intent=${existing.run.intake?.intent??"unknown"}`)}const target=explicitIntakeTarget(parsed);if(target!==null&&!matchesTarget(existing,target)){conflicts.push(`target=${existingTarget(existing)} requested=${requestedTarget(target)}`)}if(parsed.options.model!==void 0&&existing.run.model!==parsed.options.model){conflicts.push(`model=${existing.run.model}`)}if(parsed.options["reasoning-effort"]!==void 0&&existing.run.reasoning_effort!==parsed.options["reasoning-effort"]){conflicts.push(`reasoning-effort=${existing.run.reasoning_effort??"unavailable"}`)}if(conflicts.length===0)return;throw new UsageError(`Exact client turn is already captured by Run ${existing.run.run_id} (${conflicts.join(", ")}). Use the matching retry, or start the requested delivery from a new observed client turn.`)}async function latestThreadContext(composition,client,clientThreadId,candidates){if(clientThreadId===null)return{conversationId:null,implicitTarget:null};const runs=(candidates??await composition.runs.list()).filter(fold=>sameClientCorrelation(fold.run.client,client)&&fold.run.entrypoint!=="observation"&&fold.run.parent_run_id===null&&fold.run.client_thread_id===clientThreadId);const targetRun=runs.find(fold=>targetFromRun(fold)!==null);return{conversationId:runs[0]?.run.conversation_id??null,implicitTarget:targetRun===void 0?null:targetFromRun(targetRun)}}function explicitIntakeTarget(parsed){const candidates=[parsed.options.task===void 0?null:{entrypoint:"task",taskId:parsed.options.task},parsed.options.spec===void 0?null:{entrypoint:"spec",specId:parsed.options.spec},parsed.options.prd===void 0?null:{entrypoint:"prd",prdId:parsed.options.prd}];const targets=candidates.filter(target=>target!==null);if(targets.length>1){throw new UsageError("continue/refine/rework intake accepts only one of --task, --spec, or --prd")}return targets[0]??null}function isImplicitConversationCapture(parsed){return["intent","title","short-name","objective","requirements","acceptance","task","spec","prd","change","run"].every(option=>parsed.options[option]===void 0)}function isGitOnlyPublicationRequest(userMessage){if(userMessage===null)return false;const normalized=userMessage.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(normalized.length===0||normalized.split(/\s+/).length>12)return false;if(/\b(corrig|consert|repar|fix|falh|erro|ci|teste|codigo|implement|alter|qual|quando|como|status|atual)\w*\b/.test(normalized)){return false}return/\b(deploy|push|publicar|publique|publica|publish)\b/.test(normalized)}function hasCompleteNewWorkMetadata(parsed){return["title","short-name","objective"].every(option=>parsed.options[option]!==void 0)}function targetFromRun(fold){if(fold.run.entrypoint==="task"&&fold.run.task_id!==null){return{entrypoint:"task",taskId:fold.run.task_id}}if(fold.run.entrypoint==="spec"&&fold.run.spec_id!==null){return{entrypoint:"spec",specId:fold.run.spec_id}}if(fold.run.entrypoint==="prd"&&fold.run.prd_id!==null){return{entrypoint:"prd",prdId:fold.run.prd_id}}if(fold.run.task_id!==null)return{entrypoint:"task",taskId:fold.run.task_id};if(fold.run.spec_id!==null)return{entrypoint:"spec",specId:fold.run.spec_id};if(fold.run.prd_id!==null)return{entrypoint:"prd",prdId:fold.run.prd_id};return null}function matchesTarget(fold,target){return fold.run.entrypoint===target.entrypoint&&(target.taskId===void 0||fold.run.task_id===target.taskId)&&(target.specId===void 0||fold.run.spec_id===target.specId)&&(target.prdId===void 0||fold.run.prd_id===target.prdId)}function existingTarget(fold){return fold.run.task_id??fold.run.spec_id??fold.run.prd_id??"none"}function requestedTarget(target){return target.taskId??target.specId??target.prdId??"none"}function directUserRequest(userMessage){if(userMessage===null)return"";const normalized=userMessage.replace(/\r\n?/g,"\n").trim();const requestHeading=/^#{1,6}\s+My request(?:\s+for Codex)?:\s*$/im;const match=requestHeading.exec(normalized);const request=(match===null?normalized:normalized.slice(match.index+match[0].length)).trim();if(/^(?:[>"'`“”‘’]|~~~|<)/.test(request))return"";const attachmentBoundary=request.search(/\n(?:#{1,6}\s*(?:attachment|document|file|arquivo|anexo)\b|<image\b|```|---\s*$)/im);const directRequest=attachmentBoundary===-1?request:request.slice(0,attachmentBoundary);return normalizeWorkKey(directRequest)}function inferredConversationRisk(objective){const normalized=objective.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase();const isSmallFrontendAdjustment=normalized.length<=280&&/\b(ajust|corrig|alter|troqu|mud)\w*\b/.test(normalized)&&/\b(front(?:end)?|interface|ui|visual|css|layout|tela|botao|modal|popup|coluna|aba|card)\w*\b/.test(normalized);const hasElevatedScope=/\b(api|backend|banco|database|schema|migr|auth|segur|deploy|infra|lifecycle|task-first|cli)\w*\b/.test(normalized);return isSmallFrontendAdjustment&&!hasElevatedScope?"lite":"standard"}var init_conversation_intake=__esm({"src/conversation-intake.ts"(){"use strict";init_cli_arguments();init_conversation_intake_root_turn();init_conversation_semantic_terms();init_conversation_intake_root_turn()}});async function resolveConversationContinuation(parsed,composition,filesystem){if(parsed.options.intent!==void 0&&parsed.options.intent!=="continue"){throw new UsageError("conversation resolve supports --intent continue only")}if(parsed.options.definition!==void 0){throw new UsageError("conversation resolve does not authorize definition creation")}const client=parsed.options.client??"codex";const invocation2=await resolveRunClientInvocation(filesystem,client);const context2=await latestThreadContext(composition,client,invocation2.clientThreadId);const target=explicitIntakeTarget(parsed)??context2.implicitTarget;const existing=await findRootRunForExactTurn(composition,client,invocation2);const base={read_only:true,intent:"continue",target,current_run_id:existing?.run.run_id??null,current_execution_id:existing?.run.execution_id??null,start_args:null};if(target===null){return{...base,status:"unresolved",reason:"No root delivery focus in this client thread"}}const id=target.taskId??target.specId??target.prdId;if(id===void 0)throw new UsageError("Continuation target has no canonical ID");const options={...parsed.options,intent:"continue",client,[target.entrypoint]:id};const startArgs=["conversation","start",...Object.entries(options).flatMap(([key,value])=>[`--${key}`,value]),...Array.from(parsed.flags,flag=>`--${flag}`)];if(existing!==null){try{assertExactIntakeRequestCompatible(existing,{...parsed,options},"continue")}catch(error51){if(!(error51 instanceof UsageError))throw error51;return{...base,status:"conflict",reason:error51.message}}if(existing.finished!==null){return{...base,status:"closed",reason:"The matching Run is already terminal; do not dispatch new children"}}}if(target.taskId!==void 0){const task=(await composition.tasks.read(target.taskId)).task;if(["completed","cancelled","failed"].includes(task.status)){return{...base,status:"blocked",task_status:task.status,reason:"This Task cannot continue; completed/cancelled are immutable and failed requires explicit rework"}}return{...base,status:"resolved",task_status:task.status,execution_id:task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null,reused:existing!==null,start_args:startArgs}}const execution=await resolveCanonicalMacroExecution(target,composition,parsed.options.execution);return{...base,status:"resolved",execution_id:execution.id,execution_status:execution.status,task_ids:execution.dag.nodes.map(node=>node.task_id),reused:existing!==null,start_args:startArgs}}var init_conversation_resolution=__esm({"src/conversation-resolution.ts"(){"use strict";init_cli_arguments();init_conversation_intake();init_run_client_invocation();init_run_conversation_v2()}});function activeCaptureRunIds(area,parsed,result2){return area==="run"&&parsed.positionals[1]==="usage"&&(parsed.flags.has("active")||parsed.flags.has("recent"))?changedActiveCaptureRunIds(result2):null}function changedActiveCaptureRunIds(result2){const telemetry=result2?.telemetry;if(typeof telemetry!=="object"||telemetry===null||!("mode"in telemetry)||!["active_exact_session","recent_exact_session"].includes(String(telemetry.mode))||!("captured"in telemetry)||!Array.isArray(telemetry.captured))throw new UsageError("Active telemetry capture returned an invalid projection result");const ids2=[];for(const item of telemetry.captured){if(typeof item!=="object"||item===null||typeof item.run_id!=="string"||typeof item.captured!=="boolean"){throw new UsageError("Active telemetry capture returned an invalid Run result")}if(item.captured)ids2.push(item.run_id)}return ids2}var init_lifecycle_manifest_active_capture=__esm({"src/lifecycle-manifest-active-capture.ts"(){"use strict";init_cli_arguments()}});function effectiveRunFinishedAt(fold){const recordedFinish=fold.finished?.occurred_at??null;if(recordedFinish===null)return null;const startedAtMs=Date.parse(fold.run.occurred_at);const recordedFinishMs=Date.parse(recordedFinish);const reconciledFinishMs=fold.records.filter(record3=>"activity_kind"in record3&&record3.activity_kind==="retrospective_local_reconciliation").map(record3=>"source_occurred_at"in record3?record3.source_occurred_at??null:null).map(value=>value===null?Number.NaN:Date.parse(value)).filter(value=>Number.isFinite(value)&&value>=startedAtMs&&value<=recordedFinishMs);if(reconciledFinishMs.length===0)return recordedFinish;return new Date(Math.max(...reconciledFinishMs)).toISOString()}function projectedSourceTiming(runStartedAt,effectiveRecords,allRecords){const startedAtMs=Date.parse(runStartedAt);const timestampOf=value=>{const timestamp13=value===null||value===void 0?Number.NaN:Date.parse(value);return Number.isFinite(timestamp13)?timestamp13:null};const candidates=[];for(const record4 of[...effectiveRecords,...allRecords]){const sourceStartedAt2=record4.source_started_at;const sourceFinishedAt2=record4.source_finished_at;const startMs=timestampOf(sourceStartedAt2);const finishMs=timestampOf(sourceFinishedAt2);if(startMs!==null&&finishMs!==null&&finishMs>=startMs&&finishMs>=startedAtMs){candidates.push(record4);continue}const sourceOccurredAt=timestampOf(record4.source_occurred_at);if(record4.activity_kind==="retrospective_local_reconciliation"&&sourceOccurredAt!==null&&sourceOccurredAt>=startedAtMs)candidates.push({...record4,source_started_at:runStartedAt,source_finished_at:record4.source_occurred_at??void 0})}candidates.sort((left,right)=>Date.parse(left.occurred_at)-Date.parse(right.occurred_at));const record3=candidates.at(-1);const sourceStartedAt=record3?.source_started_at??null;const sourceFinishedAt=record3?.source_finished_at??record3?.source_occurred_at??null;return{source_started_at:sourceStartedAt,source_finished_at:sourceFinishedAt,source_duration_ms:timestampDelta(sourceStartedAt,sourceFinishedAt),capture_lag_ms:timestampDelta(sourceFinishedAt,record3?.occurred_at??null)}}function timestampDelta(start,finish){if(start===null||finish===null)return null;const startMs=Date.parse(start);const finishMs=Date.parse(finish);return Number.isFinite(startMs)&&Number.isFinite(finishMs)?Math.max(0,finishMs-startMs):null}var init_lifecycle_manifest_run_projection=__esm({"src/lifecycle-manifest-run-projection.ts"(){"use strict"}});function canonicalAgentName(agent){return agent.startsWith("agent-")?`zaip-agent-${agent.slice("agent-".length)}`:agent}function effectiveConfiguration(fold){const models=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.model),...fold.model_call_records.map(record3=>record3.model),...fold.effective_usage_records.map(record3=>record3.model)].filter(value=>value!==null));const efforts=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.reasoning_effort),...fold.effective_usage_records.map(record3=>record3.runtime?.reasoning_effort??null),...fold.model_call_records.map(record3=>record3.runtime?.reasoning_effort??null)].filter(value=>value!==null));return{effective_model:models.size===1?[...models][0]??null:null,effective_reasoning_effort:efforts.size===1?[...efforts][0]??null:null,effective_config_mixed:models.size>1||efforts.size>1}}function callSummary(fold){const ids2=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);const base={cli_call_count:ids2.size===0?null:ids2.size,call_count:null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null};if(fold.model_call_records.length>0)return{...base,call_count:fold.model_call_records.length};if(ids2.size===0)return base;return{...base,call_count:ids2.size,terminal_call_count:fold.provider_invocation_records.length,failed_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="failed").length,cancelled_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="cancelled").length}}var init_lifecycle_manifest_run_summary=__esm({"src/lifecycle-manifest-run-summary.ts"(){"use strict"}});function modelCallCoverage(fold){if(fold.model_call_records.length===0)return"unavailable";return fold.model_call_records.every(record3=>record3.coverage==="complete")?"complete":"partial"}function runCostInput(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}var init_lifecycle_manifest_run_usage=__esm({"src/lifecycle-manifest-run-usage.ts"(){"use strict"}});function summarizeRunObservedTiming(fold){return summarizeObservedSourceTiming(fold.effective_usage_records.map(record3=>({phase:record3.phase,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null})))}var init_observed_run_timing=__esm({"src/observed-run-timing.ts"(){"use strict";init_src4()}});async function runLifecycleManifestMaintenance(action,parsed,filesystem,composition){const store=new LifecycleManifestStore(filesystem);if(["neighbors","path","explain","gaps"].includes(action??"")){return runManifestGraphQuery(action,parsed,store)}if(action==="rebuild"){if(!parsed.flags.has("confirm-full-scan")){throw new UsageError("manifest rebuild requires --confirm-full-scan")}const events=await lifecycleManifestBootstrapEvents(composition,filesystem);return{snapshot:await store.replace(events),indexed:events.length}}if(action==="refresh")return store.refresh();if(action==="reconcile"){const id=parsed.options.id??parsed.positionals[2];if(id===void 0)throw new UsageError("manifest reconcile requires --id ID");const event=await lifecycleManifestEventForId(id,composition,filesystem);return{snapshot:await store.appendMany([event]),reconciled:[id]}}if(action==="show"){return parsed.flags.has("active")?store.readActiveWork():store.readSummary()}throw new UsageError("manifest requires rebuild, refresh, reconcile, show, neighbors, path, explain, or gaps")}async function runManifestGraphQuery(action,parsed,store){const entities=await store.readEntities();const byId2=new Map(entities.map(entity=>[entity.id,entity]));const id=parsed.options.id??parsed.positionals[2];if(action==="path"){const from=parsed.options.from??id;const to2=parsed.options.to??parsed.positionals[3];if(from===void 0||to2===void 0)throw new UsageError("manifest path requires --from ID --to ID");const queue=[[from]];const visited=new Set([from]);while(queue.length>0&&visited.size<=GRAPH_VISIT_LIMIT){const route=queue.shift();const current=route.at(-1);if(current===to2)return{path:route,bounded:true,limit:GRAPH_VISIT_LIMIT};for(const neighbor of graphNeighbors(entities,current)){if(!visited.has(neighbor.entity.id)){visited.add(neighbor.entity.id);queue.push([...route,neighbor.entity.id])}}}return{path:null,bounded:true,limit:GRAPH_VISIT_LIMIT}}if(id===void 0||!byId2.has(id))throw new UsageError("manifest graph query requires an existing --id ID");if(action==="neighbors"){const neighbors=graphNeighbors(entities,id);return{id,neighbors:neighbors.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:neighbors.length>GRAPH_RESULT_LIMIT}}if(action==="gaps"){const entity=byId2.get(id);if(entity===void 0)throw new UsageError("manifest graph query requires an existing --id ID");const gaps=relationEdgesFor(entity).filter(edge2=>!byId2.has(edge2.target_id));return{id,gaps:gaps.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:gaps.length>GRAPH_RESULT_LIMIT}}const to=parsed.options.to??parsed.positionals[3];if(to===void 0)throw new UsageError("manifest explain requires --id ID --to ID");const edge=graphNeighbors(entities,id).find(neighbor=>neighbor.entity.id===to)?.edge;return{id,to,relation:edge??null,bounded:true,limit:GRAPH_RESULT_LIMIT}}async function manifestList(area,parsed,filesystem){if(!["prd","spec","change","task","execution","run","decision"].includes(area)){throw new UsageError(`Lifecycle manifest does not support list area: ${area}`)}const store=new LifecycleManifestStore(filesystem);let entities=await store.readEntities(area);if(entities.length===0&&await store.readSummary()===null&&!await filesystem.exists(".agents/records/lifecycle/.gitkeep")){throw new UsageError("Lifecycle manifest is not initialized; run `zaip manifest rebuild --confirm-full-scan` once")}const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);entities=entities.filter(entity=>statuses.size===0||entity.status!==null&&statuses.has(entity.status)).filter(entity=>parsed.options.prd===void 0||entity.relations.includes(parsed.options.prd)).filter(entity=>parsed.options.spec===void 0||entity.relations.includes(parsed.options.spec)).filter(entity=>parsed.options.change===void 0||entity.relations.includes(parsed.options.change)).filter(entity=>parsed.options.task===void 0||entity.relations.includes(parsed.options.task)).filter(entity=>parsed.options.execution===void 0||entity.relations.includes(parsed.options.execution)).filter(entity=>from===null||Date.parse(entity.updated_at)>=from).filter(entity=>to===null||Date.parse(entity.updated_at)<=to).sort((left,right)=>right.updated_at.localeCompare(left.updated_at)||right.id.localeCompare(left.id));const after=parsed.options.after;const start=after===void 0?0:entities.findIndex(entity=>entity.id===after)+1;if(after!==void 0&&start===0)throw new UsageError(`--after id not found: ${after}`);const limit=parsed.flags.has("all")?entities.length:numberOption(parsed.options.limit,20);if(limit>200&&!parsed.flags.has("all")){throw new UsageError("--limit must be at most 200; use --all explicitly")}const view=parsed.options.view??"index";if(view!=="index"&&view!=="summary"&&view!=="full")throw new UsageError("--view must be index, summary, or full");const page=entities.slice(start,start+limit);if(view==="full")return page;if(view==="summary"){return page.map(({data:_data,...entity})=>entity)}return{schema:["id","title","status","risk","priority","updated_at","work_relations"],rows:page.map(entity=>[entity.id,entity.title,entity.status,entity.risk,entity.priority,entity.updated_at,entity.relations.filter(relation=>/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-/.test(relation)).slice(0,2)]),next_after:page.length===limit?page.at(-1)?.id??null:null}}function isLifecycleManifestMutation(action){if(action===void 0||action==="ready-next")return false;return!["list","show","next","validate","aggregate","inspect-local","preflight"].includes(action)}async function syncLifecycleManifestResult(result2,area,parsed,composition,filesystem){const store=new LifecycleManifestStore(filesystem);if(area==="decision"){const decision=findDecision(result2);if(decision!==void 0)await store.append(lifecycleManifestEventFromDecision(decision));return}if(area==="run"||area==="subagent"){const capturedIds=activeCaptureRunIds(area,parsed,result2);const candidate=area==="run"&&capturedIds===null?findRunId(result2)??parsed.options.id??parsed.positionals[2]:void 0;const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);const runIds=new Set(capturedIds??collectRunIds(result2));if(candidate!==void 0)runIds.add(candidate);for(const runId of runIds){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="conversation"){const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="validation"||area==="evidence"){const artifact=findArtifact(result2,area);if(artifact!==void 0)await store.append(lifecycleManifestEventFromEntity(artifact));return}const events=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events.length>0)await store.appendMany(events)}async function syncObservedRunManifest(runId,composition,filesystem){const run=await composition.runs.read(runId);if(run.run.entrypoint!=="observation")return;await new LifecycleManifestStore(filesystem).append(lifecycleManifestEventFromRun(run))}function findArtifact(result2,area){if(typeof result2!=="object"||result2===null)return void 0;const artifact=result2[area];if(typeof artifact!=="object"||artifact===null)return void 0;const record3=artifact;const observedAt=area==="validation"?record3.executed_at:record3.observed_at;if(typeof record3.id!=="string"||typeof observedAt!=="string"||typeof record3.status!=="string"){return void 0}return{...record3,updated_at:observedAt}}async function lifecycleManifestEventForId(id,composition,filesystem){if(id.startsWith("PRD-"))return lifecycleManifestEventFromEntity((await composition.prds.read(id)).prd);if(id.startsWith("SPEC-"))return lifecycleManifestEventFromEntity((await composition.specs.read(id)).spec);if(id.startsWith("CHG-"))return lifecycleManifestEventFromEntity((await composition.changes.read(id)).change);if(id.startsWith("TASK-"))return lifecycleManifestEventFromEntity((await composition.tasks.read(id)).task);if(id.startsWith("EXEC-"))return lifecycleManifestEventFromEntity((await composition.executions.read(id)).execution);if(id.startsWith("RUN-"))return lifecycleManifestEventFromRun(await composition.runs.read(id));if(/^(?:TEST|EVAL|CHECK|REVIEW|MUT|INT|E2E)-/.test(id)||id.startsWith("EVD-")){const artifact=(await lifecycleAssuranceBootstrapEvents(filesystem)).find(event=>event.entity.id===id);if(artifact!==void 0)return artifact;throw new UsageError(`Typed assurance artifact not found: ${id}`)}throw new UsageError(`Unsupported lifecycle manifest reconciliation id: ${id}`)}function collectLifecycleEntities(value){const found=[];const seen=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.id==="string"&&typeof record3.status==="string"&&typeof record3.updated_at==="string"&&/^(PRD|SPEC|CHG|TASK|EXEC)-/.test(record3.id)&&!seen.has(record3.id)){seen.add(record3.id);found.push(record3)}Object.values(record3).forEach(visit)};visit(value);return found}function lifecycleManifestEventFromEntity(entity){const id=entity.id;const kind=id.startsWith("PRD-")?"prd":id.startsWith("SPEC-")?"spec":id.startsWith("CHG-")?"change":id.startsWith("TASK-")?"task":id.startsWith("EVD-")?"evidence":id.startsWith("TEST-")||id.startsWith("EVAL-")||id.startsWith("CHECK-")||id.startsWith("REVIEW-")||id.startsWith("MUT-")||id.startsWith("INT-")||id.startsWith("E2E-")?"validation":"execution";const relations=new Set;collectRelationIds(entity,relations,id);for(const[key,value]of Object.entries(entity)){if(key.endsWith("_id")&&typeof value==="string")relations.add(value);if(key.endsWith("_ids")&&Array.isArray(value))value.filter(item=>typeof item==="string").forEach(item=>{relations.add(item)})}return{schema_version:1,event_id:`${id}:${String(entity.updated_at)}:${String(entity.status)}`,occurred_at:entity.updated_at,operation:"upsert",entity:{kind,id,title:typeof entity.title==="string"?entity.title:null,status:entity.status,risk:typeof entity.risk==="string"?entity.risk:null,priority:typeof entity.priority==="string"?entity.priority:null,updated_at:entity.updated_at,relations:[...relations],relation_edges:relationEdgesFromEntity(entity,[...relations]),usage:null,data:Object.fromEntries(Object.entries(entity).filter(([key])=>key!=="prepared_plan"))}}}function collectRelationIds(value,relations,ownId){if(typeof value==="string"){if(/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN|REQ|AC)-/.test(value)&&value!==ownId){relations.add(value)}return}if(Array.isArray(value)){value.forEach(item=>{collectRelationIds(item,relations,ownId)});return}if(typeof value==="object"&&value!==null){Object.values(value).forEach(item=>{collectRelationIds(item,relations,ownId)})}}function lifecycleManifestEventFromRun(fold){const costInput=runCostInput(fold);const aggregate=aggregateRunV2Usage([costInput],fold.run.run_id);const usage=aggregate.total;const runtime=fold.effective_usage_records.findLast(record3=>record3.runtime)?.runtime;const observedRuntime=fold.effective_usage_records.at(-1);const sourceTiming=projectedSourceTiming(fold.run.occurred_at,fold.effective_usage_records,fold.records);return{schema_version:1,event_id:`${fold.run.run_id}:${fold.records.length}:${fold.status}`,occurred_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,operation:"upsert",entity:{kind:"run",id:fold.run.run_id,title:null,status:fold.status,risk:null,priority:null,updated_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,relations:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null),relation_edges:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null).map(target_id=>({target_id,type:target_id===fold.run.parent_run_id?"parent":"references",direction:"outbound",provenance:"explicit",source_locator:`run:${fold.run.run_id}`})),usage:{input_tokens:usage.tokens.input,output_tokens:usage.tokens.output,cached_input_tokens:usage.tokens.cached_input,total_tokens:usage.tokens.total,cost:usage.cost.brl??usage.cost.usd,currency:usage.cost.brl!==null?"BRL":usage.cost.usd!==null?"USD":null},data:{attribution_status:fold.run.attribution_status,phase:fold.records.findLast(record3=>"phase"in record3)?.phase??fold.run.phase,run_role:effectiveRunV2Role(fold.run),run_kind:effectiveRunV2Kind(fold.run),run_purpose:effectiveRunV2Purpose(fold.run),requires_finalizer:runV2RequiresFinalizer(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,client:fold.run.client,agent:fold.run.agent,agent_name:fold.run.agent==="codex"?"codex":fold.run.agent_name??canonicalAgentName(fold.run.agent),provider:observedRuntime?.provider??fold.run.provider,model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,...effectiveConfiguration(fold),...callSummary(fold),cli_agent_name:fold.run.agent_name??null,call_coverage:modelCallCoverage(fold),service_tier:runtime?.service_tier??null,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,zaip_execution_id:fold.run.execution_id,agent_invocation_id:fold.run.agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,root_agent_invocation_id:fold.run.root_agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,parent_agent_invocation_id:fold.run.parent_agent_invocation_id??null,agent_invocation_kind:fold.run.invocation_kind??(fold.run.parent_run_id===null?"orchestrator":"delegated"),delegation_depth:fold.run.delegation_depth??(fold.run.parent_run_id===null?0:null),conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,intake:fold.run.intake??null,started_at:fold.run.occurred_at,terminal_finished_at:fold.finished?.occurred_at??null,finished_at:effectiveRunFinishedAt(fold),...sourceTiming,observed_source_timing:summarizeRunObservedTiming(fold),pricing_segments:fold.effective_usage_records.map(record3=>({event_id:record3.event_id,attributed_spec_id:record3.attributed_spec_id??null,phase:record3.phase,provider:record3.provider,model:record3.model,service_tier:record3.runtime?.service_tier??runtime?.service_tier??null,input_tokens:record3.tokens.input,cached_input_tokens:record3.tokens.cached_input,output_tokens:record3.tokens.output,reasoning_tokens:record3.tokens.reasoning,total_tokens:record3.tokens.total,recorded_usd:record3.cost.usd,recorded_brl:record3.cost.brl,recorded_fx_rate:record3.cost.fx_rate??null,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null,duration_ms:record3.source_started_at&&record3.source_finished_at?Math.max(0,Date.parse(record3.source_finished_at)-Date.parse(record3.source_started_at)):null})),entrypoint_usage:{conversation:aggregate.conversation,planning:aggregate.planning,execution:aggregate.execution,total:usage}}}}}function lifecycleManifestEventFromDecision(decision){return{schema_version:1,event_id:`${decision.id}:${decision.created_at}`,occurred_at:decision.created_at,operation:"upsert",entity:{kind:"decision",id:decision.id,title:decision.title,status:null,risk:null,priority:null,updated_at:decision.created_at,relations:[decision.scope_id],relation_edges:[{target_id:decision.scope_id,type:"references",direction:"outbound",provenance:"explicit",source_locator:`decision:${decision.id}`}],usage:null,data:{origin:decision.origin,scope_type:decision.scope_type,scope_id:decision.scope_id,category:decision.category,created_at:decision.created_at}}}}function relationEdgesFromEntity(entity,relations){return relations.map(target_id=>{const explicit=Object.entries(entity).some(([key,value])=>key.endsWith("_id")&&value===target_id||key.endsWith("_ids")&&Array.isArray(value)&&value.includes(target_id));return{target_id,type:target_id.startsWith("REQ-")||target_id.startsWith("AC-")?"requirement":"references",direction:"outbound",provenance:explicit?"explicit":"derived",source_locator:`record:${String(entity.id)}`}})}function findRunId(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.run_id==="string")return record3.run_id;for(const child of Object.values(record3)){const result2=findRunId(child);if(result2!==void 0)return result2}return void 0}function collectRunIds(value){const found=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.run_id==="string"&&record3.run_id.startsWith("RUN-")){found.add(record3.run_id)}Object.values(record3).forEach(visit)};visit(value);return[...found]}function findDecision(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.id==="string"&&record3.id.startsWith("DEC-")&&typeof record3.created_at==="string"){return record3}for(const child of Object.values(record3)){const result2=findDecision(child);if(result2!==void 0)return result2}return void 0}async function lifecycleManifestBootstrapEvents(composition,filesystem){const[prds,specs,changes,tasks,executions,runs,decisions,assurance]=await Promise.all([composition.prds.list(),composition.specs.list(),composition.changes.list(),composition.tasks.list(),composition.executions.list(),composition.runs.list(),composition.decisions.list(),lifecycleAssuranceBootstrapEvents(filesystem)]);return[...[...prds,...specs,...changes,...tasks,...executions].map(entity=>lifecycleManifestEventFromEntity(entity)),...runs.map(lifecycleManifestEventFromRun),...decisions.map(lifecycleManifestEventFromDecision),...assurance]}async function lifecycleAssuranceBootstrapEvents(filesystem){const paths2=await filesystem.listFiles(".agents/records/changes",".md");const events=[];for(const path of paths2){const isEvidence=path.includes("/artifacts/evidence/");const isValidation=/\/artifacts\/(?:tests|evals|checks)\//.test(path);if(!isEvidence&&!isValidation)continue;try{const content=await filesystem.readText(path);const artifact=isEvidence?parseMarkdown(content,evidenceArtifactV2Schema).metadata:parseMarkdown(content,validationArtifactV2Schema).metadata;const timestamp13="observed_at"in artifact?artifact.observed_at:artifact.executed_at;events.push(lifecycleManifestEventFromEntity({...artifact,updated_at:timestamp13}))}catch{}}return events}var GRAPH_RESULT_LIMIT,GRAPH_VISIT_LIMIT;var init_lifecycle_manifest_commands=__esm({"src/lifecycle-manifest-commands.ts"(){"use strict";init_src();init_src4();init_src5();init_src8();init_src8();init_src6();init_cli_arguments();init_lifecycle_manifest_active_capture();init_lifecycle_manifest_run_projection();init_lifecycle_manifest_run_summary();init_lifecycle_manifest_run_usage();init_observed_run_timing();GRAPH_RESULT_LIMIT=50;GRAPH_VISIT_LIMIT=200}});import{execFile as execFile15}from"node:child_process";import{createHash as createHash49}from"node:crypto";import{lstat as lstat10,open as open5,realpath as realpath10}from"node:fs/promises";import{isAbsolute as isAbsolute8,resolve as resolve14,toNamespacedPath}from"node:path";import{promisify as promisify15}from"node:util";function stopReceiptPath(session,turn){return`.local/hooks/stop-${hash3(JSON.stringify([session,turn]))}.json`}async function replayStopReceipt(filesystem,session,turn,options={}){const path=stopReceiptPath(session,turn);const source=JSON.parse(await filesystem.readText(path));if(source.schema_version!==1||source.session_id!==session||source.turn_id!==turn||source.event?.session_id!==session||source.event?.turn_id!==turn)throw new Error("Stop replay identity mismatch");const hook=filesystem.resolve(".codex/hooks/zaip-conversation-lifecycle.mjs");const child=promisify15(execFile15)(process.execPath,[hook,options.automatic?"--recover-previous-turn":"--replay-receipt"],{cwd:filesystem.root,windowsHide:true,timeout:options.automatic?9e3:5e4,maxBuffer:262144});child.child.stdin?.end(JSON.stringify({...source.event,stop_hook_active:true}));await child;const result2=JSON.parse(await filesystem.readText(path));return{session_id:session,turn_id:turn,state:result2.state,error:result2.error??null,telemetry:result2.telemetry??null}}async function assertTrustedStopReceipt(filesystem,session,turn){const receipt=stopReceiptSchema.parse(JSON.parse(await filesystem.readText(stopReceiptPath(session,turn))));if(receipt.session_id!==session||receipt.turn_id!==turn)throw new Error("Stop receipt session/turn mismatch");const age=Date.now()-Date.parse(receipt.observed_at);if(age<-5e3||age>7*864e5)throw new Error("Stop receipt requires a fresh transcript observation");const cursor=receipt.cursor;if(!isAbsolute8(cursor.path))throw new Error("Stop transcript path must be absolute");if(/^(?:\\\\|\/\/)/.test(cursor.path)&&!/^\\\\\?\\[a-z]:\\/i.test(cursor.path))throw new Error("Stop transcript cannot use network or device paths");const identity2=path=>process.platform==="win32"?toNamespacedPath(resolve14(path)).toLowerCase():resolve14(path);const info=await lstat10(cursor.path);if(!info.isFile()||info.isSymbolicLink()||identity2(await realpath10(cursor.path))!==identity2(cursor.path))throw new Error("Stop transcript cannot follow links");const handle=await open5(cursor.path,"r");try{const stat5=await handle.stat();if(stat5.dev!==cursor.dev||stat5.ino!==cursor.ino||stat5.birthtimeMs!==cursor.birthtime_ms||stat5.size<cursor.size||cursor.offset>cursor.size||stat5.size===cursor.size&&(stat5.mtimeMs!==cursor.mtime_ms||stat5.ctimeMs!==cursor.ctime_ms))throw new Error("Stop transcript replaced or truncated after observation");const readProof=async proof=>{if(proof.offset+proof.length>cursor.offset)throw new Error("Stop proof exceeds observed transcript");const buffer=Buffer.alloc(proof.length);const read=await handle.read(buffer,0,buffer.length,proof.offset);if(read.bytesRead!==buffer.length||hash3(buffer)!==proof.sha256)throw new Error("Stop transcript proof mismatch");return buffer};const header=await readProof(cursor.session_proof);const terminal=await readProof(cursor.terminal_proof);await readProof(cursor.anchor);if(cursor.session_proof.offset!==0||header.at(-1)!==10||terminal.at(-1)!==10||cursor.terminal_proof.offset<cursor.session_proof.length)throw new Error("Stop proof must identify complete ordered JSONL records");const first=JSON.parse(header.toString("utf8"));const sessionId=first.type==="session_meta"?first.payload?.id??first.payload?.session_id:first.payload?.type==="session_meta"?first.payload.id??first.payload.session_id:null;const last=JSON.parse(terminal.toString("utf8")).payload;if(sessionId!==session||last?.type!=="task_complete"||last.turn_id!==turn)throw new Error("Stop terminal evidence belongs to another session or turn");const status=last.status==="cancelled"?"cancelled":last.status==="failed"||last.error!=null?"failed":"completed";if(status!==cursor.terminal_status)throw new Error("Stop outcome differs from observed terminal event");const after=await handle.stat();if(stat5.size!==after.size||stat5.mtimeMs!==after.mtimeMs||stat5.ctimeMs!==after.ctimeMs)throw new Error("Stop transcript changed during proof verification");return{run_id:receipt.run_id,status}}finally{await handle.close()}}async function reconcileVerifiedStop(parsed,filesystem,composition,lifecycle,reconcile){requireOptions(parsed.options,["session","turn"]);const session=String(parsed.options.session).trim();const turn=String(parsed.options.turn).trim();const proof=await assertTrustedStopReceipt(filesystem,session,turn);const key=createHash49("sha256").update(JSON.stringify(["codex",session,turn,null,null])).digest("hex");const correlation=JSON.parse(await filesystem.readText(`.local/codex-telemetry-spool/v1/correlations/${key}.json`));if(correlation.schema_version!==1||correlation.agent_path!==null||correlation.thread_id!==session||correlation.turn_id!==turn||correlation.run_id!==proof.run_id)throw new UsageError("Stop correlation does not match exact terminal evidence");const root=await composition.runs.read(proof.run_id);if(root.run.parent_run_id!==null||root.run.client_thread_id!==session||root.run.client_turn_id!==turn||root.run.agent!=="agent-orchestrator"||root.run.run_role!=="orchestrator")throw new UsageError("reconcile-stop requires the exact canonical orchestrator root");if(root.run.task_id===null){return runConversationV2Command("finish",{...parsed,options:{...parsed.options,run:root.run.run_id,status:proof.status,summary:root.finalization_decision?.summary??"Codex host turn completed"}},composition,filesystem,lifecycle)}return reconcile(root,composition,lifecycle,proof.status)}var hash3;var init_stop_receipt=__esm({"src/stop-receipt.ts"(){"use strict";init_src();init_cli_arguments();init_run_conversation_v2();hash3=value=>createHash49("sha256").update(value).digest("hex")}});import{createHash as createHash50}from"node:crypto";import{lstat as lstat11,open as open6,realpath as realpath11}from"node:fs/promises";import{isAbsolute as isAbsolute9,resolve as resolve15,toNamespacedPath as toNamespacedPath2}from"node:path";async function verifyStopPersistence(filesystem,composition,session,turn,runId){const proof=await assertTrustedStopReceipt(filesystem,session,turn).catch(()=>{throw new Error("previous_stop_proof_invalid")});const fold=await composition.runs.read(runId);if(proof.run_id!==runId||fold.finished===null||fold.finished.status!==proof.status||fold.run.client_thread_id!==session||fold.run.client_turn_id!==turn||fold.run.parent_run_id!==null||fold.run.run_role!=="orchestrator"||fold.run.agent!=="agent-orchestrator")throw new Error("previous_stop_canonical_not_terminal");if(fold.run.task_id!==null){const task=(await composition.tasks.read(fold.run.task_id)).task;if(!["completed","blocked","failed","cancelled"].includes(task.status))throw new Error("previous_stop_task_not_terminal")}}async function regular(path,limit){if(!isAbsolute9(path)||/^(?:\\\\|\/\/)/.test(path)&&!/^\\\\\?\\[a-z]:\\/i.test(path))throw new Error("previous_stop_unsafe_path");const stat5=await lstat11(path);if(!stat5.isFile()||stat5.isSymbolicLink()||identity(await realpath11(path))!==identity(path)||limit!==void 0&&stat5.size>limit)throw new Error("previous_stop_unsafe_file");return stat5}async function precedingTurn(path,session,current){await regular(path);const handle=await open6(path,"r");try{const stat5=await handle.stat();const read=async(offset,length)=>{const buffer=Buffer.alloc(length);const{bytesRead}=await handle.read(buffer,0,length,offset);if(bytesRead!==length)throw new Error("previous_stop_transcript_changed");return buffer};const header=await read(0,Math.min(stat5.size,1024*1024));const end=header.indexOf(10);if(end<0)throw new Error("previous_stop_header_unavailable");const first=JSON.parse(header.subarray(0,end).toString("utf8"));if(first.type!=="session_meta"||(first.payload?.id??first.payload?.session_id)!==session)throw new Error("previous_stop_session_mismatch");const start=Math.max(0,stat5.size-16*1024*1024);const tail=await read(start,stat5.size-start);const aligned=start===0?tail:tail.subarray(tail.indexOf(10)+1);if(start>0&&tail.indexOf(10)<0)throw new Error("previous_stop_tail_unavailable");const lines2=aligned.toString("utf8").split("\n");lines2.pop();const turns=[];let terminal=false;for(const line of lines2){if(!line.trim())continue;if(Buffer.byteLength(line)>8*1024*1024)throw new Error("previous_stop_line_too_large");const row=JSON.parse(line),payload=row.payload;if((row.type==="turn_context"||payload?.type==="task_started")&&typeof payload?.turn_id==="string"&&payload.turn_id!==turns.at(-1)){turns.push(payload.turn_id);if(turns.length>2)turns.shift();terminal=false}if(["task_complete","turn_aborted"].includes(payload?.type)&&payload.turn_id===current)terminal=true}const after=await handle.stat();if(stat5.size!==after.size||stat5.mtimeMs!==after.mtimeMs||stat5.ctimeMs!==after.ctimeMs)throw new Error("previous_stop_transcript_changed");if(turns.length!==2||turns[1]!==current||terminal)throw new Error("previous_stop_live_turn_unverified");return turns[0]}finally{await handle.close()}}async function recoverPreviousStop(filesystem,invocation2,composition){const session=invocation2.clientThreadId,current=invocation2.clientTurnId,path=invocation2.transcriptPath;if(!session||!current||!path)return{state:"skipped",reason:"previous_stop_identity_unavailable"};let previous,runId;try{previous=await precedingTurn(path,session,current);const receiptFile=filesystem.resolve(stopReceiptPath(session,previous));if(!await filesystem.exists(stopReceiptPath(session,previous)))return{state:"skipped",reason:"previous_stop_receipt_missing",previous_turn_id:previous};await regular(receiptFile,1024*1024);const source=JSON.parse(await filesystem.readText(stopReceiptPath(session,previous)));if(source.schema_version!==1||source.session_id!==session||source.turn_id!==previous||!["pending","persisted"].includes(source.state)||source.event?.hook_event_name!=="Stop"||source.event.session_id!==session||source.event.turn_id!==previous||typeof source.event.cwd!=="string"||identity(source.event.cwd)!==identity(filesystem.root)||typeof source.event.transcript_path!=="string"||identity(source.event.transcript_path)!==identity(path))throw new Error("previous_stop_receipt_invalid");const key=hash4(JSON.stringify(["codex",session,previous,null,null]));const correlationPath=`.local/codex-telemetry-spool/v1/correlations/${key}.json`;await regular(filesystem.resolve(correlationPath),16384);const correlation=JSON.parse(await filesystem.readText(correlationPath));if(correlation.schema_version!==1||correlation.thread_id!==session||correlation.turn_id!==previous||correlation.agent_path!==null||typeof correlation.run_id!=="string")throw new Error("previous_stop_correlation_invalid");const root=(await composition.runs.read(correlation.run_id)).run;if(root.parent_run_id!==null||root.run_role!=="orchestrator"||root.agent!=="agent-orchestrator"||root.client_thread_id!==session||root.client_turn_id!==previous||root.task_id!==correlation.task_id||source.run_id!==void 0&&source.run_id!==root.run_id)throw new Error("previous_stop_root_mismatch");runId=root.run_id;if(source.state==="persisted"){await verifyStopPersistence(filesystem,composition,session,previous,runId);return{state:"persisted",reason:null,previous_turn_id:previous,run_id:runId}}await regular(filesystem.resolve(".codex/hooks/zaip-conversation-lifecycle.mjs"),2*1024*1024);const result2=await replayStopReceipt(filesystem,session,previous,{automatic:true});if(result2.state==="persisted")await verifyStopPersistence(filesystem,composition,session,previous,runId);return{state:result2.state==="persisted"?"persisted":"pending",reason:result2.error,previous_turn_id:previous,run_id:runId}}catch(error51){return{state:"pending",reason:error51 instanceof Error?error51.message:"previous_stop_unavailable",...previous===void 0?{}:{previous_turn_id:previous},...runId===void 0?{}:{run_id:runId}}}}var identity,hash4;var init_previous_stop_recovery=__esm({"src/previous-stop-recovery.ts"(){"use strict";init_stop_receipt();identity=path=>process.platform==="win32"?toNamespacedPath2(resolve15(path)).toLowerCase():resolve15(path);hash4=value=>createHash50("sha256").update(value).digest("hex")}});function preview(parsed,filesystem,layout){return resolveConversationContinuation(parsed,createV2Composition(filesystem,layout),filesystem)}async function capture(parsed,filesystem,layout,write){const invocation2=await resolveRunClientInvocation(filesystem,parsed.options.client??"codex");const recovery=await recoverPreviousStop(filesystem,invocation2,createV2Composition(filesystem,layout));const result2=await withLifecycleCanonicalMutationLock(filesystem,()=>write({invocation:invocation2,recovery}),{timeout_ms:15e3});return{...result2,stop_recovery:recovery}}function command(action,parsed,composition,filesystem,lifecycle,captured){const pending=captured?.recovery.state==="pending"?captured.recovery:void 0;return runConversationV2Command(action,parsed,composition,filesystem,lifecycle,captured===void 0?void 0:{invocation:captured.invocation,pendingRun:pending?.run_id,pendingTurn:pending?.previous_turn_id})}async function invocation(filesystem,client,intake2){return intake2?.invocation??await resolveRunClientInvocation(filesystem,client)}async function openIntakes(composition,client,thread,turn,snapshot,intake2){return(await openThreadIntakes(composition,client,thread,turn,snapshot)).filter(fold=>fold.run.run_id!==intake2?.pendingRun&&fold.run.client_turn_id!==intake2?.pendingTurn)}var init_conversation_stop_intake=__esm({"src/conversation-stop-intake.ts"(){"use strict";init_v2_router();init_conversation_intake_settlement();init_conversation_resolution();init_lifecycle_manifest_commands();init_previous_stop_recovery();init_run_client_invocation();init_run_conversation_v2()}});import{execFile as execFileCallback}from"node:child_process";import{promisify as promisify16}from"node:util";async function runDeveloperIdentityCommand(action,parsed,filesystem){if(action==="identity")action=parsed.positionals[2];if(action==="show")return{identity:await readDeveloperIdentityCache(filesystem)};if(action==="set")action="bootstrap";if(action!=="bootstrap")throw new UsageError("developer identity requires show or bootstrap");return{identity:await resolveDeveloperIdentityForRoot(filesystem,{force:true})}}async function resolveDeveloperIdentityForRoot(filesystem,options={}){const now=options.now??new Date;const cached2=await readDeveloperIdentityCache(filesystem);if(cached2!==null&&!options.force&&!developerIdentityNeedsRevalidation(cached2,now)){return cached2}try{const account=await(options.lookup??authenticatedGithubAccount)();return writeDeveloperIdentityCache(filesystem,verifiedDeveloperIdentity(account,now))}catch(error51){if(cached2!==null)return cachedFallbackDeveloperIdentity(cached2);throw new UsageError(`GitHub bootstrap failed; authenticate with gh and retry (${error51 instanceof Error?error51.message:String(error51)})`)}}async function authenticatedGithubAccount(){try{const{stdout}=await execFile16("gh",["api","user"],{encoding:"utf8"});const parsed=JSON.parse(stdout);if(typeof parsed.id!=="number"||!Number.isSafeInteger(parsed.id)||typeof parsed.login!=="string"||parsed.login.length===0)throw new Error("GitHub user response lacks id/login");return{id:String(parsed.id),login:parsed.login}}catch(error51){throw new Error(`GitHub account lookup failed (${error51 instanceof Error?error51.message:String(error51)})`)}}var execFile16;var init_developer_identity_command=__esm({"src/developer-identity-command.ts"(){"use strict";init_src5();init_cli_arguments();execFile16=promisify16(execFileCallback)}});function validatedDirectAuthorization(parsed,clientInvocation,model){const authorization=parsed.options["direct-authorization"];if(authorization===void 0)return void 0;if(!authorization.trim()||clientInvocation.clientThreadId===null||clientInvocation.clientTurnId===null||clientInvocation.clientTurnId.startsWith("local-")||["unknown","unavailable","manual"].includes(model)){throw new UsageError("Direct execution requires an observed Task-scoped delivery root and explicit authorization")}return authorization}var init_direct_authorization=__esm({"src/direct-authorization.ts"(){"use strict";init_cli_arguments()}});function taskAssuranceRiskSignalsOption(value){if(value===void 0)return void 0;try{if(Buffer.byteLength(value,"utf8")>4096)throw new Error("size");return assuranceRiskSignalsSchema.parse(JSON.parse(value))}catch{throw new UsageError("--assurance-risk-signals requires a valid risk-signals JSON object (max 4 KiB)")}}var init_task_assurance_options=__esm({"src/task-assurance-options.ts"(){"use strict";init_src7();init_cli_arguments()}});async function createTaskAndChangeAtomically(filesystem,composition,taskInput){const created=new Map;try{const task=await composition.tasks.createDraft(taskInput);created.set(composition.tasks.path(task.id),composition.tasks.serialize(task));const change=await composition.changes.createDraft({id:task.change_id,title:task.title,risk:task.risk,taskId:task.id,requirementIds:task.requirement_ids,acceptanceIds:task.acceptance_ids});return{task,change}}catch(error51){await rollbackTaskChangeCreation(filesystem,created);throw error51}}async function rollbackTaskChangeCreation(filesystem,created){for(const[path,content]of[...created].reverse()){await filesystem.removeFileIfContentMatches(path,content)}}var init_task_change_creation=__esm({"src/task-change-creation.ts"(){"use strict"}});function compactRunAggregate(aggregate){const bucket=value=>({usage_event_count:value.usage_event_count,tokens:value.tokens,cost:value.cost,coverage:value.coverage});return{scope_id:aggregate.scope_id,run_count:aggregate.run_count,run_coverage:aggregate.run_coverage,attribution:aggregate.attribution,conversation:bucket(aggregate.conversation),planning:bucket(aggregate.planning),execution:bucket(aggregate.execution),total:bucket(aggregate.total),work_types:{new:bucket(aggregate.work_types.new),rework:bucket(aggregate.work_types.rework)}}}function runV2CostInput(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}function runV2Summary(fold,composition){const usage=aggregateRunV2Usage([runV2CostInput(fold)],fold.run.run_id).total;const callIds=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);return{id:fold.run.run_id,status:fold.status,created_at:fold.run.occurred_at,finished_at:fold.finished?.occurred_at??null,phase:latestRunV2Phase(fold.records),run_role:effectiveRunV2Role(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,intake:fold.run.intake??null,agent:fold.run.agent,agent_name:fold.run.agent_name??(fold.run.agent.startsWith("agent-")?`zaip-agent-${fold.run.agent.slice("agent-".length)}`:fold.run.agent),model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,call_count:callIds.size===0?null:callIds.size,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,usage:{event_count:usage.usage_event_count,tokens:usage.tokens,cost:usage.cost,coverage:usage.coverage},artifact_path:composition.runs.path(fold.run.run_id)}}var init_run_conversation_summary=__esm({"src/run-conversation-summary.ts"(){"use strict";init_src4();init_src5();init_conversation_intake_settlement()}});async function assertFinalizationCandidatePreflight(parent,outcome,evidenceIds,changedFiles,composition){if(parent.run.execution_kind!=="delivery")return;const taskId=parent.run.task_id;if(isParentalRelayShape(parent)){const proof=await authenticatedParentalRelay(parent,composition,true);if(!proof||changedFiles.length!==0||outcome==="completed"&&(evidenceIds.length!==proof.parentEvidenceIds.length||new Set(evidenceIds).size!==proof.parentEvidenceIds.length||evidenceIds.some(id=>!proof.parentEvidenceIds.includes(id))))throw new LifecycleGateError("Parental relay Gui requires exact original Evidence and no product changes");return}if(taskId===null){if(outcome==="completed"&&!await hasPassedTypedEvidenceForRun(parent,evidenceIds,composition))throw new LifecycleGateError("finalization-evidence: macro completion requires its passed typed Evidence before Gui decision");if(outcome==="completed"&&parent.run.spec_id!==null&&parent.run.entrypoint==="spec"){const{execution}=await composition.executions.read(parent.run.execution_id);const{spec}=await composition.specs.read(parent.run.spec_id);const context2=await parentalProofTasks(spec.id,execution.id,composition);const configured2=composition.layout.projectConfig?.assurance;await assertParentDeliveryPreflight({filesystem:composition.filesystem,layout:composition.layout,repositories:composition,spec_id:spec.id,execution_id:execution.id,acceptance_ids:spec.acceptance_ids,...context2,assurance:configured2?.version===1?configured2:{standard_depth:"auto",require_final_commit:true},selected_evidence_ids:evidenceIds,composition})}return}const executionId=parent.run.execution_id;if(executionId===null)throw new LifecycleGateError("Gui Task decision requires a delivery Execution");const{task}=await composition.tasks.read(taskId).catch(()=>{throw new LifecycleGateError(`Gui responsible Task is unavailable: ${taskId}`)});const boundary=await historicalPublishedBoundaryForTask(task,parent,composition);assertHistoricalRelayChangedFiles(boundary,changedFiles);await assertChangedFilesInScopeOrCausalRecords(task,changedFiles,composition.filesystem,executionId,composition,boundary);if(outcome!=="completed")return;if(!await hasPassedTypedEvidenceForRun(parent,evidenceIds,composition)){throw new LifecycleGateError("finalization-evidence: completed Gui decision requires passed typed Evidence linked to the same Task, Change, Execution, and Run and one candidate")}const configured=composition.layout.projectConfig?.assurance;const config2=configured?.version===1?configured:{standard_depth:"auto",require_final_commit:false};if(!effectiveTaskAssurance(task,config2).require_final_commit)return;const bundle=await readAssuranceBundle(composition.filesystem,composition.layout,[task],evidenceIds);await requireFinalProductCandidate(composition.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,changedFiles,boundary??void 0)}var init_finalization_candidate_preflight=__esm({"src/finalization-candidate-preflight.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_v2_delivery_assurance();init_parent_delivery_preflight();init_post_publication_parental();init_run_finalization_evidence_v2()}});function assertFinalizationEvidenceInput(ids2){if(ids2.some(id=>!/^EVD-[A-Z0-9-]+$/.test(id))){throw new UsageError("Finalization --evidence accepts comma-separated EVD IDs only, not JSON, Decision IDs or file paths")}return ids2}var init_finalization_evidence_input=__esm({"src/finalization-evidence-input.ts"(){"use strict";init_cli_arguments()}});function activeRunIds(value){if(typeof value!=="object"||value===null||value.schema_version!==1||!Array.isArray(value.items))return[];return value.items.flatMap(item=>{if(typeof item!=="object"||item===null)return[];const candidate=item;return candidate.kind==="run"&&candidate.status==="running"&&typeof candidate.id==="string"?[candidate.id]:[]})}function activeRunWindow(ids2,now=Date.now(),limit=32){if(!Number.isSafeInteger(limit)||limit<1||limit>32)throw new Error("Active telemetry limit must be an integer between 1 and 32");if(ids2.length===0)return ids2;const minute=Math.floor(now/6e4);const start=minute*(ids2.length<=limit?1:limit)%ids2.length;return Array.from({length:Math.min(limit,ids2.length)},(_value,index)=>ids2[(start+index)%ids2.length])}var init_v2_run_active_window=__esm({"src/source-size-cli/v2-run-active-window.ts"(){"use strict"}});import{createHash as createHash51}from"node:crypto";function nextRecentTelemetryWindow(ids2,limit,cursor){if(!Number.isSafeInteger(limit)||limit<1||limit>32)throw new UsageError("Recent telemetry limit must be an integer between 1 and 32");const candidate_sha256=createHash51("sha256").update(JSON.stringify(ids2)).digest("hex");const valid2=cursor?.schema_version===1&&Array.isArray(cursor.visited_ids)&&cursor.visited_ids.length<=512&&cursor.visited_ids.every(id=>typeof id==="string")&&Number.isSafeInteger(cursor.next_offset)&&cursor.next_offset>=0;const known2=new Set(ids2);const visited=new Set(valid2?cursor.visited_ids.filter(id=>known2.has(id)):[]);const pending=ids2.filter(id=>!visited.has(id));const offset=valid2?cursor.next_offset%Math.max(ids2.length,1):0;const selected=pending.length>0?pending.slice(0,limit):ids2.length===0?[]:Array.from({length:Math.min(limit,ids2.length)},(_value,index)=>ids2[(offset+index)%ids2.length]);const prior_visited_ids=[...visited];for(const id of selected)visited.add(id);const complete=visited.size===ids2.length;const next_offset=ids2.length===0?0:(offset+selected.length)%ids2.length;return{selected,prior_visited_ids,complete,pending_count:ids2.length-visited.size,cursor:{schema_version:1,candidate_sha256,visited_ids:[...visited],next_offset,complete}}}function recentTelemetrySegmentFinder(list=listRecentCodexSegments){const sessions=new Map;return async(root,keys2,options={})=>{const key=JSON.stringify([root,options.threadId??null,options.agentPath??null,options.parentThreadId??null,options.transcriptPath??null]);let pending=sessions.get(key);if(pending===void 0){pending=list(root,new Set,{...options,turnId:null,startedAfter:null});sessions.set(key,pending)}return[...await pending].filter(segment2=>!keys2.has(segment2.segmentKey)&&segment2.turnId===options.turnId&&(!options.requireTaskComplete||segment2.terminalType==="task_complete")).sort((left,right)=>(left.finishedAt??left.startedAt??"").localeCompare(right.finishedAt??right.startedAt??"")).at(-1)??null}}async function captureActiveRunTelemetry(parsed,composition,filesystem){if(!parsed.flags.has("disable-codex-raw"))throw new UsageError("run usage --active requires --disable-codex-raw");const activeIds=activeRunIds(await new LifecycleManifestStore(filesystem).readActiveWork());const captured=[];for(const id of activeRunWindow(activeIds,Date.now(),numberOption(parsed.options.limit,32))){const fold=await composition.runs.read(id);if(fold.finished===null&&isCodexTelemetryClient(fold.run.client)&&fold.run.client_turn_id!==null){const current=await recordCodexTelemetryIfAvailable(fold,composition,filesystem);captured.push({run_id:id,captured:current.records.length>fold.records.length})}}return{telemetry:{mode:"active_exact_session",captured},artifact_path:null}}function recentTelemetryRunIds(entities,now=Date.now()){const cutoff=now-72*60*60*1e3;return entities.filter(entity=>{const data2=entity.data;const terminalSourceMeasured=typeof data2?.source_finished_at==="string"&&Number.isFinite(Date.parse(data2.source_finished_at))&&entity.usage?.total_tokens!=null;return entity.kind==="run"&&data2!==null&&!terminalSourceMeasured&&Date.parse(entity.updated_at)>=cutoff&&typeof data2.client==="string"&&isCodexTelemetryClient(data2.client)&&typeof data2.client_thread_id==="string"&&data2.client_thread_id.length>0&&typeof data2.client_turn_id==="string"&&data2.client_turn_id.length>0&&(entity.status==="running"||entity.usage?.total_tokens==null||data2.call_coverage==="unavailable")}).map(entity=>entity.id).sort()}async function captureRecentRunTelemetry(parsed,composition,filesystem,capture2=recordCodexTelemetryIfAvailable,batchCapture=recordCodexTelemetryBatch,clock=Date.now){if(!parsed.flags.has("disable-codex-raw"))throw new UsageError("run usage --recent requires --disable-codex-raw");if(parsed.flags.has("active"))throw new UsageError("Choose only one telemetry window: --active or --recent");const automatic=!parsed.flags.has("drain");const startedAt=clock();let readEntitiesMs=0;let selectionMs=0;let runReadMs=0;let captureMs=0;let lastGroupMs=0;let preparationPending=false;let lastRunId=null;let examined=0;let candidateCount=null;let pendingCount=null;const report=async(phase2,runId=lastRunId)=>{if(!automatic||typeof filesystem.writeTextAtomic!=="function")return;await filesystem.writeTextAtomic(recentProgressPath,`${JSON.stringify({schema_version:1,phase:phase2,last_run_id:runId,candidate_count:candidateCount,processed_count:examined,pending_count:pendingCount,read_entities_ms:readEntitiesMs,selection_ms:selectionMs,run_read_ms:runReadMs,capture_ms:captureMs,elapsed_ms:clock()-startedAt,updated_at:new Date().toISOString()})}
3599
3599
  `)};await report("read_entities");const entityStartedAt=clock();const ids2=recentTelemetryRunIds(await new LifecycleManifestStore(filesystem).readEntities("run"));readEntitiesMs=clock()-entityStartedAt;candidateCount=ids2.length;await report("selection");const selectionStartedAt=clock();const limit=numberOption(parsed.options.limit,32);let previous=null;if(automatic&&typeof filesystem.readText==="function"){try{previous=JSON.parse(await filesystem.readText(recentCursorPath))}catch{previous=null}}const progress=nextRecentTelemetryWindow(ids2,limit,previous);selectionMs=clock()-selectionStartedAt;if(ids2.length>512)throw new UsageError("Recent telemetry backlog exceeds 512 Runs; capture is incomplete");const selected=automatic?progress.selected:ids2;const visited=new Set(progress.prior_visited_ids);pendingCount=ids2.length-visited.size;const captured=[];const finder=capture2===recordCodexTelemetryIfAvailable?recentTelemetrySegmentFinder():null;for(let offset=0;offset<selected.length;){if(automatic&&clock()-startedAt>=automaticTimeBudgetMs)break;if(automatic&&lastGroupMs>0&&clock()-startedAt+lastGroupMs>automaticTimeBudgetMs)break;const groupStartedAt=clock();const window=selected.slice(offset,offset+(finder===null?1:recentCaptureBatchSize));const folds=[];for(const id of window){if(automatic&&clock()-startedAt>=automaticTimeBudgetMs)break;await report("run_read",id);const runStartedAt=clock();folds.push(await composition.runs.read(id));runReadMs+=clock()-runStartedAt}if(folds.length===0)break;const eligible=folds.filter(fold=>isCodexTelemetryClient(fold.run.client)&&fold.run.client_turn_id!==null&&fold.run.client_thread_id!==null);if(eligible.length>0){await report("batch_capture",eligible[0].run.run_id);const captureStartedAt=clock();let results;try{results=finder===null?[await capture2(eligible[0],composition,filesystem)]:await batchCapture(eligible,composition,filesystem,finder,automatic?{deadline:Date.now()+Math.max(0,automaticTimeBudgetMs-(clock()-startedAt))}:{})}catch(error51){if(!automatic||!(error51 instanceof TelemetryIndexPreparationPendingError))throw error51;preparationPending=true;captureMs+=clock()-captureStartedAt;break}captureMs+=clock()-captureStartedAt;if(results.length!==eligible.length)throw new UsageError("Recent telemetry batch returned an incomplete result");for(const[index,fold]of eligible.entries())captured.push({run_id:fold.run.run_id,captured:results[index].records.length>fold.records.length})}for(const fold of folds){examined+=1;lastRunId=fold.run.run_id;visited.add(lastRunId)}pendingCount=ids2.length-visited.size;if(automatic&&typeof filesystem.writeTextAtomic==="function")await filesystem.writeTextAtomic(recentCursorPath,`${JSON.stringify({...progress.cursor,visited_ids:[...visited],complete:pendingCount===0})}
3600
3600
  `);await report("committed");lastGroupMs=clock()-groupStartedAt;offset+=folds.length;await new Promise(resolve32=>setImmediate(resolve32))}await report(preparationPending?"index_preparation_pending":"finished");return{telemetry:{mode:"recent_exact_session",captured,candidate_count:ids2.length,processed_count:examined,pending_count:automatic?pendingCount:0,complete:!automatic||!preparationPending&&pendingCount===0,...preparationPending?{deferred_reason:"index_preparation_pending"}:{},timing_ms:{read_entities:readEntitiesMs,selection:selectionMs,run_read:runReadMs,batch_capture:captureMs},last_examined_run_id:lastRunId},artifact_path:null}}var recentCursorPath,recentProgressPath,automaticTimeBudgetMs,recentCaptureBatchSize;var init_recent_run_telemetry=__esm({"src/recent-run-telemetry.ts"(){"use strict";init_src4();init_src5();init_src8();init_cli_arguments();init_record_codex_telemetry();init_v2_run_active_window();recentCursorPath=".local/codex-telemetry/recent-cursor-v1.json";recentProgressPath=".local/codex-telemetry/recent-progress-v1.json";automaticTimeBudgetMs=9e4;recentCaptureBatchSize=8}});async function settleInteractionExecutionForRun(run,composition,finalizationBlockReason){if(run.run.execution_id===null)return null;let execution=(await composition.executions.read(run.run.execution_id)).execution;if(execution.kind!=="interaction")return null;if(run.finished?.status==="cancelled"){return["running","paused","verifying"].includes(execution.status)?composition.executions.transition(execution.id,"cancelled","Run explicitly cancelled"):execution}if(finalizationBlockReason!==null){return["running","paused","verifying"].includes(execution.status)?composition.executions.transition(execution.id,"blocked",null,void 0,finalizationBlockReason):execution}if(execution.status==="running"){execution=await composition.executions.transition(execution.id,"verifying")}return execution.status==="verifying"?composition.executions.transition(execution.id,"completed","Interaction finalized"):execution}var init_v2_run_interaction_execution=__esm({"src/source-size-cli/v2-run-interaction-execution.ts"(){"use strict"}});async function runParentalPreview(parsed,composition){requireOptions(parsed.options,["actor-run","relay"]);const actor=await composition.runs.read(parsed.options["actor-run"]);const proof=await parentalRelayProof(composition,actor,parsed.options.relay,false);await assertLiveRelayAuthority(composition,proof.intent);const owners2=(await composition.runs.list()).filter(run=>run.status==="running"&&run.run.execution_id===proof.execution.id&&run.run.task_id===null&&run.run.run_purpose==="orchestration"&&run.run.agent==="agent-orchestrator");if(owners2.length>0)throw new UsageError("Parental preview has another active historical owner");const blockedReason=proof.execution.status_reason;const blockedRunId=proof.execution.status==="blocked"&&proof.spec.status==="blocked"&&blockedReason===proof.spec.status_reason?/^Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming \(Run (RUN-[A-Z0-9-]+)\)\.$/.exec(blockedReason??"")?.[1]:void 0;const blockedOwner=blockedRunId?await composition.runs.read(blockedRunId):null;const blockedParentsReady=blockedOwner!==null&&blockedOwner.finished!==null&&blockedOwner.status!=="running"&&blockedOwner.run.run_role==="orchestrator"&&blockedOwner.run.task_id===null&&blockedOwner.run.execution_id===proof.execution.id&&blockedOwner.run.spec_id===proof.spec.id;if(!blockedParentsReady&&(!["running","paused"].includes(proof.execution.status)||!["active","blocked"].includes(proof.spec.status)))throw new UsageError("Parental preview requires resumable historical parents");return{eligible:true,actor_run_id:actor.run.run_id,intent_id:proof.intentId,execution_id:proof.execution.id,execution_status:proof.execution.status,spec_id:proof.spec.id,spec_status:proof.spec.status,candidate_sha:proof.intent.candidate_sha,parent_evidence_ids:proof.parentEvidenceIds,next:{execution_resume:proof.execution.status==="paused"||blockedParentsReady,spec_activate:proof.spec.status==="blocked"}}}var init_v2_run_parental_preview=__esm({"src/commands/v2-run-parental-preview.ts"(){"use strict";init_cli_arguments();init_post_publication_parental();init_post_publication_relay_contract()}});async function cancelTaskRunsForHuman(taskId,composition,parsed){return composition.runs.withUsageAttributionLock(async()=>{const candidates=await composition.runs.list();const roots2=candidates.filter(fold=>fold.finished===null&&fold.run.parent_run_id===null&&fold.run.task_id===taskId);for(const root of roots2){await cancelActiveDescendantRuns(activeDescendantRuns(root.run.run_id,candidates),composition,parsed);await cancelActiveDescendantRuns([root],composition,parsed)}return roots2.map(root=>root.run.run_id)})}async function cancelActiveDescendantRuns(descendants,composition,parsed){for(const descendant2 of[...descendants].reverse()){let current=await composition.runs.read(descendant2.run.run_id);if(current.finished!==null)continue;if(current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const record3=runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,current.records.length+1),run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"cancelled"});foldRunV2Records([...current.records,record3]);await composition.runs.appendRecord(record3)}}var init_v2_run_cancellation_and_aggregate=__esm({"src/source-size-cli/v2-run-cancellation-and-aggregate.ts"(){"use strict";init_src4();init_src5();init_run_conversation_v2();init_run_hierarchy()}});function rootRunStartConflicts(existing,input,explicitConversationId,explicitRunId){const actual=existing.run;const candidates=[["phase",actual.phase,input.phase],["entrypoint",actual.entrypoint,input.entrypoint],["work-type",actual.work_type,input.workType],["agent",actual.agent,input.agent],["provider",actual.provider,input.provider],["model",actual.model,input.model],["reasoning-effort",actual.reasoning_effort??null,input.reasoningEffort??null],["execution",actual.execution_id,input.executionId??null],["task",actual.task_id,input.taskId??null],["spec",actual.spec_id,input.specId??null],["prd",actual.prd_id,input.prdId??null],["change",actual.change_id,input.changeId??null],["continuation",actual.continuation_of_run_id,input.continuationOfRunId??null],["retry",actual.retry_of_run_id,input.retryOfRunId??null],["purpose",actual.run_purpose??null,input.runPurpose??null],["execution-kind",actual.execution_kind??null,input.executionKind??null],["direct-authorization",actual.direct_execution_authorization??null,input.directExecutionAuthorization??null],["run-role",effectiveRunV2Role(actual),input.runRole??(input.phase==="execution"?"orchestrator":"intake")]];if(existing.finished!==null)candidates.push(["terminal",existing.finished.status,"running"]);if(explicitRunId!==void 0)candidates.push(["id",actual.run_id,explicitRunId]);if(explicitConversationId!==void 0){candidates.push(["conversation",actual.conversation_id,input.conversationId])}return candidates.filter(([,left,right])=>left!==right).map(([field])=>field)}async function assertTaskExecutionIntakeCompatibleBeforeMutation(filesystem,composition,taskId,executionId){const invocation2=await resolveRunClientInvocation(filesystem,"codex");const intake2=await findIntakeForExactTurn(composition,"codex",invocation2);if(intake2===null)return;if(intake2.run.task_id===taskId&&intake2.run.execution_id===executionId)return;throw new UsageError(`Exact client turn is already captured by intake Run ${intake2.run.run_id} (Task ${intake2.run.task_id??"none"}, Execution ${intake2.run.execution_id??"none"}); it cannot start delivery for Task ${taskId} and Execution ${executionId}. Start delivery from a new observed client turn.`)}var init_execution_intake_compatibility=__esm({"src/execution-intake-compatibility.ts"(){"use strict";init_src5();init_cli_arguments();init_conversation_intake();init_run_client_invocation()}});function inferredOrphanFailureTask(fold,tasks){if(fold.finished?.status!=="failed"||fold.run.client_thread_id!==null||fold.run.client_turn_id!==null||fold.finalization_decision!=null||effectiveRunV2Role(fold.run)!=="orchestrator")return void 0;return tasks.find(task=>{const result2=task.result;return task.id===fold.run.task_id&&task.status==="failed"&&result2!=null&&result2.completed_run_id===fold.run.run_id&&result2.changed_files.length===0&&result2.evidence_ids.length===0&&task.status_reason===`Run ${fold.run.run_id} failed and closed its operational lifecycle.`})}var init_inferred_orphan_failure=__esm({"src/inferred-orphan-failure.ts"(){"use strict";init_src5()}});async function hostTerminalOnlyPreflight(composition,filesystem){let active;try{active=await new LifecycleManifestStore(filesystem).readActiveWork()}catch{return{kind:"full"}}const items=activeWorkItems(active);if(items===null)return{kind:"full"};const activeRuns=items.filter(item=>item.kind==="run"&&item.status==="running");const operationalOwners=items.filter(isOperationalOwner);if(operationalOwners.some(owner=>!activeRuns.some(run=>run.relations.includes(owner.id)))){return{kind:"full"}}let current;try{current=await Promise.all(activeRuns.map(item=>composition.runs.read(item.id)))}catch{return{kind:"full"}}const observedTerminalRunIds=current.filter(fold=>fold.finished!==null).map(fold=>fold.run.run_id);if(observedTerminalRunIds.length>0){return{kind:"full",observed_terminal_run_ids:observedTerminalRunIds,observed_terminal_runs:current.filter(fold=>fold.finished!==null)}}const codex=current.filter(fold=>isCodexTelemetryClient(fold.run.client));if(codex.some(fold=>fold.run.client_thread_id===null||fold.run.client_turn_id===null)){return{kind:"full"}}if(codex.length>0){const activity=await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds:codex.map(fold=>fold.run.client_thread_id),invocations:codex.map(fold=>({threadId:fold.run.client_thread_id,turnId:fold.run.client_turn_id}))});const terminal=new Set(activity.lifecycles.filter(item=>item.finishedAt!==null&&item.status!=="active").map(item=>`${item.sessionId}:${item.turnId}`));if(codex.some(fold=>terminal.has(`${fold.run.client_thread_id}:${fold.run.client_turn_id}`))){return{kind:"full"}}}return{kind:"no-op",result:{runs:[],orphaned_executions:[],orphaned_interaction_executions:[],orphaned_tasks:[],orphaned_execution_entities:[],orphaned_owner_entities:[],reconciliations:[],reconciliation_errors:[],unresolved_running_run_ids:current.map(fold=>fold.run.run_id)}}}function activeWorkItems(value){if(typeof value!=="object"||value===null||value.schema_version!==1||typeof value.updated_at!=="string"||!Number.isFinite(Date.parse(value.updated_at))||!Array.isArray(value.items))return null;const items=value.items;const parsed=[];for(const item of items){if(typeof item!=="object"||item===null)return null;const candidate=item;if(typeof candidate.kind!=="string"||candidate.kind.length===0||typeof candidate.id!=="string"||candidate.id.length===0||typeof candidate.status!=="string"||candidate.status.length===0||candidate.relations!==void 0&&(!Array.isArray(candidate.relations)||candidate.relations.some(id=>typeof id!=="string")))return null;parsed.push({kind:candidate.kind,id:candidate.id,status:candidate.status,relations:candidate.relations??[]})}return parsed}function isOperationalOwner(item){return item.kind==="task"&&["executing","verifying"].includes(item.status)||item.kind==="change"&&["executing","verifying"].includes(item.status)||item.kind==="execution"&&["running","paused","verifying"].includes(item.status)||item.kind==="spec"&&item.status==="active"||item.kind==="prd"&&item.status==="active"}var init_open_work_host_preflight=__esm({"src/open-work-host-preflight.ts"(){"use strict";init_src4();init_src8();init_record_codex_telemetry()}});function runDepth(fold,runs){const parentById=new Map(runs.map(candidate=>[candidate.run.run_id,candidate.run.parent_run_id]));let depth=0;let parent=fold.run.parent_run_id;const seen=new Set([fold.run.run_id]);while(parent!==null&&!seen.has(parent)){seen.add(parent);depth+=1;parent=parentById.get(parent)??null}return depth}function terminalSubjectIds(fold){const role=effectiveRunV2Role(fold.run);if(role==="orchestrator"&&fold.run.entrypoint==="task"){return fold.run.task_id===null?[]:[fold.run.task_id]}if(role==="orchestrator"){return[fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}return[]}var init_open_work_run_topology=__esm({"src/open-work-run-topology.ts"(){"use strict";init_src5()}});function recoveryReason(id){return`Macro Execution ${id} has no unfinished Run or active descendant after the reconciliation grace period; terminal incomplete DAG work requires explicit recovery.`}async function reconcileExplicitOrphanedMacroExecution(catalog,runs,composition,now,executionId){if(executionId===void 0)return void 0;const execution=catalog.executions.find(candidate=>candidate.id===executionId);if(!isEligibleMacro(execution,catalog,runs,now))return void 0;const reason=recoveryReason(execution.id);const clock=new SystemClock;if(execution.status!=="blocked")await composition.executions.transition(execution.id,"blocked",null,clock,reason);const ancestors=await blockMacroAncestors(execution,catalog,composition,clock,reason);return{execution:(await composition.executions.read(execution.id)).execution,ancestors}}function isEligibleMacro(execution,catalog,runs,now){if(execution===void 0||execution.kind!=="delivery"||execution.origin.type==="task"||!(["running","verifying"].includes(execution.status)||execution.status==="blocked"&&execution.status_reason===recoveryReason(execution.id))||!overdue(execution,now))return false;const origin=execution.origin;if(origin.type==="prd"&&!catalog.prds.some(prd=>prd.id===origin.prd_id))return false;if(origin.type==="spec"&&!catalog.specs.some(spec=>spec.id===origin.spec_id))return false;const tasks=execution.dag.nodes.map(node=>catalog.tasks.find(task=>task.id===node.task_id));if(!tasks.every(task=>task!==void 0&&TERMINAL_TASK_STATUSES.has(task.status)))return false;if(!tasks.some(task=>task!==void 0&&["blocked","failed","cancelled"].includes(task.status)))return false;const taskIds=new Set(execution.dag.nodes.map(node=>node.task_id));const relatedRoots=runs.filter(run=>run.run.execution_id===execution.id||run.run.task_id!==null&&taskIds.has(run.run.task_id));return!relatedRoots.some(run=>run.finished===null||activeDescendantRuns(run.run.run_id,runs).length>0)}function overdue(execution,now){const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);return Number.isFinite(startedAt)&&now.getTime()-startedAt>=ORPHANED_EXECUTION_GRACE_MS}async function blockMacroAncestors(execution,catalog,composition,clock,reason){const ancestors=[];const specIds=macroSpecIds(execution,catalog);for(const specId of specIds){const spec=catalog.specs.find(candidate=>candidate.id===specId);if(spec===void 0||ancestorHasOtherWork(execution,catalog,spec.id,void 0))continue;if(spec.status==="active")ancestors.push(await composition.specs.transition(spec.id,"blocked",clock,reason));else if(spec.status==="blocked"&&spec.status_reason===reason)ancestors.push(spec)}const prdId=macroPrdId(execution,catalog,specIds);const prd=prdId===void 0?void 0:catalog.prds.find(candidate=>candidate.id===prdId);if(prd!==void 0&&!ancestorHasOtherWork(execution,catalog,void 0,prd.id)){if(prd.status==="active")ancestors.push(await composition.prds.transition(prd.id,"blocked",clock,reason));else if(prd.status==="blocked"&&prd.status_reason===reason)ancestors.push(prd)}return ancestors}function ancestorHasOtherWork(selected,catalog,specId,prdId){const selectedTasks=new Set(selected.dag.nodes.map(node=>node.task_id));const linkedSpec=id=>specId===id||prdId!==void 0&&catalog.specs.some(spec=>spec.id===id&&spec.prd_id===prdId);const changes=catalog.changes.filter(change=>{const source=change.source;return(source.type==="spec"||source.type==="prd")&&(source.spec_id!==null?linkedSpec(source.spec_id):source.type==="prd"&&prdId!==void 0&&source.prd_id===prdId)});if(changes.some(change=>change.task_ids.some(id=>{const task=catalog.tasks.find(item=>item.id===id);return!selectedTasks.has(id)&&(task===void 0||!TERMINAL_TASK_STATUSES.has(task.status))})))return true;return catalog.executions.some(other=>{if(other.id===selected.id||!OPEN_EXECUTION_STATUSES.has(other.status))return false;const specs=macroSpecIds(other,catalog);if(specId!==void 0)return specs.includes(specId);return macroPrdId(other,catalog,specs)===prdId||other.dag.nodes.some(node=>changes.some(change=>change.id===node.change_id))})}function macroSpecIds(execution,catalog){const origin=execution.origin;if(origin.type==="spec")return[origin.spec_id];if(origin.type!=="prd")return[];const changes=new Map(catalog.changes.map(change=>[change.id,change]));const ids2=execution.dag.nodes.flatMap(node=>{const source=node.change_id===void 0?void 0:changes.get(node.change_id)?.source;if(source===void 0||source.type!=="spec"&&source.type!=="prd"||source.spec_id===null)return[];return[source.spec_id]});return[...new Set(ids2)].filter(id=>catalog.specs.some(spec=>spec.id===id&&spec.prd_id===origin.prd_id))}function macroPrdId(execution,catalog,specIds){if(execution.origin.type==="prd")return execution.origin.prd_id;if(execution.origin.type!=="spec")return void 0;const spec=catalog.specs.find(candidate=>candidate.id===specIds[0]);return spec?.prd_id??void 0}async function blockOrphanedStandaloneExecutions(catalog,runs,composition,now,scope){const ids2=new Set(orphanedStandaloneExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))}));if(ids2.size===0)return[];const clock=new SystemClock;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const blocked2=[];for(const id of ids2){const execution=catalog.executions.find(item=>item.id===id);if(execution===void 0)continue;const reason=`Execution ${id} has no active orchestrator agent call after the reconciliation grace period.`;for(const node of execution.dag.nodes){const task=taskById.get(node.task_id);if(task!==void 0&&(scope===void 0||scope.matchesTask(task.id))&&["executing","verifying"].includes(task.status)){await composition.tasks.transition(task.id,"blocked",null,clock,reason)}const change=changeById.get(node.change_id);if(change!==void 0&&["executing","verifying"].includes(change.status)){const latestTasks=await Promise.all(change.task_ids.map(async taskId=>(await composition.tasks.read(taskId)).task));if(latestTasks.every(candidate=>["blocked","completed","failed","cancelled"].includes(candidate.status)))await composition.changes.transition(change.id,"blocked",null,clock,reason)}}if(execution.status!=="blocked")await composition.executions.transition(id,"blocked",null,clock,reason);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}function orphanedStandaloneExecutionIds(catalog,runs,now=new Date,includePlanned=false){return catalog.executions.flatMap(execution=>{if(execution.origin.type!=="task"||!["running","verifying",...includePlanned?["planned"]:[]].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS){return[]}const taskIds=new Set(execution.dag.nodes.map(node=>node.task_id));const hasActiveOrchestratorRun=runs.some(run=>{const required3=[run.finished===null,effectiveRunV2Role(run.run)==="orchestrator",run.run.parent_run_id===null,run.run.entrypoint==="task"];if(!required3.every(Boolean))return false;return run.run.execution_id===execution.id||run.run.task_id!==null&&taskIds.has(run.run.task_id)});return hasActiveOrchestratorRun?[]:[execution.id]})}var ORPHANED_EXECUTION_GRACE_MS,TERMINAL_TASK_STATUSES,OPEN_EXECUTION_STATUSES;var init_orphaned_macro_reconciliation=__esm({"src/orphaned-macro-reconciliation.ts"(){"use strict";init_src();init_src5();init_run_hierarchy();ORPHANED_EXECUTION_GRACE_MS=10*60*1e3;TERMINAL_TASK_STATUSES=new Set(["blocked","completed","failed","cancelled"]);OPEN_EXECUTION_STATUSES=new Set(["planned","running","paused","verifying"])}});async function reconcileOpenWork(parsed,composition,lifecycle,filesystem){const hostTerminalOnly=parsed.flags?.has("host-terminal-only")??false;let observedTerminalRunIds=[];let observedTerminalRuns=[];if(hostTerminalOnly){const preflight=await hostTerminalOnlyPreflight(composition,filesystem);if(preflight.kind==="no-op")return preflight.result;observedTerminalRunIds=preflight.observed_terminal_run_ids??[];observedTerminalRuns=preflight.observed_terminal_runs??[];if(observedTerminalRunIds.length>0){await Promise.all(observedTerminalRunIds.map(async runId=>{const current=await composition.runs.read(runId);if(isReconcilableCodexClient(current.run.client,false)&&current.run.client_thread_id!==null&&current.run.client_turn_id!==null)await recordCodexTelemetryIfAvailable(current,composition,filesystem)}))}}let runs=hostTerminalOnly&&observedTerminalRuns.length>0?[...observedTerminalRuns]:await composition.runs.list();const orphanScope=authorizedOrphanScope(parsed);if(!hostTerminalOnly&&orphanScope?.exactExecutionId!==void 0){const executions2=await composition.executions.list();const selected=executions2.find(item=>item.id===orphanScope.exactExecutionId);if(selected?.kind==="delivery"&&selected.origin.type!=="task"){const[tasks2,changes2,specs2,prds2]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.specs.list(),composition.prds.list()]);const recovered=await reconcileExplicitOrphanedMacroExecution({tasks:tasks2,changes:changes2,executions:executions2,specs:specs2,prds:prds2},runs,composition,new Date,selected.id);return{runs:[],observed_terminal_runs:[],orphaned_interaction_executions:[],orphaned_tasks:[],reconciliations:[],reconciliation_errors:[],orphaned_executions:recovered===void 0?[]:[recovered.execution.id],orphaned_execution_entities:recovered===void 0?[]:[recovered.execution],orphaned_owner_entities:recovered?.ancestors??[],unresolved_running_run_ids:runs.filter(run=>run.finished===null&&run.run.execution_id===selected.id).map(run=>run.run.run_id)}}}const runningCodex=runs.filter(fold=>[fold.finished===null,isReconcilableCodexClient(fold.run.client,orphanScope!==void 0),orphanScope===void 0?fold.run.client_thread_id!==null:orphanScope.matchesRun(fold)].every(Boolean)).sort((left,right)=>runDepth(right,runs)-runDepth(left,runs));const threadIds=runningCodex.flatMap(fold=>typeof fold.run.client_thread_id==="string"?[fold.run.client_thread_id]:[]);const invocations=runningCodex.flatMap(fold=>{const threadId=fold.run.client_thread_id;const turnId=fold.run.client_turn_id;return typeof threadId==="string"&&typeof turnId==="string"?[{threadId,turnId}]:[]});const{lifecycles:localLifecycles,activeInvocations}=threadIds.length===0?{lifecycles:[],activeInvocations:[]}:await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds,invocations});const localByInvocation=new Map(localLifecycles.map(item=>[`${item.sessionId}:${item.turnId}`,item]));const closedRuns=[];const orphanedRootRunIds=new Set;const reconciliationStartedAt=new Date;for(const fold of runningCodex){if((await composition.runs.read(fold.run.run_id)).finished!==null)continue;const local=localByInvocation.get(`${fold.run.client_thread_id??""}:${fold.run.client_turn_id??""}`);const completedLocally=(local?.status==="completed"||local?.status==="cancelled"||local?.status==="interrupted"||local?.status==="failed")&&local.finishedAt!==null;const orphaned=!hostTerminalOnly&&(isOrphanedCodexRun(fold,activeInvocations,reconciliationStartedAt)||orphanScope!==void 0&&isExplicitLegacyNoHostOrphan(fold,reconciliationStartedAt));if(!completedLocally&&!orphaned)continue;if(orphaned)orphanedRootRunIds.add(fold.run.run_id);const role=effectiveRunV2Role(fold.run);const activeChildren=activeDescendantRuns(fold.run.run_id,runs);if(role==="orchestrator"&&activeChildren.length>0){if(local?.status!=="cancelled")continue;await cancelActiveDescendantRuns2(activeChildren,composition,parsed);runs=await composition.runs.list()}let current=completedLocally?await recordCodexTelemetryIfAvailable(fold,composition,filesystem):fold;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}const finished=runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:completedLocally?local.finishedAt:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:completedLocally&&local?.status==="cancelled"?"cancelled":completedLocally&&local?.status==="failed"?"failed":completedLocally?"completed":"failed"});foldRunV2Records([...current.records,finished]);await composition.runs.appendRecord(finished);const refreshed=await composition.runs.read(current.run.run_id);closedRuns.push(refreshed);runs=replaceRunSnapshot(runs,refreshed)}let[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);let catalog={tasks,changes,executions,specs,prds};const explicitlyCancelled=hostTerminalOnly?[]:await closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,orphanScope);if(explicitlyCancelled.length>0){closedRuns.push(...explicitlyCancelled);runs=await composition.runs.list()}const activeSubjectIds=activeLifecycleSubjectIds(runs.filter(item=>item.finished===null&&!(!hostTerminalOnly&&orphanScope?.matchesRun(item)&&isOrphanedCodexRun(item,activeInvocations,reconciliationStartedAt))),catalog);const operationalSubjectIds=terminalReconciliationSubjectIds(catalog);const inferredRepairIds=new Set;if(!hostTerminalOnly&&orphanScope!==void 0){for(const fold of runs){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task===void 0||!orphanScope.matchesRun(fold)||activeSubjectIds.has(task.id)||activeDescendantRuns(fold.run.run_id,runs).length>0)continue;inferredRepairIds.add(fold.run.run_id);orphanedRootRunIds.add(fold.run.run_id);operationalSubjectIds.add(task.id)}}const reconciliations=[];const reconciliationErrors=[];const reconciledSubjectIds=new Set;const terminal=runs.filter(fold=>fold.finished!==null&&(!hostTerminalOnly||observedTerminalRunIds.includes(fold.run.run_id))&&terminalSubjectIds(fold).some(id=>operationalSubjectIds.has(id))&&(orphanScope===void 0||orphanScope.matchesRun(fold))).sort((left,right)=>(right.finished?.occurred_at??right.run.occurred_at).localeCompare(left.finished?.occurred_at??left.run.occurred_at));for(const fold of terminal){const subjects=terminalSubjectIds(fold);if(subjects.length===0||subjects.some(id=>activeSubjectIds.has(id))||subjects.every(id=>reconciledSubjectIds.has(id))){continue}try{if(inferredRepairIds.has(fold.run.run_id)){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task!==void 0)await lifecycle.startTask(task.id,"rework")}const reconciliation=hostTerminalOnly&&observedTerminalRunIds.includes(fold.run.run_id)&&effectiveRunV2Role(fold.run)==="orchestrator"?await reconcileTerminalOrchestratorRoot(fold,runs,composition,lifecycle):await reconcileFinishedRunLifecycle(fold,composition,lifecycle,{...inferredRepairIds.has(fold.run.run_id)?{}:{catalog},candidateRuns:runs,...orphanedRootRunIds.has(fold.run.run_id)?{requestedOutcome:"blocked",forceRequestedOutcome:true,summary:"Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming"}:{}});reconciliations.push("reconciliation"in reconciliation?reconciliation.reconciliation:reconciliation)}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);reconciliations.push({...await snapshotRunLifecycle(fold,composition,catalog),status:"deferred",error:message2});reconciliationErrors.push({run_id:fold.run.run_id,error:message2})}subjects.forEach(id=>{reconciledSubjectIds.add(id)})}[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);catalog={tasks,changes,executions,specs,prds};const orphanedExecutions=hostTerminalOnly?[]:await blockOrphanedStandaloneExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedInteractionExecutions=hostTerminalOnly?[]:await blockOrphanedInteractionExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedMacro=hostTerminalOnly?void 0:await reconcileExplicitOrphanedMacroExecution(catalog,runs,composition,reconciliationStartedAt,orphanScope?.exactExecutionId);const orphanedOwnerEntities=await readOrphanedExecutionOwners([...orphanedExecutions,...orphanedInteractionExecutions],composition);return{runs:closedRuns,observed_terminal_runs:observedTerminalRunIds.map(run_id=>({run_id})),orphaned_executions:[...orphanedExecutions.map(execution=>execution.id),...orphanedMacro===void 0?[]:[orphanedMacro.execution.id]],orphaned_interaction_executions:orphanedInteractionExecutions.map(execution=>execution.id),orphaned_tasks:[],orphaned_execution_entities:[...orphanedExecutions,...orphanedInteractionExecutions,...orphanedMacro===void 0?[]:[orphanedMacro.execution]],orphaned_owner_entities:[...orphanedOwnerEntities,...orphanedMacro?.ancestors??[]],reconciliations,reconciliation_errors:reconciliationErrors,unresolved_running_run_ids:runs.filter(fold=>fold.finished===null).map(fold=>fold.run.run_id)}}function replaceRunSnapshot(runs,refreshed){return runs.map(fold=>fold.run.run_id===refreshed.run.run_id?refreshed:fold)}async function readOrphanedExecutionOwners(executions,composition){const taskIds=new Set;const changeIds=new Set;for(const execution of executions){for(const node of execution.dag.nodes){taskIds.add(node.task_id);if(node.change_id!==void 0)changeIds.add(node.change_id)}}return Promise.all([...[...taskIds].map(async id=>(await composition.tasks.read(id)).task),...[...changeIds].map(async id=>(await composition.changes.read(id)).change)])}async function closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,scope){const cancelledTaskIds=new Set(catalog.tasks.filter(task=>task.status==="cancelled").map(task=>task.id));const closed=[];for(const fold of runs){if(fold.finished!==null||effectiveRunV2Role(fold.run)!=="orchestrator"||fold.run.parent_run_id!==null||fold.run.entrypoint!=="task"||fold.run.task_id===null||!cancelledTaskIds.has(fold.run.task_id)||scope!==void 0&&!scope.matchesRun(fold)){continue}const current=await composition.runs.read(fold.run.run_id);if(current.finished!==null)continue;const activeChildren=activeDescendantRuns(current.run.run_id,runs);if(activeChildren.length>0)await cancelActiveDescendantRuns2(activeChildren,composition,parsed);let attributable=await composition.runs.read(current.run.run_id);if(attributable.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(attributable,parsed,attributable.records.length+1));attributable=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${attributable.run.run_id}:${String(attributable.records.length+1).padStart(6,"0")}`,run_id:attributable.run.run_id,sequence:attributable.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(attributable.records),status:"cancelled"}));closed.push(await composition.runs.read(current.run.run_id))}return closed}async function cancelActiveDescendantRuns2(descendants,composition,parsed){for(const descendant2 of[...descendants].reverse()){let current=await composition.runs.read(descendant2.run.run_id);if(current.finished!==null)continue;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"cancelled"}))}}async function blockOrphanedInteractionExecutions(catalog,runs,composition,now,scope){const ids2=orphanedInteractionExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))});if(ids2.length===0)return[];const clock=new SystemClock;const blocked2=[];for(const id of ids2){await composition.executions.transition(id,"blocked",null,clock,`Interaction Execution ${id} has no active orchestrator Run after the reconciliation grace period.`);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}function orphanedInteractionExecutionIds(catalog,runs,now=new Date){return catalog.executions.flatMap(execution=>{if(execution.kind!=="interaction"||!["running","verifying"].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS2){return[]}const hasActiveRoot=runs.some(run=>run.finished===null&&effectiveRunV2Role(run.run)==="orchestrator"&&run.run.parent_run_id===null&&run.run.execution_id===execution.id);return hasActiveRoot?[]:[execution.id]})}function terminalReconciliationSubjectIds(catalog){const ids2=new Set;const unsettledTaskIds=new Set(catalog.tasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.id));unsettledTaskIds.forEach(id=>{ids2.add(id)});for(const change of catalog.changes){const unsettled=["planned","executing","verifying"].includes(change.status);const hasUnsettledTask=change.task_ids.some(id=>unsettledTaskIds.has(id));if(!unsettled&&!hasUnsettledTask)continue;change.task_ids.forEach(id=>{ids2.add(id)});if(change.source.type==="spec")ids2.add(change.source.spec_id);if(change.source.type==="prd"){ids2.add(change.source.prd_id);if(change.source.spec_id!==null)ids2.add(change.source.spec_id)}}for(const execution of catalog.executions){if(!["planned","running","paused","verifying"].includes(execution.status))continue;execution.dag.nodes.forEach(node=>{ids2.add(node.task_id)})}catalog.specs.filter(spec=>spec.status==="active").forEach(spec=>{ids2.add(spec.id)});catalog.prds.filter(prd=>prd.status==="active").forEach(prd=>{ids2.add(prd.id)});return ids2}function authorizedOrphanScope(parsed){const reason=parsed.options["orphan-reason"];const scope=parsed.options["orphan-scope"];if(reason===void 0&&scope===void 0)return void 0;if(reason!=="inactive_terminal_without_host_identity"){throw new Error("--orphan-reason must be inactive_terminal_without_host_identity for explicit orphan reconciliation")}if(scope===void 0||scope.trim().length===0){throw new Error("Explicit orphan reconciliation requires --orphan-scope all or comma-separated Run/Task/Execution IDs")}const ids2=new Set(scope.split(",").map(value=>value.trim()).filter(Boolean));if(ids2.size===0)throw new Error("--orphan-scope must name all or at least one canonical ID");const[onlyId]=[...ids2];const exactExecutionId=ids2.size===1&&onlyId?.startsWith("EXEC-")?onlyId:void 0;return{...exactExecutionId===void 0?{}:{exactExecutionId},matchesRun(fold){return ids2.has("all")||ids2.has(fold.run.run_id)||fold.run.task_id!==null&&ids2.has(fold.run.task_id)||fold.run.execution_id!==null&&ids2.has(fold.run.execution_id)},matchesTask(taskId){return ids2.has("all")||ids2.has(taskId)},matchesExecution(execution){return ids2.has("all")||ids2.has(execution.id)||execution.origin.type==="task"&&ids2.has(execution.origin.task_id)||execution.dag.nodes.some(node=>ids2.has(node.task_id))}}}function isOrphanedCodexRun(fold,activeInvocations,now=new Date){if(fold.finished!==null||!isCodexTelemetryClient(fold.run.client))return false;const startedAt=Date.parse(fold.run.occurred_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_RUN_GRACE_MS){return false}return!activeInvocations.some(active=>{if(active.sessionId!==fold.run.client_thread_id)return false;const activeObservedAt=Date.parse(active.observedAt??active.startedAt??"");if(!Number.isFinite(activeObservedAt)||now.getTime()-activeObservedAt>ORPHANED_RUN_GRACE_MS){return false}if(active.turnId===fold.run.client_turn_id)return true;const activeStartedAt=active.startedAt===null?Number.NaN:Date.parse(active.startedAt);return Number.isFinite(activeStartedAt)&&Math.abs(activeStartedAt-startedAt)<=ACTIVE_INVOCATION_START_TOLERANCE_MS})}function isReconcilableCodexClient(client,explicitScope){return isCodexTelemetryClient(client)||explicitScope&&EXPLICIT_LEGACY_CODEX_CLIENTS.has(client)}function isExplicitLegacyNoHostOrphan(fold,now){if(fold.finished!==null||!EXPLICIT_LEGACY_CODEX_CLIENTS.has(fold.run.client)||fold.run.client_thread_id!==null){return false}const startedAt=Date.parse(fold.run.occurred_at);return Number.isFinite(startedAt)&&now.getTime()-startedAt>=ORPHANED_RUN_GRACE_MS}function activeLifecycleSubjectIds(activeRuns,catalog){const ids2=new Set;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const specById=new Map(catalog.specs.map(spec=>[spec.id,spec]));for(const fold of activeRuns){relatedWorkIds(fold).forEach(id=>{ids2.add(id)});const task=fold.run.task_id===null?void 0:taskById.get(fold.run.task_id);const change=task===void 0?void 0:changeById.get(task.change_id);const specId=fold.run.spec_id??(change?.source.type==="spec"||change?.source.type==="prd"?change.source.spec_id:null);const prdId=fold.run.prd_id??(change?.source.type==="prd"?change.source.prd_id:null)??(specId===null?null:specById.get(specId)?.prd_id??null);if(change!==void 0)ids2.add(change.id);if(specId!==null)ids2.add(specId);if(prdId!==null)ids2.add(prdId);for(const candidate of catalog.changes){const belongsToSpec=specId!==null&&candidate.source.type!=="task"&&candidate.source.spec_id===specId;const belongsToPrd=candidate.source.type==="prd"&&candidate.source.prd_id===prdId;if(!belongsToSpec&&!belongsToPrd)continue;ids2.add(candidate.id);candidate.task_ids.forEach(id=>{ids2.add(id)})}for(const execution of catalog.executions){if(execution.origin.type==="prd"&&execution.origin.prd_id===prdId||execution.origin.type==="spec"&&execution.origin.spec_id===specId){ids2.add(execution.id);execution.dag.nodes.forEach(node=>{ids2.add(node.task_id)})}}}return ids2}function relatedWorkIds(fold){return[fold.run.task_id,fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}var ORPHANED_RUN_GRACE_MS,ORPHANED_EXECUTION_GRACE_MS2,ACTIVE_INVOCATION_START_TOLERANCE_MS,EXPLICIT_LEGACY_CODEX_CLIENTS;var init_open_work_reconciliation=__esm({"src/open-work-reconciliation.ts"(){"use strict";init_src();init_src4();init_src5();init_inferred_orphan_failure();init_open_work_host_preflight();init_open_work_run_topology();init_orchestrator_stop_reconciliation();init_orphaned_macro_reconciliation();init_record_codex_telemetry();init_run_conversation_v2();init_run_hierarchy();init_run_lifecycle_reconciliation();init_orphaned_macro_reconciliation();ORPHANED_RUN_GRACE_MS=10*60*1e3;ORPHANED_EXECUTION_GRACE_MS2=10*60*1e3;ACTIVE_INVOCATION_START_TOLERANCE_MS=2*60*1e3;EXPLICIT_LEGACY_CODEX_CLIENTS=new Set(["codex-prd-authoring","codex-prd-composite-authoring"])}});async function loadAgentCatalog(filesystem){if(!await filesystem.exists(AGENT_CATALOG_PATH2)){throw new UsageError(`Agent catalog not found at ${AGENT_CATALOG_PATH2}`)}const catalog=parseAgentCatalog(parseYaml(await filesystem.readText(AGENT_CATALOG_PATH2)));const findings=validateAgentCatalog(catalog);if(findings.length>0){throw new Error(`Invalid Agent catalog: ${findings[0]?.message??"unknown finding"}`)}return catalog}async function resolveRunAgentIdentityResult(filesystem,input){const client=input.client.trim();if(client.length===0)throw new UsageError("--client must not be empty");const fallback=client==="codex"||client.startsWith("codex-")?"codex":client;const requested=input.agent?.trim();if(requested===void 0||requested.length===0||requested===client||requested===fallback){return{agent_id:fallback,warning:null}}const catalog=await loadAgentCatalog(filesystem).catch(error51=>{if(error51 instanceof UsageError){throw new UsageError(`${error51.message}; omit --agent to use fallback "${fallback}"`)}throw error51});try{const selected=resolveAgentIdentity(catalog,requested);return{agent_id:selected.canonical_id,warning:selected.warning}}catch(error51){if(!(error51 instanceof Error)||!error51.message.startsWith("Unknown Agent identity:")){throw new UsageError(error51 instanceof Error?error51.message:String(error51))}}const available=catalog.agents.flatMap(agent=>[agent.id,agent.codex_name]).sort().join(", ");throw new UsageError(`Unknown Agent "${requested}". Use one of: ${available}; omit --agent to use fallback "${fallback}"`)}async function resolveRunAgentName(filesystem,agentId2){if(agentId2==="codex")return"codex";if(!agentId2.startsWith("agent-"))return agentId2;const catalog=await loadAgentCatalog(filesystem);return catalog.agents.find(agent=>agent.id===agentId2)?.codex_name??null}var AGENT_CATALOG_PATH2;var init_run_agent_identity=__esm({"src/run-agent-identity.ts"(){"use strict";init_src();init_cli_arguments();AGENT_CATALOG_PATH2=".agents/config/agents/catalog.yaml"}});function defaultExecutionPolicy(risk2,signals={}){const independentBranches=signals.independent_branches===true;return{failure_policy:"stop_on_terminal_failure",max_parallelism:risk2==="lite"?1:independentBranches?risk2==="critical"?3:2:1,max_operational_retries:risk2==="lite"?0:1,max_repair_cycles_per_task:risk2==="lite"?0:2,soft_model_cycle_budget:risk2==="lite"?4:risk2==="standard"?24:40,context_refresh_after_cycles:risk2==="lite"?4:8,verification_mode:risk2==="critical"?"full":"scoped",max_cost_usd:signals.max_cost_usd??null}}function completeObservedCostUsd(costs){if(costs.length===0||costs.some(cost3=>cost3===null))return null;return costs.reduce((sum,cost3)=>sum+cost3,0)}async function evaluateRunBudget(run,composition,filesystem){if(run.run.execution_id===null)return null;const execution=(await composition.executions.read(run.run.execution_id)).execution;const cycles=run.effective_usage_records.length;const providerInputTokens=run.effective_usage_records.reduce((sum,event)=>sum+Math.max(0,(event.tokens.input??0)-(event.tokens.cached_input??0)),0);const observedContextTokens=run.effective_usage_records.reduce((sum,event)=>sum+(event.context_stats?.initial_pack_tokens??0)+(event.context_stats?.tool_output_tokens??0),0);const measuredInputTokens=providerInputTokens>0?providerInputTokens:observedContextTokens;const cycleBudget=execution.policy.soft_model_cycle_budget??null;const refreshAfter=execution.policy.context_refresh_after_cycles??null;const checkpointRequired=cycleBudget!==null&&cycles>=cycleBudget;const contextRefreshRequired=refreshAfter!==null&&cycles>0&&cycles%refreshAfter===0;const costCapUsd=execution.policy.max_cost_usd??null;const observedCostUsd=completeObservedCostUsd(run.effective_usage_records.map(event=>event.cost.usd));const hasCompleteObservedCost=observedCostUsd!==null;const budget={schema_version:1,run_id:run.run.run_id,execution_id:execution.id,measured_at:new Date().toISOString(),cycles,provider_uncached_input_tokens:providerInputTokens,observed_context_tokens:observedContextTokens,measured_input_tokens:measuredInputTokens,measurement_source:providerInputTokens>0?"provider_uncached":"context_stats",soft_model_cycle_budget:cycleBudget,context_refresh_after_cycles:refreshAfter,max_cost_usd:costCapUsd,observed_cost_usd:observedCostUsd,cost_measurement_source:hasCompleteObservedCost?"observed":"unavailable",cost_checkpoint_required:costCapUsd!==null&&observedCostUsd!==null&&observedCostUsd>=costCapUsd,checkpoint_required:checkpointRequired,context_refresh_required:contextRefreshRequired};if(checkpointRequired||contextRefreshRequired||budget.cost_checkpoint_required){await filesystem.writeTextAtomic(`.local/checkpoints/${run.run.run_id}.json`,`${JSON.stringify(budget,null,2)}
3601
3601
  `)}return budget}var init_run_budget=__esm({"src/run-budget.ts"(){"use strict"}});async function reconcileHistoricalCodexTiming(parsed,composition,filesystem,fallbackSegmentFinder=findLatestCodexSegment){return composition.runs.withUsageAttributionLock(async()=>{requireOptions(parsed.options,["id","session","turn"]);const id=parsed.options.id;const turnId=parsed.options.turn;const sessionPath=parsed.options.session;const current=await composition.runs.read(id);if(current.run.client_turn_id!==turnId){throw new UsageError(`Run ${id} is not correlated with the requested turn`)}const candidate=await fallbackSegmentFinder(filesystem.root,new Set,{turnId,sessionPaths:[sessionPath],...current.run.client_thread_id==null?{}:{threadId:current.run.client_thread_id}});if(candidate===null||candidate.startedAt===null||candidate.finishedAt===null||candidate.turnId!==turnId){throw new UsageError("No completed observed interval exists for the requested Run/session/turn")}const sourceSegmentKey=candidate.segmentKey;const sourceUsage=current.effective_usage_records.find(record3=>record3.source_segment_key===sourceSegmentKey);const timingOnly=sourceUsage===void 0;const remeasurement=sourceUsage===void 0?null:await remeasureObservedCalls(candidate,sourceUsage,filesystem);const sourceFinishedAt=remeasurement?.source_finished_at??candidate.finishedAt;const existing=current.records.find(record3=>record3.type==="usage.recorded"&&record3.source_segment_key===sourceSegmentKey&&"source_started_at"in record3&&record3.source_started_at===candidate.startedAt&&"source_finished_at"in record3&&record3.source_finished_at===sourceFinishedAt);const timing={run_id:id,session:sessionPath,turn_id:turnId,source_started_at:candidate.startedAt,source_finished_at:sourceFinishedAt,source_duration_ms:Date.parse(sourceFinishedAt)-Date.parse(candidate.startedAt),source_segment_key:sourceSegmentKey,supersedes_event_id:sourceUsage?.event_id??null,usage:timingOnly?"unavailable":"preserved",...remeasurement===null?{}:{remeasurement}};const enrichesUsage=sourceUsage!==void 0&&remeasurement!==null&&(sourceUsage.tokens.cache_write_input==null&&remeasurement.tokens.cache_write_input!=null||sourceUsage.cost.usd===null&&remeasurement.cost.usd!==null||sourceUsage.cost.brl===null&&remeasurement.cost.brl!==null);if(existing!==void 0&&!enrichesUsage)return{applied:false,reason:"already-reconciled",timing};const existingOwner=(await composition.runs.list()).find(fold=>fold.run.run_id!==id&&fold.effective_usage_records.some(record3=>record3.source_segment_key===sourceSegmentKey||record3.source_segment_key?.startsWith(`${sourceSegmentKey}@`)===true));if(existingOwner!==void 0){throw new UsageError(`Observed source segment is already attributed to ${existingOwner.run.run_id}`)}if(parsed.flags.has("dry-run"))return{applied:false,reason:"dry-run",timing};const sequence=current.records.length+1;await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,sequence),run_id:id,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:timingOnly?"retrospective_observed_timing":"retrospective_local_remeasurement",classification_source:sourceUsage?.classification_source??"current_context",tokens:remeasurement?.tokens??sourceUsage?.tokens??{input:null,cached_input:null,cache_write_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:remeasurement?.cost??sourceUsage?.cost??{usd:null,brl:null,fx_rate:null},provider:sourceUsage?.provider??null,model:sourceUsage?.model??null,source_segment_key:sourceSegmentKey,supersedes_event_id:sourceUsage?.event_id??null,retrospective_correction:true,source_occurred_at:sourceFinishedAt,source_started_at:candidate.startedAt,source_finished_at:sourceFinishedAt}));return{applied:true,timing,artifact_path:composition.runs.path(id)}})}async function remeasureObservedCalls(candidate,sourceUsage,filesystem){const matchingLoops=observedCallPrefix(candidate,sourceUsage.tokens);if(matchingLoops===null){throw new UsageError("Observed Model Calls do not match the canonical usage record")}const observed=aggregateSegmentUsage({...candidate,loops:matchingLoops});if(observed.input!==sourceUsage.tokens.input||observed.cached_input!==sourceUsage.tokens.cached_input||observed.output!==sourceUsage.tokens.output||observed.reasoning!==sourceUsage.tokens.reasoning||observed.total!==sourceUsage.tokens.total){throw new UsageError("Observed Model Calls do not match the canonical usage record")}const pricing=new PricingRepository(filesystem);const[catalog,fxRate]=await Promise.all([pricing.readCatalog(),pricing.readLatestFxRate()]);const estimates=matchingLoops.map(loop=>{const model=loop.model??candidate.model??sourceUsage.model;const provider=inferProvider(model??"",sourceUsage.provider??"","");return estimateUsageCost({provider,model:model??"",usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null})});if(estimates.some(estimate=>estimate.estimated_usd===null)){throw new UsageError("Observed Model Calls cannot be priced by the current catalog")}const usd=estimates.reduce((total,estimate)=>total+(estimate.estimated_usd??0),0);return{source_call_count:matchingLoops.length,source_finished_at:matchingLoops.at(-1)?.timestamp??candidate.finishedAt,tokens:observed,cost:{usd,brl:fxRate===null?null:usd*fxRate.rate,fx_rate:fxRate?.rate??null}}}function observedCallPrefix(candidate,expected){for(let count=1;count<=candidate.loops.length;count+=1){const loops=candidate.loops.slice(0,count);const usage=aggregateSegmentUsage({...candidate,loops});if(usage.input===expected.input&&usage.cached_input===expected.cached_input&&usage.output===expected.output&&usage.reasoning===expected.reasoning&&usage.total===expected.total){return loops}}return null}var init_v2_run_historical_codex_timing=__esm({"src/source-size-cli/v2-run-historical-codex-timing.ts"(){"use strict";init_src4();init_src5();init_cli_arguments();init_run_conversation_v2()}});async function recoverRunAttribution(id,composition){return composition.runs.withUsageAttributionLock(async()=>{const current=await composition.runs.read(id);const started=current.records[0];if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${id}`);if(started?.type!=="run.started")throw new UsageError(`Run V2 has no start record: ${id}`);if(current.attribution_recovery!==null){throw new UsageError(`Run V2 already has an attribution recovery: ${id}`)}if(current.run.entrypoint!=="task"||current.run.execution_id===null||current.run.task_id===null||current.run.change_id!==null){throw new UsageError(`Run ${id} is not an active task Run with an unclaimed Change attribution`)}const task=await composition.tasks.read(current.run.task_id);const changeId=task.task.change_id;if(changeId===null)throw new UsageError(`Task ${task.task.id} has no materialized Change`);await validateRunV2Attribution({shortName:current.run.run_id,phase:"execution",entrypoint:"task",workType:current.run.work_type,client:current.run.client,agent:current.run.agent,provider:current.run.provider,model:current.run.model,conversationId:current.run.conversation_id,executionId:current.run.execution_id,taskId:current.run.task_id,changeId,parentRunId:current.run.parent_run_id,continuationOfRunId:current.run.continuation_of_run_id,retryOfRunId:current.run.retry_of_run_id},composition);const record3=runAttributionRecoveredV2Schema.parse({schema_version:2,event_id:runV2EventId(id,current.records.length+1),run_id:id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.attribution.recovered",phase:"execution",execution_id:current.run.execution_id,task_id:current.run.task_id,change_id:changeId});await composition.runs.appendRecord(record3);return{recovery:record3,run:runV2Summary(await composition.runs.read(id),composition),artifact_path:composition.runs.path(id)}})}var init_v2_run_attribution_recovery=__esm({"src/commands/v2-run-attribution-recovery.ts"(){"use strict";init_src5();init_attribution_v2();init_cli_arguments();init_run_conversation_v2()}});async function snapshotRuns(filesystem){const store=new LifecycleManifestStore(filesystem);const entities=await store.readEntities("run");if(entities.length===0&&await store.readSummary()===null)throw incomplete("run","snapshot");return entities.map(fromEntity)}function filterSnapshotRuns(runs,parsed){const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);const phase2=parsed.options.phase===void 0?void 0:runV2PhaseOption(parsed.options.phase);const entry2=parsed.options.entrypoint===void 0?void 0:runV2EntrypointOption(parsed.options.entrypoint);const work2=parsed.options["work-type"]===void 0?void 0:runV2WorkTypeOption(parsed.options["work-type"]);return runs.filter(run=>{const at=Date.parse(run.created_at);if(statuses.size&&!statuses.has(run.status)||from!==null&&at<from||to!==null&&at>to||parsed.options.agent!==void 0&&parsed.options.agent!==run.agent&&parsed.options.agent!==run.agent_name)return false;return[[parsed.positionals[2],run.id],[parsed.options.id,run.id],[phase2,run.phase],[entry2,run.entrypoint],[work2,run.work_type],[parsed.options.conversation,run.conversation_id],[parsed.options.execution,run.execution_id],[parsed.options.task,run.task_id],[parsed.options.spec,run.spec_id],[parsed.options.prd,run.prd_id],[parsed.options.change,run.change_id]].every(([wanted,actual])=>wanted===void 0||wanted===actual)}).sort((a,b)=>b.created_at.localeCompare(a.created_at)||b.id.localeCompare(a.id))}function snapshotCostInput(run){return{run:{run_id:run.id,attribution_status:run.attribution_status,conversation_id:run.conversation_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,work_type:run.work_type},records:run.pricing_segments,effective_usage_records:run.pricing_segments}}function aggregateSnapshotRunsByAgent(runs){const groups=new Map;for(const run of runs){const key=run.agent_name??run.agent;groups.set(key,[...groups.get(key)??[],run])}return[...groups.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([name,group])=>{const durations=group.flatMap(run=>run.terminal_finished_at===null?[]:duration3(run.created_at,run.terminal_finished_at));const aggregate=aggregateRunV2Usage(group.map(snapshotCostInput),name);const cycles=group.map(run=>run.pricing_segments.length);return{agent:group[0]?.agent??name,agent_name:name,run_count:group.length,rework_runs:group.filter(run=>run.work_type==="rework").length,duration:{known_runs:durations.length,unknown_runs:group.length-durations.length,total_ms:durations.reduce((a,b)=>a+b,0),average_ms:durations.length?Math.round(durations.reduce((a,b)=>a+b,0)/durations.length):null},observed_usage_cycles:{total:cycles.reduce((a,b)=>a+b,0),average:cycles.length?Number((cycles.reduce((a,b)=>a+b,0)/cycles.length).toFixed(2)):null},tokens:aggregate.total.tokens,cost:aggregate.total.cost,coverage:aggregate.run_coverage}})}function snapshotObservedSourceTiming(runs){return summarizeObservedSourceTiming(runs.flatMap(run=>run.pricing_segments).map(segment2=>({phase:segment2.phase,source_started_at:segment2.source_started_at,source_finished_at:segment2.source_finished_at})))}function filterRunV2Folds(runs,parsed){const snapshots=runs.map(fold=>({id:fold.run.run_id,status:fold.status,created_at:fold.run.occurred_at,phase:fold.records.findLast(record3=>"phase"in record3)?.phase??fold.run.phase,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,agent:fold.run.agent,agent_name:fold.run.agent_name??null,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id}));const ids2=new Set(filterSnapshotRuns(snapshots,parsed).map(run=>run.id));return runs.filter(run=>ids2.has(run.run.run_id))}function fromEntity(entity){const d=data(entity);return{id:entity.id,status:string4(entity.status,"status"),created_at:string4(d.started_at,"started_at"),terminal_finished_at:nullable2(d.terminal_finished_at),effective_finished_at:nullable2(d.finished_at),phase:phase(d.phase),run_role:string4(d.run_role,"run_role"),parent_run_id:nullable2(d.parent_run_id),entrypoint:entry(d.entrypoint),work_type:work(d.work_type),intake:intake(d.intake),agent:string4(d.agent,"agent"),agent_name:nullable2(d.cli_agent_name),model:string4(d.model,"model"),reasoning_effort:nullable2(d.reasoning_effort),call_count:nullableNumber(d.cli_call_count,"cli_call_count"),client_thread_id:nullable2(d.client_thread_id),client_turn_id:nullable2(d.client_turn_id),conversation_id:d.conversation_id===null?null:string4(d.conversation_id,"conversation_id"),execution_id:nullable2(d.execution_id),task_id:nullable2(d.task_id),spec_id:nullable2(d.spec_id),prd_id:nullable2(d.prd_id),change_id:nullable2(d.change_id),attribution_status:attribution(d.attribution_status),pricing_segments:segments(d.pricing_segments)}}function data(entity){if(entity.data===null)throw incomplete(entity.id,"data");return entity.data}function string4(v,f){if(typeof v!=="string"||!v)throw incomplete("run",f);return v}function nullable2(v){if(v===null)return null;if(typeof v==="string")return v;throw incomplete("run","nullable")}function nullableNumber(v,f){if(v===null)return null;if(typeof v==="number"&&Number.isInteger(v)&&v>=0)return v;throw incomplete("run",f)}function phase(v){if(v==="conversation"||v==="planning"||v==="execution")return v;throw incomplete("run","phase")}function entry(v){if(v==="conversation"||v==="task"||v==="spec"||v==="prd")return v;throw incomplete("run","entrypoint")}function work(v){if(v==="new"||v==="rework")return v;throw incomplete("run","work_type")}function attribution(v){if(v==="attributed"||v==="legacy_unattributed")return v;throw incomplete("run","attribution_status")}function intake(v){if(v===null)return null;if(typeof v!=="object"||v===null)throw incomplete("run","intake");const x=v;if(typeof x.intent!=="string"||typeof x.classification_source!=="string"||typeof x.confidence!=="number"||!Array.isArray(x.reason_codes)||!x.reason_codes.every(item=>typeof item==="string"))throw incomplete("run","intake");return{intent:x.intent,classification_source:x.classification_source,confidence:x.confidence,reason_codes:x.reason_codes}}function segments(v){if(!Array.isArray(v))throw incomplete("run","pricing_segments");return v.map(item=>{if(typeof item!=="object"||item===null)throw incomplete("run","pricing_segments");const x=item;return{event_id:string4(x.event_id,"pricing_segments.event_id"),phase:phase(x.phase),tokens:tokens(x),cost:cost2(x),source_started_at:nullable2(x.source_started_at),source_finished_at:nullable2(x.source_finished_at),attributed_spec_id:nullable2(x.attributed_spec_id)}})}function tokens(x){return{input:metric4(x.input_tokens,"input_tokens"),cached_input:metric4(x.cached_input_tokens,"cached_input_tokens"),output:metric4(x.output_tokens,"output_tokens"),reasoning:metric4(x.reasoning_tokens,"reasoning_tokens"),total:metric4(x.total_tokens,"total_tokens")}}function cost2(x){return{usd:metric4(x.recorded_usd,"recorded_usd"),brl:metric4(x.recorded_brl,"recorded_brl")}}function metric4(v,f){if(v===null)return null;if(typeof v==="number"&&Number.isFinite(v)&&v>=0)return v;throw incomplete("run",f)}function duration3(a,b){const n=Date.parse(b)-Date.parse(a);return Number.isFinite(n)&&n>=0?[n]:[]}function incomplete(id,field){return new Error(`Run snapshot is incomplete (${id}: ${field}); run \`zaip manifest rebuild --confirm-full-scan\``)}var init_v2_run_snapshot=__esm({"src/commands/v2-run-snapshot.ts"(){"use strict";init_src4();init_src8();init_cli_arguments()}});function sameStringSet(left,right){return left.length===right.length&&left.every(value=>right.includes(value))}function runV2ScopeOption(parsed){return parsed.positionals[2]??parsed.options.id??parsed.options.conversation??parsed.options.execution??parsed.options.task??parsed.options.spec??parsed.options.prd??parsed.options.change??null}var init_v2_run_support=__esm({"src/commands/v2-run-support.ts"(){"use strict"}});var v2_run_exports={};__export(v2_run_exports,{activeRunWindow:()=>activeRunWindow,cancelTaskRunsForHuman:()=>cancelTaskRunsForHuman,filterRunV2Folds:()=>filterRunV2Folds,runRunV2Command:()=>runRunV2Command});async function runRunV2Command(action,parsed,composition,filesystem,lifecycle){if(action==="parental-preview")return runParentalPreview(parsed,composition);if(action==="start"){requireOptions(parsed.options,["short-name","phase","entrypoint","work-type","client","model"]);const client=parsed.options.client;const phase2=runV2PhaseOption(parsed.options.phase);const parentRunId=parsed.options.parent??null;const clientInvocation=await resolveRunClientInvocation(filesystem,client);const agentResolution=await resolveRunAgentIdentityResult(filesystem,{agent:parsed.options.agent,client});const agent=agentResolution.agent_id;const runPurpose=parsed.options["run-purpose"]===void 0?phase2!=="execution"?"intake":agent==="agent-finalizer"?"finalization":agent==="agent-reviewer"?"review":agent==="agent-auditor"?"audit":parentRunId===null?"orchestration":"execution":runV2PurposeSchema.parse(parsed.options["run-purpose"]);const catalog=await loadAgentCatalog(filesystem).catch(()=>null);const catalogAgent=catalog?.agents.find(candidate=>candidate.id===agent);const parent=parentRunId===null?null:await composition.runs.read(parentRunId);const execution=parent===null&&parsed.options.execution!==void 0?await composition.executions.read(parsed.options.execution).catch(()=>null):null;const executionKind=parent?.run.execution_kind??execution?.execution.kind??void 0;const rootDeveloperIdentity=parentRunId===null?await resolveDeveloperIdentityForRoot(filesystem):void 0;const input={...parsed.options.id===void 0?{}:{id:parsed.options.id},shortName:parsed.options["short-name"],phase:phase2,...parsed.options["run-role"]===void 0?{}:{runRole:runV2RoleSchema.parse(parsed.options["run-role"])},runPurpose,...executionKind===void 0?{}:{executionKind},executionEligibility:catalogAgent?.execution_eligibility??[],...parsed.options["direct-authorization"]===void 0?{}:{directExecutionAuthorization:parsed.options["direct-authorization"]},entrypoint:runV2EntrypointOption(parsed.options.entrypoint),workType:runV2WorkTypeOption(parsed.options["work-type"]),client,agent,agentName:await resolveRunAgentName(filesystem,agent),...agentResolution.warning===null?{}:{agentIdentityWarning:agentResolution.warning},provider:parsed.options.provider??null,model:parsed.options.model,reasoningEffort:parsed.options["reasoning-effort"]===void 0?null:runV2ReasoningEffortSchema.parse(parsed.options["reasoning-effort"]),...clientInvocation,conversationId:parsed.options.conversation??createConversationId(parsed.options["short-name"]),executionId:parsed.options.execution??null,taskId:parsed.options.task??null,specId:parsed.options.spec??null,prdId:parsed.options.prd??null,changeId:parsed.options.change??null,parentRunId,continuationOfRunId:parsed.options.continuation??null,retryOfRunId:parsed.options.retry??null,...rootDeveloperIdentity===void 0?{}:{developerIdentity:rootDeveloperIdentity}};await validateRunV2Attribution(input,composition);if(parentRunId===null){const existing=await findRootRunForExactTurn(composition,client,clientInvocation);if(existing!==null){const conflicts=rootRunStartConflicts(existing,input,parsed.options.conversation,parsed.options.id);if(conflicts.length>0){throw new UsageError(`Exact client turn is already captured by root Run ${existing.run.run_id}; requested root Run conflicts on ${conflicts.join(", ")}. Reuse matching metadata or start the delivery from a new observed client turn.`)}return{run:existing.run,artifact_path:composition.runs.path(existing.run.run_id),warnings:agentResolution.warning===null?[]:[agentResolution.warning],reused:true}}}const start=async()=>{if(parentRunId!==null){const freshParent=await composition.runs.read(parentRunId);const candidates=await composition.runs.list();assertChildRunMayStart(freshParent,runPurpose,agent,candidates,catalogAgent?.execution_eligibility??[])}const writer=await composition.runs.start(input);return{run:writer.started,artifact_path:composition.runs.path(writer.started.run_id),warnings:agentResolution.warning===null?[]:[agentResolution.warning]}};return parentRunId===null?start():composition.runs.withUsageAttributionLock(start)}if(action==="list"||action==="aggregate"){const runs=filterSnapshotRuns(await snapshotRuns(filesystem),parsed);if(action==="aggregate"){const aggregate=aggregateRunV2Usage(runs.map(snapshotCostInput),runV2ScopeOption(parsed));const agents=aggregateSnapshotRunsByAgent(runs);const observed_source_timing=snapshotObservedSourceTiming(runs);return parsed.options.view==="full"?{...aggregate,agents,observed_source_timing}:{...compactRunAggregate(aggregate),agents,observed_source_timing}}const summaries=runs.map(run=>({id:run.id,status:run.status,created_at:run.created_at,finished_at:run.terminal_finished_at,phase:run.phase,run_role:run.run_role,parent_run_id:run.parent_run_id,entrypoint:run.entrypoint,work_type:run.work_type,intake:run.intake,agent:run.agent,agent_name:run.agent_name??(run.agent.startsWith("agent-")?`zaip-agent-${run.agent.slice("agent-".length)}`:run.agent),model:run.model,reasoning_effort:run.reasoning_effort,call_count:run.call_count,client_thread_id:run.client_thread_id,client_turn_id:run.client_turn_id,conversation_id:run.conversation_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,usage:(()=>{const usage=aggregateRunV2Usage([snapshotCostInput(run)],run.id).total;return{event_count:usage.usage_event_count,tokens:usage.tokens,cost:usage.cost,coverage:usage.coverage}})(),artifact_path:composition.runs.path(run.id)}));return listLifecyclePage(summaries,parsed)}if(action==="reconcile"){if(parsed.flags.has("open"))return reconcileOpenWork(parsed,composition,lifecycle,filesystem);return reconcileHistoricalCodexTiming(parsed,composition,filesystem)}if(action==="usage"&&parsed.flags.has("recent"))return captureRecentRunTelemetry(parsed,composition,filesystem);if(action==="usage"&&parsed.flags.has("active"))return captureActiveRunTelemetry(parsed,composition,filesystem);const id=requiredEntityId(parsed,2,"Run V2 id");if(action==="show"){const run=await composition.runs.read(id);const includeEvents=parsed.flags.has("events")||parsed.options["event-id"]!==void 0||parsed.options["from-sequence"]!==void 0;return includeEvents?{run:{...run,records:run.records.filter(record3=>(parsed.options["event-id"]===void 0||record3.event_id===parsed.options["event-id"])&&(parsed.options["from-sequence"]===void 0||record3.sequence>=numberOption(parsed.options["from-sequence"],1)))},artifact_path:composition.runs.path(id)}:runV2Summary(run,composition)}if(action==="recover-attribution")return recoverRunAttribution(id,composition);if(action==="closure"){const current=await composition.runs.read(id);if(current.finished===null)throw new UsageError(`Run V2 is still running: ${id}`);const closure=await assessRunLifecycleClosure(current,composition);if(closure.status==="action_required"){throw new UsageError(`Run ${id} left related work open: ${closure.open_subject_ids.join(", ")}. ${closure.guidance}`)}return{closure,artifact_path:composition.runs.path(id)}}if(action==="usage"){let current=await composition.runs.read(id);if(!await hookTrackingEnabled(filesystem))return{telemetry:{tracking:"disabled"},run:runV2Summary(current,composition),artifact_path:composition.runs.path(id)};const appServerEventsPath=parsed.options["codex-app-server-events"];const rawCaptureDisabled=parsed.flags.has("disable-codex-raw");if(appServerEventsPath!==void 0&&!rawCaptureDisabled){const notifications=parseCodexAppServerNotificationStream(await filesystem.readText(appServerEventsPath));const persisted=await ingestCodexAppServerNotifications(filesystem,notifications);current=await recordCodexTelemetryIfAvailable(current,composition,filesystem);return{telemetry:{received_notifications:notifications.length,persisted_event_ids:persisted.map(event=>event.event_id)},run:runV2Summary(current,composition),artifact_path:composition.runs.path(id)}}if(rawCaptureDisabled){current=await recordCodexTelemetryIfAvailable(current,composition,filesystem);return{telemetry:{raw_capture:"disabled",fallback:"codex_session_fallback"},run:runV2Summary(current,composition),artifact_path:composition.runs.path(id)}}if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${id}`);const sequence=current.records.length+1;const input=nullableNumberOption(parsed.options["input-tokens"]);const cachedInput=nullableNumberOption(parsed.options["cached-input-tokens"]);const outputTokens=nullableNumberOption(parsed.options["output-tokens"]);const reasoning=nullableNumberOption(parsed.options["reasoning-tokens"]);const explicitTotal=nullableNumberOption(parsed.options["total-tokens"]);const occurredAt=new Date().toISOString();const tokens2={input,cached_input:cachedInput,output:outputTokens,reasoning,total:explicitTotal??(input===null||outputTokens===null?null:input+outputTokens),source:tokenSourceOption(parsed.options["token-source"])};const provider=inferProvider(parsed.options.model??current.run.model,parsed.options.provider??current.run.provider??current.run.client,current.run.agent);const pricing=new PricingRepository(filesystem);const estimated=estimateUsageCost({provider,model:parsed.options.model??current.run.model,usage:tokens2,catalog:await pricing.readCatalog(),fxRate:await pricing.readLatestFxRate()});const record3=usageRecordedV2Schema.parse({schema_version:2,event_id:parsed.options["event-id"]??runV2EventId(id,sequence),run_id:id,sequence,occurred_at:occurredAt,type:"usage.recorded",phase:runV2PhaseOption(parsed.options.phase??latestRunV2Phase(current.records)),activity_kind:parsed.options.activity??"implementation",classification_source:runV2ClassificationOption(parsed.options.classification),tokens:tokens2,cost:{usd:nullableCurrencyOption(parsed.options["cost-usd"])??estimated.estimated_usd,brl:nullableCurrencyOption(parsed.options["cost-brl"])??estimated.estimated_brl,fx_rate:parsed.options["cost-brl"]===void 0?estimated.fx_rate:null},provider,model:parsed.options.model??current.run.model,source_segment_key:parsed.options["source-segment"]??null,supersedes_event_id:parsed.options.supersedes??null,...runUsageMetadataOptions(parsed.options,occurredAt)});const folded=foldRunV2Records([...current.records,record3]);await composition.runs.appendRecord(record3);const budget=await evaluateRunBudget(folded,composition,filesystem);return{usage:record3,budget,artifact_path:composition.runs.path(id)}}if(action==="finish"){const telemetryCandidate=await composition.runs.read(id);if(process.env.ZAIP_HOOK_TRACKING_ENABLED!=="false")await recordCodexTelemetryIfAvailable(telemetryCandidate,composition,filesystem);return composition.runs.withUsageAttributionLock(async()=>{let current=await composition.runs.read(id);const status=runV2FinishStatusOption(parsed.options.status);const candidateRuns=await composition.runs.list();const suppliedEvidenceIds=csvOption(parsed.options.evidence);const finalizationDecision=current.finalization_decision??null;if(finalizationDecision!==null&&suppliedEvidenceIds.length>0&&!sameStringSet(suppliedEvidenceIds,finalizationDecision.evidence_ids)){throw new UsageError("--evidence must match the persisted Gui finalization decision")}const evidenceIds=finalizationDecision?.evidence_ids??suppliedEvidenceIds;const suppliedChangedFiles=csvOption(parsed.options["changed-files"]);if(finalizationDecision!==null&&suppliedChangedFiles.length>0&&!sameStringSet(suppliedChangedFiles,finalizationDecision.changed_files)){throw new UsageError("--changed-files must match the persisted Gui finalization decision")}const changedFiles=finalizationDecision?.changed_files??suppliedChangedFiles;const finalizationBarrier=assessRunFinalizationBarrier(current,candidateRuns,await hasPassedTypedEvidenceForRun(current,evidenceIds,composition,candidateRuns));const barrierBlockReason=finalizationBarrierBlockReason(finalizationBarrier);const finalizationBlockReason=finalizationDecision!==null&&finalizationDecision.outcome!=="completed"?null:barrierBlockReason;const suppliedOutcome=lifecycleOutcomeOption(parsed.options);const missingFinalizationDecision=ownsLifecycleAttempt(current)&&finalizationBarrier.required&&finalizationDecision===null;if(finalizationDecision!==null&&suppliedOutcome!==void 0&&suppliedOutcome!==finalizationDecision.outcome){throw new UsageError(`--task-outcome must match the persisted Gui decision (${finalizationDecision.outcome})`)}if(finalizationDecision!==null&&parsed.options.summary!==void 0&&parsed.options.summary!==finalizationDecision.summary){throw new UsageError("--summary must match the persisted Gui finalization decision")}const mustFailClosed=finalizationBlockReason!==null||missingFinalizationDecision;const requestedOutcome=mustFailClosed?"blocked":finalizationDecision?.outcome??suppliedOutcome;const reconciliationSummary=finalizationBlockReason??(missingFinalizationDecision?"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.":finalizationDecision?.summary??parsed.options.summary);if(current.finished===null&&ownsLifecycleAttempt(current)){const activeChildren=activeDescendantRuns(id,candidateRuns);if(activeChildren.length>0){throw new UsageError(`Run ${id} cannot finish while descendant Runs are active: ${activeChildren.map(child=>child.run.run_id).join(", ")}`)}}if(!mustFailClosed&&parsed.flags.has("defer-orchestrator-closure")&&ownsLifecycleAttempt(current)){throw new UsageError(`Orchestrator Run closure cannot be deferred for Run ${id}`)}const deferClosure=!mustFailClosed&&parsed.flags.has("defer-orchestrator-closure");if(current.finished!==null){if(current.finished.status!==status){throw new UsageError(`Run V2 is already ${current.finished.status}: ${id}`)}const reconciliation2=await reconcileFinishedRunLifecycle(current,composition,lifecycle,{requestedOutcome,forceRequestedOutcome:mustFailClosed,summary:reconciliationSummary,changedFiles,evidenceIds,defer:deferClosure,candidateRuns});const interactionExecution2=await settleInteractionExecutionForRun(current,composition,mustFailClosed?reconciliationSummary??null:finalizationBlockReason);return{run:parsed.flags.has("events")||parsed.options.view==="full"?current:runV2Summary(current,composition),reconciliation:reconciliation2,execution:interactionExecution2,finalization_barrier:finalizationBarrier,closure:await assessRunLifecycleClosure(current,composition,candidateRuns),artifact_path:composition.runs.path(id)}}if(await hookTrackingEnabled(filesystem)&&current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const sequence=current.records.length+1;const record3=runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,sequence),run_id:id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status});const prospectiveRun=foldRunV2Records([...current.records,record3]);const closureGate=new LifecycleV2Gate(filesystem,composition.layout,{...composition,runs:runClosureView(composition.runs,current,prospectiveRun)});const reconciliation=await reconcileFinishedRunLifecycle(prospectiveRun,composition,closureGate,{requestedOutcome,forceRequestedOutcome:mustFailClosed,summary:reconciliationSummary,changedFiles,evidenceIds,defer:deferClosure,candidateRuns});const interactionExecution=await settleInteractionExecutionForRun(prospectiveRun,composition,mustFailClosed?reconciliationSummary??null:finalizationBlockReason);await syncLifecycleManifestResult({reconciliation,execution:interactionExecution},"execution",parsed,composition,filesystem);await composition.runs.appendRecord(record3);const run=await composition.runs.read(id);const closure=await assessRunLifecycleClosure(run,composition,candidateRuns);return{run:parsed.flags.has("events")||parsed.options.view==="full"?run:runV2Summary(run,composition),reconciliation,execution:interactionExecution,finalization_barrier:finalizationBarrier,closure,artifact_path:composition.runs.path(id)}})}if(action==="finalization"){const current=await composition.runs.read(id);if(!ownsLifecycleAttempt(current)){throw new UsageError(`Run ${id} is not an orchestrator Run`)}const outcome=lifecycleOutcomeOption(parsed.options);if(outcome===void 0)throw new UsageError("Missing options: --task-outcome");const summary=parsed.options.summary?.trim();if(summary===void 0||summary.length===0)throw new UsageError("Missing options: --summary");const evidenceIds=csvOption(parsed.options.evidence);assertFinalizationEvidenceInput(evidenceIds);const changedFiles=csvOption(parsed.options["changed-files"]);const requestedFinalizerRunId=parsed.options["finalizer-run-id"]?.trim();return composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(id);const existing=fresh.finalization_decision??null;if(existing!==null){if(requestedFinalizerRunId!==void 0&&requestedFinalizerRunId.length>0&&existing.finalizer_run_id!==requestedFinalizerRunId||existing.outcome!==outcome||existing.summary!==summary||!sameStringSet(existing.evidence_ids,evidenceIds)||!sameStringSet(existing.changed_files,changedFiles)){throw new UsageError(`Run ${id} already has a different Gui finalization decision`)}return{finalization:existing,reused:true,artifact_path:composition.runs.path(id)}}const lockedCandidates=await composition.runs.list();const finalizers=lockedCandidates.filter(candidate=>candidate.run.parent_run_id===id&&effectiveRunV2Purpose(candidate.run)==="finalization"&&candidate.run.agent==="agent-finalizer");const activeFinalizers=finalizers.filter(candidate=>candidate.finished===null);const terminalFallbackFinalizers=finalizers.filter(candidate=>candidate.finished!==null&&candidate.run.client==="codex-subagent"&&candidate.run.client_turn_id===null&&candidate.run.provider===null&&candidate.run.model==="unavailable");const candidatesForDecision=fresh.finished===null?activeFinalizers:terminalFallbackFinalizers;const lockedFinalizer=requestedFinalizerRunId===void 0||requestedFinalizerRunId.length===0?candidatesForDecision.length===1?candidatesForDecision[0]:void 0:candidatesForDecision.find(candidate=>candidate.run.run_id===requestedFinalizerRunId);if(lockedFinalizer===void 0){if(fresh.finished!==null){throw new UsageError(`Run ${id} requires its exact terminal fallback Gui finalizer to record a post-close decision`)}throw new UsageError(`Run ${id} requires an active Gui finalizer to record its decision`)}if(fresh.finished!==null&&fresh.finished.status!=="completed"){throw new UsageError(`Run V2 is already ${fresh.finished.status}: ${id}`)}const lockedActiveElsewhere=activeDescendantRuns(id,lockedCandidates).filter(candidate=>candidate.run.run_id!==lockedFinalizer.run.run_id);if(lockedActiveElsewhere.length>0){throw new UsageError(`Gui finalization for Run ${id} requires every other descendant to be terminal: ${lockedActiveElsewhere.map(run=>run.run.run_id).join(", ")}`)}await assertFinalizationCandidatePreflight(fresh,outcome,evidenceIds,changedFiles,composition);const record3=runFinalizationDecidedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,fresh.records.length+1),run_id:id,sequence:fresh.records.length+1,occurred_at:new Date().toISOString(),type:"run.finalization.decided",finalizer_run_id:lockedFinalizer.run.run_id,outcome,summary,evidence_ids:evidenceIds,changed_files:changedFiles});await composition.runs.appendRecord(record3);return{finalization:record3,reused:false,artifact_path:composition.runs.path(id)}})}throw new UsageError(`Unknown Run V2 action: ${action??""}`)}var init_v2_run=__esm({"src/commands/v2-run.ts"(){"use strict";init_src4();init_finalization_candidate_preflight();init_finalization_evidence_input();init_hook_tracking_policy();init_task_attempt();init_recent_run_telemetry();init_v2_run_interaction_execution();init_v2_run_parental_preview();init_v2_run_cancellation_and_aggregate();init_src5();init_attribution_v2();init_cli_arguments();init_conversation_intake();init_developer_identity_command();init_execution_intake_compatibility();init_lifecycle_manifest_commands();init_lifecycle_v2();init_open_work_reconciliation();init_record_codex_telemetry();init_run_agent_identity();init_run_budget();init_run_client_invocation();init_run_closure_view();init_run_conversation_v2();init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_hierarchy();init_run_lifecycle_closure();init_run_lifecycle_reconciliation();init_v2_run_historical_codex_timing();init_v2_run_attribution_recovery();init_v2_run_snapshot();init_v2_run_support();init_v2_run_active_window();init_v2_run_snapshot()}});async function runConversationV2Command(action,parsed,composition,filesystem,lifecycle,intake2){if(action==="start"){const client=parsed.options.client??"codex";const clientInvocation=await invocation(filesystem,client,intake2);const requestedIntent=resolveConversationIntent(parsed,clientInvocation.userMessage);assertDefinitionConversationIntake(parsed,requestedIntent);if(requestedIntent==="git_only"||isImplicitConversationCapture(parsed)&&isGitOnlyPublicationRequest(clientInvocation.userMessage)){return{skipped:true,reason:"git-only-publication",message:"Explicit deploy, push, and publication requests do not create ZAIP lifecycle records"}}const request=conversationRequestOptions(clientInvocation.userMessage);const intakeSnapshot=await composition.runs.list({client,threadId:clientInvocation.clientThreadId});const threadContext=await latestThreadContext(composition,client,clientInvocation.clientThreadId,intakeSnapshot);let intent=requestedIntent;const newWorkMetadata=intent==="new_work"?requireSemanticNewWorkMetadata(parsed):null;let target=intent==="continue"||intent==="refine"||intent==="rework"?explicitIntakeTarget(parsed)??threadContext.implicitTarget:null;let decision=intakeDecision(parsed,intent,clientInvocation.userMessage);if(intent==="new_work"&&newWorkMetadata!==null&&decision.classification_source!=="explicit"&&threadContext.implicitTarget?.taskId!==void 0){const focusedTask=(await composition.tasks.read(threadContext.implicitTarget.taskId)).task;if((focusedTask.status==="draft"||focusedTask.status==="planned")&&focusedTask.started_at===null&&describesEquivalentWork(newWorkMetadata,focusedTask)){intent="continue";target=threadContext.implicitTarget;decision={intent:"continue",classification_source:"fallback",confidence:1,reason_codes:["equivalent-thread-work-reused"]}}}if((intent==="continue"||intent==="refine"||intent==="rework")&&target===null){intent="conversation";target=null;decision={intent:"conversation",classification_source:"fallback",confidence:0,reason_codes:["target-not-resolved"]}}const existing=await findIntakeForExactTurn(composition,client,clientInvocation,intakeSnapshot);if(existing!==null){assertExactIntakeRequestCompatible(existing,parsed,intent);const task2=existing.run.task_id===null?null:(await composition.tasks.read(existing.run.task_id)).task;assertConversationProfileReplay(parsed.options,task2?.model_profile);return{task:task2,run:existing.run,task_path:task2===null?null:composition.tasks.path(task2.id),run_path:composition.runs.path(existing.run.run_id),reused:true}}const model=resolveConversationModel(parsed.options.model,clientInvocation.observedModel);const reasoningEffort=resolveConversationReasoningEffort(parsed.options["reasoning-effort"],clientInvocation.observedReasoningEffort);const timeZone=composition.layout.project.timezone;const conversationId2=parsed.options.conversation??threadContext.conversationId??createConversationId(intent==="new_work"?"new-work":"conversation");const clientTurnId=clientInvocation.clientTurnId??`local-${Date.now()}-${createCollisionCode(16)}`;const executionPolicy={failure_policy:"stop_on_terminal_failure",max_parallelism:1,max_operational_retries:1,max_repair_cycles_per_task:0,verification_mode:"scoped"};let activeTaskContinuation=false;const directAuthorization=validatedDirectAuthorization(parsed,clientInvocation,model);const commonInput=(executionId,executionKind)=>({...parsed.options.run===void 0?{}:{id:parsed.options.run},phase:conversationCapturePhase(intent,activeTaskContinuation),workType:runV2WorkTypeOption(intent==="rework"?"rework":parsed.options["work-type"]??"new"),client,runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:executionKind==="delivery",executionKind,executionEligibility:[],...directAuthorization===void 0||executionKind!=="delivery"?{}:{directExecutionAuthorization:directAuthorization},agent:"agent-orchestrator",agentName:"zaip-agent-orchestrator",provider:parsed.options.provider??null,model,reasoningEffort,clientThreadId:clientInvocation.clientThreadId,clientTurnId,conversationId:conversationId2,executionId,intake:decision});if(intent==="new_work"&&composition.layout.projectConfig?.assurance?.require_final_commit===true)await assertGitDeliveryReady(filesystem.root);const rootDeveloperIdentity=await resolveDeveloperIdentityForRoot(filesystem);const openIntakes2=await openIntakes(composition,client,clientInvocation.clientThreadId,clientInvocation.clientTurnId,intakeSnapshot,intake2);const continuationOfRunId=resolveContinuationPredecessor(intakeSnapshot,openIntakes2,target);if(intent!=="new_work"){if(intent==="continue"&&target?.taskId!==void 0){const targetedTask=(await composition.tasks.read(target.taskId)).task;if(targetedTask.status==="blocked"){await lifecycle.startTask(targetedTask.id,"resume")}}const canonicalTaskExecution=target?.taskId===void 0?null:await activeCanonicalTaskExecution(target.taskId,composition);const canonicalMacroExecution=intent==="continue"&&target?.taskId===void 0&&(target?.specId!==void 0||target?.prdId!==void 0)?await resolveCanonicalMacroExecution(target,composition,parsed.options.execution):null;let execution=target===null?await composition.executions.createInteraction({id:parsed.options.execution??createId("EXEC",`interaction-${intent}`,{timeZone}),clientTurnId,conversationId:conversationId2,policy:executionPolicy}):canonicalTaskExecution??canonicalMacroExecution??await composition.executions.createDeliveryIntake({id:parsed.options.execution??createId("EXEC",`delivery-${intent}`,{timeZone}),clientTurnId,origin:target.taskId!==void 0?{type:"task",task_id:target.taskId}:target.specId!==void 0?{type:"spec",spec_id:target.specId}:{type:"prd",prd_id:target.prdId},policy:executionPolicy});const targetTask=target?.taskId===void 0?null:(await composition.tasks.read(target.taskId)).task;activeTaskContinuation=intent==="continue"&&(canonicalTaskExecution!==null&&targetTask!==null&&(targetTask.status==="executing"||targetTask.status==="verifying")||canonicalMacroExecution!==null);if(canonicalMacroExecution?.status==="planned"){execution=await composition.executions.transition(canonicalMacroExecution.id,"running")}const input={...commonInput(execution.id,execution.kind??"delivery"),developerIdentity:rootDeveloperIdentity,shortName:parsed.options["short-name"]??intent.replaceAll("_","-"),entrypoint:target?.entrypoint??"conversation",...target?.taskId===void 0?{}:{taskId:target.taskId},...targetTask===null?{}:{changeId:targetTask.change_id},...target?.specId===void 0?{}:{specId:target.specId},...target?.prdId===void 0?{}:{prdId:target.prdId},continuationOfRunId};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const settledIntakes=await finishOpenThreadIntakes(openIntakes2,composition,filesystem,parsed,lifecycle);const task2=input.taskId==null?null:(await composition.tasks.read(input.taskId)).task;return{task:task2,run:writer.started,settled_intakes:settledIntakesForView(settledIntakes,parsed.options.view),task_path:task2===null?null:composition.tasks.path(task2.id),run_path:composition.runs.path(writer.started.run_id)}}const metadata3=newWorkMetadata??requireSemanticNewWorkMetadata(parsed);const modelProfile=conversationTaskModelProfile(parsed.options);const taskId=parsed.options.task??createId("TASK",metadata3.shortName,{timeZone});const changeId=parsed.options.change??createId("CHG",metadata3.shortName,{timeZone});const{task,change}=await createTaskAndChangeAtomically(filesystem,composition,{id:taskId,changeId,title:metadata3.title,shortName:metadata3.shortName,objective:metadata3.objective,risk:modelProfile?.risk??riskOption(parsed.options.risk??request.risk),modelProfile,priority:priorityOption(parsed.options.priority),targetRelease:await taskFirstRelease(filesystem,parsed.options["target-release"]),owner:parsed.options.owner??null,requirementIds:csvOption(parsed.options.requirements??"REQ-WORK-001"),acceptanceIds:csvOption(parsed.options.acceptance??"AC-WORK-001-09"),dependsOn:[],writeScopes:csvOption(parsed.options["write-scopes"]),assuranceRiskSignals:taskAssuranceRiskSignalsOption(parsed.options["assurance-risk-signals"])});const createdArtifacts=new Map([[composition.tasks.path(task.id),composition.tasks.serialize(task)],[composition.changes.path(change.id),composition.changes.serialize(change)]]);let deliveryExecution;try{deliveryExecution=await composition.executions.createDeliveryIntake({id:parsed.options.execution??createId("EXEC",`delivery-${intent}`,{timeZone}),clientTurnId,origin:{type:"task",task_id:task.id},policy:executionPolicy})}catch(error51){await rollbackTaskChangeCreation(filesystem,createdArtifacts);throw error51}try{const plan=createTaskFirstPreparedPlan({task,executionId:deliveryExecution.id,preparedAt:new Date().toISOString(),policy:executionPolicy});await composition.tasks.setPreparedPlan(task.id,plan);await composition.materializer.execute(plan);await composition.executions.transition(deliveryExecution.id,"running");await composition.changes.transition(changeId,"executing");const activeTask=await lifecycle.startTask(task.id);const input={...commonInput(deliveryExecution.id,"delivery"),developerIdentity:rootDeveloperIdentity,shortName:metadata3.shortName,entrypoint:"task",taskId,changeId};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const settledIntakes=await finishOpenThreadIntakes(openIntakes2,composition,filesystem,parsed,lifecycle);return{task:activeTask,assurance_planning:assurancePlanning(activeTask,effectiveTaskAssurance(activeTask,composition.layout.projectConfig?.assurance?.version===1?composition.layout.projectConfig.assurance:{standard_depth:"auto",require_final_commit:false})),run:writer.started,settled_intakes:settledIntakesForView(settledIntakes,parsed.options.view),task_path:composition.tasks.path(task.id),run_path:composition.runs.path(writer.started.run_id)}}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);await composition.tasks.transition(taskId,"cancelled",{summary:`Conversation Run was not created: ${message2}`,changed_files:[],evidence_ids:[],completed_run_id:null});await composition.changes.transition(changeId,"cancelled",`Conversation Run was not created: ${message2}`);const currentExecution=(await composition.executions.read(deliveryExecution.id)).execution;if(currentExecution.status==="planned"||currentExecution.status==="running"){await composition.executions.transition(deliveryExecution.id,"cancelled",`Conversation Run was not created: ${message2}`)}throw error51}}if(action==="finish"){requireOptions(parsed.options,["run","summary"]);const runId=parsed.options.run;const current=await composition.runs.read(runId);if(parsed.options.task!==void 0&&current.run.task_id!==parsed.options.task)throw new UsageError(`Run ${runId} is not attributed to Task ${parsed.options.task}`);if(parsed.flags.has("cancel-task"))throw new UsageError("--cancel-task cannot bypass Gui; finish the delivery Run after Gui finalization");const{runRunV2Command:runRunV2Command2}=await Promise.resolve().then(()=>(init_v2_run(),v2_run_exports));const result2=await runRunV2Command2("finish",{...parsed,positionals:["run","finish",runId]},composition,filesystem,lifecycle);const task=current.run.task_id===null?null:(await composition.tasks.read(current.run.task_id)).task;return{...result2,task,summary:parsed.options.summary,task_path:task===null?null:composition.tasks.path(task.id),run_path:composition.runs.path(runId)}}throw new UsageError(`Unknown Conversation action: ${action??""}`)}var init_run_conversation_v2=__esm({"src/run-conversation-v2.ts"(){"use strict";init_src();init_src5();init_assurance_planning();init_attribution_v2();init_conversation_model_observation();init_lifecycle_assurance_v2();init_cli_arguments();init_conversation_canonical_execution();init_conversation_continuation_owner();init_conversation_canonical_execution();init_conversation_intake();init_conversation_intake_settlement();init_conversation_stop_intake();init_developer_identity_command();init_direct_authorization();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_task_assurance_options();init_task_change_creation();init_run_conversation_summary();init_conversation_intake_settlement()}});async function completedStopSnapshot(root,composition){const r=root.run,decision=root.finalization_decision;if(r.parent_run_id!==null||r.run_role!=="orchestrator"||r.entrypoint!=="task"||r.execution_kind!=="delivery"||r.task_id===null||r.change_id===null||r.execution_id===null||root.finished?.status!=="completed"||decision?.outcome!=="completed")return null;try{const[{task},{change},{execution},gui]=await Promise.all([composition.tasks.read(r.task_id),composition.changes.read(r.change_id),composition.executions.read(r.execution_id),composition.runs.read(decision.finalizer_run_id)]);if(task.id!==r.task_id||task.status!=="completed"||task.change_id!==r.change_id||task.result?.completed_run_id!==r.run_id||change.id!==r.change_id||change.status!=="completed"||!change.task_ids.includes(task.id)||execution.id!==r.execution_id||execution.status!=="completed"||execution.origin.type!=="task"||execution.origin.task_id!==task.id||execution.dag.nodes.length!==1||execution.dag.nodes[0]?.task_id!==task.id||execution.dag.nodes[0]?.change_id!==change.id||gui.run.run_id!==decision.finalizer_run_id||gui.run.parent_run_id!==r.run_id||gui.run.task_id!==task.id||gui.run.change_id!==change.id||gui.run.execution_id!==execution.id||gui.run.agent!=="agent-finalizer"||gui.run.run_purpose!=="finalization"||gui.finished?.status!=="completed"||!decision.evidence_ids.length||decision.evidence_ids.some(id=>!task.result?.evidence_ids.includes(id)))return null;return{status:"closed",parent_run_id:r.run_id,already_reconciled:true,finalization_decision:decision,finalization_barrier:{required:true,evidence_required:true,evidence_satisfied:true,status:"completed",finalizer_run_id:decision.finalizer_run_id,satisfied:true,source:"immutable_completed_task"},reconciliation:{run_id:r.run_id,status:"closed",outcome:"completed",fallback_from:null,error:null,tasks:[task],changes:[change],executions:[execution],specs:[],prds:[]}}}catch{return null}}var init_completed_stop=__esm({"src/host-native-delegation/completed-stop.ts"(){"use strict"}});import{createHash as createHash52}from"node:crypto";function closureReceiptPath(runId){return`.local/lifecycle-closure/${createHash52("sha256").update(runId).digest("hex")}.json`}async function reconcilePendingAncestorStops(child,composition,lifecycle){let parentId=child.run.parent_run_id;const seen=new Set;while(parentId!==null&&!seen.has(parentId)){seen.add(parentId);const parent=await composition.runs.read(parentId);const path=closureReceiptPath(parentId);if(await composition.filesystem.exists(path)){const receipt=JSON.parse(await composition.filesystem.readText(path));if(receipt.schema_version===1&&receipt.run_id===parentId&&receipt.task_id===parent.run.task_id&&receipt.execution_id===parent.run.execution_id&&receipt.state==="pending"&&["completed","failed","cancelled"].includes(receipt.terminal_status))await reconcileOrchestratorStop(parent,composition,lifecycle,receipt.terminal_status)}parentId=parent.run.parent_run_id}}async function reconcileOrchestratorStop(current,composition,lifecycle,terminalStatus4="completed"){return composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);const completed=await completedStopSnapshot(fresh,composition);if(completed!==null){const path=closureReceiptPath(fresh.run.run_id);const content=`${JSON.stringify({schema_version:1,run_id:fresh.run.run_id,task_id:fresh.run.task_id,execution_id:fresh.run.execution_id,terminal_status:"completed",state:"reconciled"})}
@@ -3638,8 +3638,8 @@ ${turnId}`).replace("native-","intent-")}function claimPath(taskId,reservationId
3638
3638
  ${attempt.run.run_id}`).digest("hex")}});for(const delegation of delegations){const agent=catalog.agents.find(item=>item.id===delegation.agent_id);assertChildRunMayStart(delegation.parent_run_id===parent.run.run_id?parent:await composition.runs.read(delegation.parent_run_id),delegation.purpose,delegation.agent_id,runs,agent?.execution_eligibility);if(!await composition.filesystem.exists(delegation.context_ref)){throw new UsageError(`Context file does not exist for ${delegation.task_id}`)}}const recoveryDelegations=delegations.filter(delegation=>delegation.recovery!==void 0);if(recoveryDelegations.length>0&&!parsed.flags.has("reserve-causal")){const safe=delegations.filter(delegation=>delegation.recovery===void 0);return{...batch,delegations:safe,recovery_reservation_required:recoveryDelegations.map(item=>item.task_id),mode:"host-native",provider_started:false,continuation:nativeContinuation(tasks,safe.length,false),next:"Reserve the exact recovery dispatch with --reserve-causal before spawning a provider."}}if(parsed.flags.has("reserve-causal")&&recoveryDelegations.length!==1)throw new UsageError("Causal reservation requires exactly one recovery delegation");let reserved=delegations;if(recoveryDelegations.length===1){if(!parsed.options["codex-hook-id"]||!parsed.options["codex-hook-thread"]||!argv.includes(`--codex-hook-id=${parsed.options["codex-hook-id"]}`)||!argv.includes(`--codex-hook-thread=${parsed.options["codex-hook-thread"]}`))throw new UsageError("Causal reservation requires a one-use observed hook receipt");const observed=await resolveRunClientInvocation(composition.filesystem,"codex",{argv});const ancestry=[];let ancestor=parent;while(ancestor.run.parent_run_id!==null){ancestry.push(ancestor.run.run_id);if(ancestry.length>8)throw new UsageError("Causal parent ancestry is too deep");ancestor=await composition.runs.read(ancestor.run.parent_run_id)}if(observed.clientThreadId!==ancestor.run.client_thread_id||observed.clientTurnId!==parent.run.client_turn_id||!observed.transcriptPath||observed.observedModel!==parent.run.model||observed.observedReasoningEffort!==parent.run.reasoning_effort)throw new UsageError("Causal reservation requires the exact native parent turn");const delegation=recoveryDelegations[0];const ledger=ledgers[delegation.task_id];const failed=ledger?.entries.findLast(entry2=>entry2.kind==="attempt"&&entry2.status==="failed");const candidate=await currentCommitSha(composition.filesystem.root);if(!ledger||!failed||!candidate)throw new UsageError("Causal reservation requires an observed failure and candidate");const contextHash=createHash62("sha256").update(await composition.filesystem.readText(delegation.context_ref)).digest("hex");assertScopedProductClean(composition.filesystem.root,tasks.find(task=>task.id===delegation.task_id).write_scopes);const productTree=scopedProductTreeHash(composition.filesystem.root,tasks.find(task=>task.id===delegation.task_id).write_scopes);const blueprint=plan.blueprints.tasks.find(task=>task.id===delegation.task_id);const node=plan.dag.nodes.find(item=>item.task_id===delegation.task_id);const reservationId=`CAUSAL-${createHash62("sha256").update(JSON.stringify({task_id:delegation.task_id,stage:delegation.purpose,product_tree:productTree,policy:plan.policy,acceptance_contract:plan.acceptance_contract??null,blueprint,node,context_hash:contextHash,failure:{id:failed.id,result:failed.result,context:failed.recovery_context},action:delegation.recovery?.plan})).digest("hex")}`;await composition.runs.withUsageAttributionLock(async()=>{const freshParent=await composition.runs.read(parent.run.run_id);const freshTask=(await composition.tasks.read(delegation.task_id)).task;const freshExecution=(await composition.executions.read(id)).execution;assertScopedProductClean(composition.filesystem.root,freshTask.write_scopes);if(freshParent.status!=="running"||freshParent.run.client_turn_id!==parent.run.client_turn_id||freshTask.status!=="executing"||freshExecution.plan_hash!==plan.hash||await currentCommitSha(composition.filesystem.root)!==candidate||scopedProductTreeHash(composition.filesystem.root,freshTask.write_scopes)!==productTree||createHash62("sha256").update(await composition.filesystem.readText(delegation.context_ref)).digest("hex")!==contextHash)throw new UsageError("Causal dispatch inputs changed before reservation");await ledgerStore.update(delegation.task_id,ledger.preset,ledger.legacy_attempts,current=>{if(JSON.stringify(current)!==JSON.stringify(ledger))throw new UsageError("Recovery ledger changed before causal reservation");return reserveRecovery(current,reservationId,"attempt")});await bindCausalDispatch(delegation.task_id,reservationId,parent.run.run_id,productTree,composition)});reserved=delegations.map(item=>item===delegation?{...item,idempotency_key:reservationId,recovery_reservation_id:reservationId}:item)}return{...batch,delegations:reserved,mode:"host-native",provider_started:false,continuation:nativeContinuation(tasks,reserved.length,false),next:nativeContinuation(tasks,reserved.length,false).instruction}}var init_command=__esm({"src/host-native-delegation/command.ts"(){"use strict";init_src();init_src6();init_src7();init_cli_arguments();init_lifecycle_assurance_v2();init_prepared_plan_v22();init_run_agent_identity();init_run_client_invocation();init_run_finalization_barrier();init_task_scope_amendment();init_causal_recovery();init_command_handler();init_continuation();init_host_native_delegation();init_product_candidate();init_recovery_evidence();init_task_attempt()}});async function runExecutionV2Command(action,parsed,composition,lifecycle,runAutonomous){if(action==="list"){const executions=(await composition.executions.list()).filter(execution=>(parsed.options.prd===void 0||execution.origin.type==="prd"&&execution.origin.prd_id===parsed.options.prd)&&(parsed.options.spec===void 0||execution.origin.type==="spec"&&execution.origin.spec_id===parsed.options.spec)&&(parsed.options.task===void 0||execution.dag.nodes.some(node=>node.task_id===parsed.options.task)));return listLifecyclePage(executions,parsed).map(execution=>({execution,artifact_path:composition.executions.path(execution.id)}))}const id=requiredEntityId(parsed,2,"Execution id");if(action==="show"){return{...await composition.executions.read(id),artifact_path:composition.executions.path(id)}}if(action==="link"){requireOptions(parsed.options,["parent"]);const execution=await composition.executions.linkChildExecution(id,parsed.options.parent);return{execution,artifact_path:composition.executions.path(id)}}if(action==="run")return runAutonomous(id,parsed);if(action==="native-next")return runNativeDelegationCommand(id,parsed,composition);if(action==="verify"){const execution=await lifecycle.verifyExecution(id);return{execution,artifact_path:composition.executions.path(id)}}if(action==="complete"){throw new UsageError("Execution terminal status is applied only by Gui through run finish")}if(["block","fail","cancel"].includes(action??""))throw new UsageError("Execution terminal status is applied only by Gui through run finish");if(["start","resume","pause"].includes(action??"")){const statuses={start:"running",resume:"running",pause:"paused"};const execution=await composition.executions.transition(id,statuses[action],null);return{execution,artifact_path:composition.executions.path(id)}}throw new UsageError(`Unknown V2 Execution action: ${action??""}`)}var init_execution_commands_v2=__esm({"src/execution-commands-v2.ts"(){"use strict";init_cli_arguments();init_command()}});import{createHash as createHash63}from"node:crypto";function narrativeJournalPath(review){const fingerprint=digest9(JSON.stringify(review.changes.map(({id,before_sha256,after_sha256})=>({id,before_sha256,after_sha256}))));return`${journalRoot}/${review.task_id}/${review.run_id}/${fingerprint}.json`}async function readNarrativeJournal(filesystem,review,scopes,expectedPath){const path=narrativeJournalPath(review);assertJournalScope(path,scopes);if(!await filesystem.exists(path))return null;const source=await filesystem.readText(path);if(Buffer.byteLength(source)>maxJournalBytes)throw new UsageError(`Narrative recovery journal exceeds 16 MiB: ${path}`);let journal;try{journal=JSON.parse(source)}catch{throw new UsageError(`Narrative recovery journal is invalid JSON: ${path}`)}if(journal?.schema_version!==1||journal.purpose!=="change_narrative_recovery"||journal.task_id!==review.task_id||journal.run_id!==review.run_id||!Array.isArray(journal.entries)||journal.entries.length!==review.changes.length)throw new UsageError(`Narrative recovery journal belongs to another attempt: ${path}`);for(const[index,entry2]of journal.entries.entries()){const expected=review.changes[index];if(!entry2||!expected||entry2.id!==expected.id||entry2.path!==expectedPath(entry2.id)||!scopes.some(scope=>workspaceScopeMatches(scope,entry2.path))||entry2.before_sha256!==expected.before_sha256||entry2.after_sha256!==expected.after_sha256||typeof entry2.source!=="string"||typeof entry2.target!=="string"||digest9(entry2.source)!==entry2.before_sha256||digest9(entry2.target)!==entry2.after_sha256)throw new UsageError(`Narrative recovery journal failed integrity or scope check: ${path}`);const originalMetadata=/^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(entry2.source)?.[0];const targetMetadata=/^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(entry2.target)?.[0];if(!originalMetadata||originalMetadata!==targetMetadata)throw new UsageError(`Narrative recovery journal cannot change lifecycle metadata: ${entry2.id}`);const metadata3=parseMarkdown(entry2.source,changeV2Schema).metadata;const generated=await refreshChangeNarrative(filesystem,entry2.path,metadata3,entry2.source.slice(originalMetadata.length),{preserveManual:true});if(metadata3.id!==entry2.id||`${originalMetadata}${generated}`!==entry2.target)throw new UsageError(`Narrative recovery journal differs from generated narrative transformation: ${entry2.id}`)}return{path,entries:journal.entries}}async function applyNarrativeWithRecovery(filesystem,review,entries,scopes,expectedPath){const path=narrativeJournalPath(review);assertJournalScope(path,scopes);let existing=await readNarrativeJournal(filesystem,review,scopes,expectedPath);if(!existing){for(const entry2 of entries){if(entry2.path!==expectedPath(entry2.id)||!scopes.some(scope=>workspaceScopeMatches(scope,entry2.path)))throw new UsageError(`Narrative recovery target outside Task scope: ${entry2.id}`);if(digest9(await filesystem.readText(entry2.path))!==entry2.before_sha256)throw new UsageError(`Change changed before journal creation: ${entry2.id}`)}const journal={schema_version:1,purpose:"change_narrative_recovery",task_id:review.task_id,run_id:review.run_id,entries};const serialized=`${JSON.stringify(journal)}
3639
3639
  `;if(Buffer.byteLength(serialized)>maxJournalBytes)throw new UsageError("Narrative recovery journal would exceed 16 MiB");try{await filesystem.writeTextAtomicExclusive(path,serialized)}catch(error51){existing=await readNarrativeJournal(filesystem,review,scopes,expectedPath);if(!existing)throw error51}}const effective=existing?.entries??entries;const states=await Promise.all(effective.map(async entry2=>{const current=digest9(await filesystem.readText(entry2.path));if(current!==entry2.before_sha256&&current!==entry2.after_sha256)throw new UsageError(`Change diverged from recovery journal: ${entry2.id}; journal ${path}`);return current}));const attempted=[];try{for(const[index,entry2]of effective.entries()){if(states[index]===entry2.after_sha256)continue;if(digest9(await filesystem.readText(entry2.path))!==entry2.before_sha256)throw new UsageError(`Change changed during narrative apply: ${entry2.id}`);attempted.push(entry2);await filesystem.writeTextAtomic(entry2.path,entry2.target);if(digest9(await filesystem.readText(entry2.path))!==entry2.after_sha256)throw new Error(`Change repair hash verification failed: ${entry2.id}`)}}catch(error51){const restored=[];const remaining=[];for(const entry2 of attempted.reverse()){try{const current=digest9(await filesystem.readText(entry2.path));if(current===entry2.before_sha256)continue;if(current!==entry2.after_sha256){remaining.push(`${entry2.id}: content diverged; preserved`);continue}await filesystem.writeTextAtomic(entry2.path,entry2.source);if(digest9(await filesystem.readText(entry2.path))!==entry2.before_sha256)throw new Error("restore hash mismatch");restored.push(entry2.id)}catch(rollbackError){remaining.push(`${entry2.id}: ${String(rollbackError)}`)}}throw new Error(`Narrative apply failed: ${String(error51)}; journal ${path}; restored=[${restored.join(", ")}]; unresolved=[${remaining.join(", ")}]; previously_applied=[${effective.filter((entry2,i)=>states[i]===entry2.after_sha256).map(entry2=>entry2.id).join(", ")}]`)}return{journal_path:path,replayed:existing!==null,applied_count:attempted.length}}function assertJournalScope(path,scopes){if(!scopes.some(scope=>workspaceScopeMatches(scope,path)))throw new UsageError(`Narrative recovery journal outside Task write scope: ${path}`)}var digest9,journalRoot,maxJournalBytes;var init_change_narrative_recovery=__esm({"src/change-narrative-recovery.ts"(){"use strict";init_src();init_src6();init_cli_arguments();init_lifecycle_gate_helpers();digest9=value=>createHash63("sha256").update(value).digest("hex");journalRoot=".local/change-narrative-recovery";maxJournalBytes=16*1024*1024}});import{createHash as createHash64}from"node:crypto";import{posix as posix10}from"node:path";async function runChangeNarrativeCommand(parsed,filesystem,composition){if(parsed.positionals[2]!=="refresh")throw new UsageError("Usage: change narrative refresh --id CHG-ID --task TASK --run RUN [--apply]");const apply=parsed.flags.has("apply");const taskId=parsed.options.task;const runId=parsed.options.run;if(!taskId||!runId)throw new UsageError("Change narrative refresh requires --task and --run");if(!/^TASK-[A-Z0-9-]+$/.test(taskId)||!/^RUN-[A-Z0-9-]+$/.test(runId))throw new UsageError("Change narrative refresh requires canonical Task and Run IDs");const{task}=await composition.tasks.read(taskId);const runFold=await composition.runs.read(runId);if(!["executing","verifying"].includes(task.status)||runFold.finished!==null||runFold.run.task_id!==taskId||runFold.run.change_id!==task.change_id||runFold.run.execution_id!==task.plan_ref?.execution_id){throw new UsageError("Change narrative refresh requires the exact active Task Run")}const manifest=parsed.options.manifest===void 0?null:await readReviewedManifest(filesystem,parsed.options.manifest,taskId,runId);if(manifest!==null&&(parsed.options.id||parsed.options.ids))throw new UsageError("Choose --manifest or explicit --id/--ids, not both");const ids2=manifest?.changes.map(entry2=>entry2.id)??selectedIds(parsed);if(apply&&manifest===null&&ids2.length!==1)throw new UsageError("Applying multiple Changes requires an exact reviewed --manifest");if(apply&&manifest!==null){const prior=await readNarrativeJournal(filesystem,manifest,task.write_scopes,id=>composition.changes.path(id));if(prior){const recovery2=await applyNarrativeWithRecovery(filesystem,manifest,prior.entries,task.write_scopes,id=>composition.changes.path(id));return{...manifest,mode:"applied",applied_at:new Date().toISOString(),changed_count:manifest.changes.filter(entry2=>entry2.before_sha256!==entry2.after_sha256).length,...recovery2}}}const candidates=[];for(const id of ids2){const path=composition.changes.path(id);if(!task.write_scopes.some(scope=>workspaceScopeMatches(scope,path)))throw new UsageError(`Change ${id} is outside Task ${taskId} write scopes: ${path}`);const source=await filesystem.readText(path);const prefix=/^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(source)?.[0];if(!prefix)throw new UsageError(`Change ${id} lacks a valid YAML frontmatter boundary`);const metadata3=parseMarkdown(source,changeV2Schema).metadata;if(metadata3.id!==id)throw new UsageError(`Change path and YAML ID disagree: ${id}`);const body=source.slice(prefix.length);const refreshed=await refreshChangeNarrative(filesystem,path,metadata3,body,{preserveManual:true});const target=`${prefix}${refreshed}`;candidates.push({id,path,status:metadata3.status,finished_at:metadata3.finished_at,before_sha256:digest10(source),after_sha256:digest10(target),changed:source!==target,source,target})}if(manifest!==null)for(const[index,expected]of manifest.changes.entries()){const candidate=candidates[index];if(candidate?.id!==expected.id||candidate.before_sha256!==expected.before_sha256||candidate.after_sha256!==expected.after_sha256)throw new UsageError(`Reviewed manifest differs from current Change ${expected.id}`)}const receipt={schema_version:1,purpose:"change_narrative_refresh",task_id:taskId,run_id:runId,changes:candidates.map(({id,before_sha256,after_sha256,path,status,finished_at,changed})=>({id,before_sha256,after_sha256,path,status,finished_at,changed})),mode:apply?"applied":"preview",changed_count:candidates.filter(candidate=>candidate.changed).length,applied_at:apply?new Date().toISOString():null};if(!apply)return receipt;if(receipt.changed_count===0)return receipt;const review={task_id:taskId,run_id:runId,changes:candidates.map(({id,before_sha256,after_sha256})=>({id,before_sha256,after_sha256}))};const recovery=await applyNarrativeWithRecovery(filesystem,review,candidates,task.write_scopes,id=>composition.changes.path(id));return{...receipt,...recovery}}function selectedIds(parsed){if(parsed.options.id&&parsed.options.ids)throw new UsageError("Choose --id or --ids");const ids2=parsed.options.id?[parsed.options.id]:(parsed.options.ids??"").split(",").filter(Boolean);if(ids2.length===0||ids2.length>2e3||ids2.some(id=>!idPattern.test(id))||new Set(ids2).size!==ids2.length)throw new UsageError("Select 1-2000 distinct canonical Change IDs with --id or --ids");return ids2}async function readReviewedManifest(filesystem,path,taskId,runId){const normalized=path.replaceAll("\\","/");if(!normalized.startsWith(".local/")||posix10.normalize(normalized)!==normalized||normalized.split("/").includes(".."))throw new UsageError("Reviewed manifest must be a workspace-local .local/ path");const source=await filesystem.readText(path);if(source.length>4*1024*1024)throw new UsageError("Reviewed manifest exceeds 4 MiB");let raw;try{raw=JSON.parse(source)}catch{throw new UsageError("Reviewed manifest is not JSON")}const value=raw;if(value?.schema_version!==1||value.purpose!=="change_narrative_refresh"||value.task_id!==taskId||value.run_id!==runId||!Array.isArray(value.changes)||value.changes.length===0||value.changes.length>2e3||value.changes.some(entry2=>!idPattern.test(entry2?.id)||!shaPattern.test(entry2?.before_sha256)||!shaPattern.test(entry2?.after_sha256))||new Set(value.changes.map(entry2=>entry2.id)).size!==value.changes.length)throw new UsageError("Reviewed manifest is invalid or belongs to another Task Run");return value}var digest10,idPattern,shaPattern;var init_change_narrative_command=__esm({"src/change-narrative-command.ts"(){"use strict";init_src();init_src6();init_change_narrative_recovery();init_cli_arguments();init_lifecycle_gate_helpers();digest10=value=>createHash64("sha256").update(value).digest("hex");idPattern=/^CHG-[A-Z0-9-]+$/;shaPattern=/^[a-f0-9]{64}$/}});async function runChangeV2Command(action,parsed,composition,lifecycle){if(action==="narrative")return runChangeNarrativeCommand(parsed,composition.filesystem,composition);if(action==="list"){const changes=(await composition.changes.list()).filter(change=>(parsed.options.prd===void 0||change.source.type==="prd"&&change.source.prd_id===parsed.options.prd)&&(parsed.options.spec===void 0||change.source.type==="spec"&&change.source.spec_id===parsed.options.spec||change.source.type==="prd"&&change.source.spec_id===parsed.options.spec));return listLifecyclePage(changes,parsed).map(change=>({change,artifact_path:composition.changes.path(change.id)}))}const id=requiredEntityId(parsed,2,"Change id");if(action==="show"){return{...await composition.changes.read(id),artifact_path:composition.changes.path(id)}}if(action==="verify"){const change=await lifecycle.verifyChange(id);return{change,artifact_path:composition.changes.path(id)}}if(action==="complete"){throw new UsageError("Change terminal status is applied only by Gui through run finish")}if(["block","fail","cancel"].includes(action??""))throw new UsageError("Change terminal status is applied only by Gui through run finish");if(["start","resume"].includes(action??"")){const statuses={start:"executing",resume:"executing"};const change=await composition.changes.transition(id,statuses[action],null);return{change,artifact_path:composition.changes.path(id)}}throw new UsageError(`Unknown V2 Change action: ${action??""}`)}async function runDecisionV2Command(action,parsed,filesystem,composition){const scope=decisionV2ScopeOption(parsed);if(action==="list"){const decisions=await composition.decisions.list(scope);return decisions.map(decision=>({decision,artifact_path:composition.decisions.path(decision.scope_type,decision.scope_id,decision.id)}))}if(action==="show"){if(scope===void 0)throw new UsageError("decision show requires --change or --execution");const id=requiredEntityId(parsed,2,"Decision id");return{decision:await composition.decisions.read(scope.type,scope.id,id),artifact_path:composition.decisions.path(scope.type,scope.id,id)}}if(action==="record"){if(scope===void 0)throw new UsageError("decision record requires --change or --execution");if(!await filesystem.exists(composition.layout.activePath(scope.type,scope.id))){throw new UsageError(`Decision owner does not resolve: ${scope.type} ${scope.id}`)}requireOptions(parsed.options,["origin","title","short-name","category","context","decision","reason"]);const origin=originOption(parsed.options.origin);const decision=await composition.decisions.record({...parsed.options.id===void 0?{}:{id:parsed.options.id},shortName:parsed.options["short-name"],title:parsed.options.title,scopeType:scope.type,scopeId:scope.id,origin,category:categoryV2Option(parsed.options.category),context:parsed.options.context,decision:parsed.options.decision,reason:parsed.options.reason,alternatives:csvOption(parsed.options.alternatives),consequences:csvOption(parsed.options.consequences),reversible:parsed.flags.has("reversible"),rollback:parsed.options.rollback??"Not applicable.",confidence:origin==="agent"?confidenceOption(parsed.options.confidence):null,confirmed:origin==="human"&&parsed.flags.has("confirmed"),timeZone:composition.layout.project.timezone});return{decision,artifact_path:composition.decisions.path(scope.type,scope.id,decision.id)}}throw new UsageError(`Unknown V2 Decision action: ${action??""}`)}var init_governance_commands_v2=__esm({"src/governance-commands-v2.ts"(){"use strict";init_change_narrative_command();init_cli_arguments()}});function normalizeSubagentSessionOption(parsed){const alias=parsed.options["session-id"];const session=parsed.options.session;if(alias!==void 0&&session!==void 0&&alias!==session){throw new UsageError("--session and --session-id must match when both are provided")}if(session!==void 0||alias===void 0)return parsed;return{...parsed,options:{...parsed.options,session:alias}}}function baseValues(parsed){return["session","turn","agent-id","agent-type"].map(name=>{const value=parsed.options[name]?.trim();if(value===void 0||value.length===0||value.length>200){throw new UsageError(`--${name} must contain 1 to 200 characters`)}return value})}function optionValue(parsed,name){const value=parsed.options[name]?.trim();if(value===void 0||value.length===0||value.length>200){throw new UsageError(`--${name} must contain 1 to 200 characters`)}return value}function terminalStatus(value){if(value==="completed"||value==="failed"||value==="cancelled")return value;throw new UsageError("--status must be completed, failed, or cancelled")}function startValues(parsed){const model=parsed.options.model?.trim();if(model===void 0||model.length===0||model.length>200){throw new UsageError("--model must contain 1 to 200 characters")}return[...baseValues(parsed),model]}function slug(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"worker"}var init_capture_options=__esm({"src/host-native-delegation/capture-options.ts"(){"use strict";init_cli_arguments()}});function captureResult(fold,reused){return{captured:true,reused,run:fold.run,status:fold.status}}var init_capture_result=__esm({"src/host-native-delegation/capture-result.ts"(){"use strict"}});import{createHash as createHash65}from"node:crypto";async function matchesLegacyRootReplay(parsed,existing,filesystem){const{run}=existing;const agentId2=parsed.options["agent-id"];if(parsed.options["agent-type"]!=="zaip-agent-orchestrator"||!agentId2||run.parent_run_id!==null||run.agent!=="agent-orchestrator"||run.client_thread_id!==parsed.options.session||run.client_turn_id!==parsed.options.turn||run.model!==parsed.options.model||parsed.options["reasoning-effort"]!==void 0&&parsed.options["reasoning-effort"]!==run.reasoning_effort||parsed.options.task!==void 0&&parsed.options.task!==run.task_id||["parent-agent-id","parent-run-id","native-session","relay","recovery-reservation"].some(key=>parsed.options[key]!==void 0))return false;try{const binding=JSON.parse(await filesystem.readText(pathFor(agentId2,run.run_id)));return binding.schema_version===1&&binding.agent_id===agentId2&&binding.turn_id===run.client_turn_id&&binding.root_session===run.client_thread_id&&binding.run_id===run.run_id}catch{return false}}async function persistOrchestratorBinding(parsed,result2,filesystem){if(parsed.options["agent-type"]!=="zaip-agent-orchestrator")return;const run=result2.run;if(!run||run.parent_run_id!==null||run.agent!=="agent-orchestrator")return;const agentId2=parsed.options["agent-id"];if(!agentId2)throw new UsageError("Observed orchestrator binding requires its host agent identity");const binding={schema_version:1,agent_id:agentId2,turn_id:parsed.options.turn,root_session:run.client_thread_id,run_id:run.run_id};const path=pathFor(agentId2,run.run_id);if(await filesystem.exists(path)){if(JSON.stringify(JSON.parse(await filesystem.readText(path)))!==JSON.stringify(binding))throw new UsageError("Observed orchestrator binding conflicts with its original invocation");return}try{await filesystem.writeTextExclusive(path,`${JSON.stringify(binding)}
3640
3640
  `)}catch(error51){if(error51.code!=="EEXIST"||JSON.stringify(JSON.parse(await filesystem.readText(path)))!==JSON.stringify(binding))throw error51}}async function resolveOrchestratorBinding(parsed,composition,filesystem){const parentId=parsed.options["parent-agent-id"];if(!parentId)return parsed;const explicitRun=parsed.options["parent-run-id"];const paths2=explicitRun===void 0?await filesystem.listFiles(directoryFor(parentId),".json"):await filesystem.exists(pathFor(parentId,explicitRun))?[pathFor(parentId,explicitRun)]:[];if(paths2.length===0){if(explicitRun!==void 0&&(await filesystem.listFiles(directoryFor(parentId),".json")).length>0)throw new UsageError("Observed orchestrator binding has incompatible parent identity");return parsed}if(paths2.length>128)throw new UsageError("Orchestrator binding history requires an exact --parent-run-id");const bindings=await Promise.all(paths2.map(async path=>JSON.parse(await filesystem.readText(path))));const candidates=[];for(const binding2 of bindings){const parent2=await composition.runs.read(binding2.run_id);if(explicitRun!==void 0||parent2.status==="running")candidates.push(binding2)}if(candidates.length!==1)throw new UsageError("Orchestrator parent is ambiguous or inactive; pass the exact --parent-run-id");const binding=candidates[0];const parent=await composition.runs.read(binding.run_id);if(binding.schema_version!==1||binding.agent_id!==parentId||parent.run.parent_run_id!==null||parent.run.agent!=="agent-orchestrator"||parent.run.client_thread_id!==binding.root_session||parsed.options["parent-run-id"]!==void 0&&parsed.options["parent-run-id"]!==binding.run_id)throw new UsageError("Observed orchestrator binding has incompatible parent identity");return{...parsed,options:{...parsed.options,"parent-agent-id":binding.root_session,"parent-run-id":binding.run_id}}}var directoryFor,pathFor;var init_orchestrator_binding=__esm({"src/host-native-delegation/orchestrator-binding.ts"(){"use strict";init_cli_arguments();directoryFor=id=>`.local/host-native-orchestrators/${createHash65("sha256").update(id).digest("hex")}`;pathFor=(id,runId)=>`${directoryFor(id)}/${createHash65("sha256").update(runId).digest("hex")}.json`}});function selectParent(runs,sessionId,turnId,parentAgentId,parentRunId,allowObservedHistoricalInvocation=false){const explicitParent=parentAgentId?.trim();const explicitRun=parentRunId?.trim();if(explicitRun!==void 0&&explicitRun.length>0){if(explicitParent===void 0||explicitParent.length===0){throw new UsageError("--parent-run-id requires --parent-agent-id")}return runs.find(fold=>(fold.status==="running"||allowObservedHistoricalInvocation)&&fold.run.run_id===explicitRun&&fold.run.client_thread_id===explicitParent)}if(explicitParent!==void 0&&explicitParent.length>0){const candidates=runs.filter(fold=>fold.status==="running"&&fold.run.client_thread_id===explicitParent);if(candidates.length>1){throw new UsageError(`Multiple active root Runs share ${explicitParent}; pass --parent-run-id for exact attribution`)}return candidates[0]}return runs.filter(fold=>fold.status==="running"&&fold.run.parent_run_id===null&&fold.run.client_thread_id===sessionId&&fold.run.client_turn_id===turnId).sort((left,right)=>right.run.occurred_at.localeCompare(left.run.occurred_at))[0]}function assertCapturedSubagentIdentity(child,runs,sessionId,rawParentAgentId,requireRootSession=false){const parent=child.run.parent_run_id===null?void 0:runs.find(candidate=>candidate.run.run_id===child.run.parent_run_id);const declaredParent=rawParentAgentId?.trim();if(parent===void 0||declaredParent!==void 0&&declaredParent.length>0&&parent.run.client_thread_id!==declaredParent){throw new UsageError(`Sub-Run identity conflicts with existing Run ${child.run.run_id}`)}if(declaredParent!==void 0&&declaredParent.length>0&&!requireRootSession)return;let root=parent;while(root.run.parent_run_id!==null){const next=runs.find(candidate=>candidate.run.run_id===root.run.parent_run_id);if(next===void 0){throw new UsageError(`Sub-Run identity conflicts with existing Run ${child.run.run_id}`)}root=next}if(root.run.client_thread_id!==sessionId){throw new UsageError(`Sub-Run identity conflicts with existing Run ${child.run.run_id}`)}}var init_parent_selection=__esm({"src/host-native-delegation/parent-selection.ts"(){"use strict";init_cli_arguments()}});async function nativeTaskAttribution(parent,taskId,repositories,relayId){const source=parent.run;if(taskId===void 0)return{entrypoint:source.entrypoint,executionId:source.execution_id,taskId:source.task_id,changeId:source.change_id,specId:source.spec_id,prdId:source.prd_id};if(source.task_id!==null&&source.task_id!==taskId&&repositories.decisions&&repositories.runs){if(!relayId)throw new UsageError("Cross-Execution capture requires an exact relay intent");const relay=await authenticatedRelayForCapture(repositories,parent,taskId,relayId);if(relay!==null){const[{task:task2},{execution:execution2},macro]=await Promise.all([repositories.tasks.read(taskId),repositories.executions.read(relay.target_execution_id),repositories.runs.read(relay.macro_run_id)]);const activeOwners=(await repositories.runs.list()).filter(run=>run.status==="running"&&run.run.task_id===taskId);if(parent.status!=="running"||source.run_id!==relay.actor_run_id||source.parent_run_id!==relay.macro_run_id||source.run_role!=="subagent"||source.run_purpose!=="orchestration"||source.agent!=="agent-orchestrator"||macro.status!=="running"||macro.run.run_role!=="orchestrator"||macro.run.parent_run_id!==null||macro.run.spec_id!==source.spec_id||macro.run.execution_id!==source.execution_id||task2.status!=="executing"||task2.change_id!==relay.target_change_id||execution2.origin.type!=="spec"||execution2.origin.spec_id!==relay.target_spec_id||!execution2.dag.nodes.some(node2=>node2.task_id===task2.id&&node2.change_id===task2.change_id)||activeOwners.length>0)throw new UsageError("Historical relay capture has another owner or ancestry");return{entrypoint:"task",executionId:execution2.id,taskId,changeId:task2.change_id,specId:relay.target_spec_id,prdId:null}}}if(source.execution_id===null||source.execution_kind!=="delivery"||source.task_id!==null&&source.task_id!==taskId){throw new UsageError("Native Task capture requires its delivery parent; cannot retarget a Task Run")}const{execution}=await repositories.executions.read(source.execution_id);const{task}=await repositories.tasks.read(taskId);const node=execution.dag.nodes.find(candidate=>candidate.task_id===taskId);if(node===void 0||node.change_id!==task.change_id||execution.plan_hash===null){throw new UsageError(`Execution ${execution.id} does not own prepared Task ${taskId}`)}for(const dependency of node.depends_on){if((await repositories.tasks.read(dependency)).task.status!=="completed"){throw new UsageError(`Native Task ${taskId} has unfinished dependency ${dependency}`)}}const{change}=await repositories.changes.read(task.change_id);const origin=change.source;const specId=origin.type==="spec"?origin.spec_id:origin.type==="prd"?origin.spec_id:null;const prdId=origin.type==="prd"?origin.prd_id:source.prd_id;if(source.spec_id!==null&&source.spec_id!==specId||source.prd_id!==null&&source.prd_id!==prdId){throw new UsageError(`Native Task ${taskId} does not belong to the parent's macro scope`)}return{entrypoint:"task",executionId:execution.id,taskId,changeId:task.change_id,specId,prdId}}function assertNativeTaskReplay(run,taskId){if(taskId!==void 0&&run.run.task_id!==taskId){throw new UsageError(`Native invocation is already attributed to Task ${run.run.task_id??"none"}; cannot capture ${taskId}`)}return run}var init_task_attribution=__esm({"src/host-native-delegation/task-attribution.ts"(){"use strict";init_cli_arguments();init_post_publication_relay()}});function createCaptureReplay(parsed,composition,filesystem){const[sessionId,turnId,agentId2]=baseValues(parsed);return async(existing,runs)=>{assertNativeTaskReplay(existing,parsed.options.task);await assertCausalReplay(existing,parsed.options["recovery-reservation"],composition);if(await matchesLegacyRootReplay(parsed,existing,filesystem))return{...captureResult(existing,true),bound_to_root:true};const parent=runs.find(fold=>fold.run.run_id===existing.run.parent_run_id);const parental=isParentalRelayShape(existing);if(parental){if(!parsed.options.relay||!parsed.options["native-session"]||parent===void 0)throw new UsageError("Parental replay requires its exact relay and native session");const proof=await authenticatedParentalRelay(existing,composition,false,parsed.options["native-session"]);if(proof?.intentId!==parsed.options.relay)throw new UsageError("Parental replay differs from its issued relay")}const historical=!parental&&parent!==void 0&&parent.run.task_id!==null&&parent.run.task_id!==existing.run.task_id;const historicalDescendant=!historical&&parent!==void 0&&parent.run.task_id===existing.run.task_id&&(await historicalRelayEvidenceIds(parent,composition)).size>0;if(historical){if(!parsed.options.task)throw new UsageError("Historical native replay requires its exact Task");await assertRelayNativeCapture(composition,parent,parsed.options.task,parsed.options.relay,parsed.options["native-session"],agentId2,turnId,false)}else if(parsed.options.relay&&!parental){throw new UsageError("Relay intent requires exact historical Task capture")}if(historicalDescendant&&(parent===void 0||parsed.options["parent-run-id"]!==parent.run.run_id||parsed.options["parent-agent-id"]!==parent.run.client_thread_id))throw new UsageError("Historical descendant replay requires its exact bound parent");assertCapturedSubagentIdentity(existing,runs,sessionId,parsed.options["parent-agent-id"],!(historical||historicalDescendant||parental));return captureResult(existing,true)}}var init_capture_replay=__esm({"src/host-native-delegation/capture-replay.ts"(){"use strict";init_cli_arguments();init_post_publication_parental();init_post_publication_relay();init_capture_options();init_capture_result();init_causal_recovery();init_orchestrator_binding();init_parent_selection();init_task_attribution()}});function catalogTaskNameFromHostIdentity(value){if(value===null)return null;const leaf=value.split(/[\\/]/u).filter(Boolean).at(-1)?.trim()??"";if(leaf.length===0)return null;return leaf.replace(/\s+the\s+\d+(?:st|nd|rd|th)$/iu,"")}var init_catalog_task_name=__esm({"src/host-native-delegation/catalog-task-name.ts"(){"use strict"}});import{execFile as execFile21}from"node:child_process";import{promisify as promisify21}from"node:util";async function registeredGitWorktreeRoots(root){const output2=await execFileAsync11("git",["worktree","list","--porcelain"],{cwd:root,encoding:"utf8",windowsHide:true,timeout:15e3}).catch(()=>({stdout:""}));const roots2=output2.stdout.split(/\r?\n/u).filter(line=>line.startsWith("worktree ")).map(line=>line.slice("worktree ".length).trim()).filter(Boolean);return[...new Set([root,...roots2])]}var execFileAsync11;var init_registered_git_worktrees=__esm({"src/registered-git-worktrees.ts"(){"use strict";execFileAsync11=promisify21(execFile21)}});import{homedir as homedir5}from"node:os";import{join as join7}from"node:path";async function discoverRegisteredChildLifecycles(workspaceRoot,parentThreadId,options={}){const output2=[];for(const root of await registeredGitWorktreeRoots(workspaceRoot)){const observed=await listCodexInvocationLifecycles(root,{...options,parentThreadId});output2.push(...observed.map(item=>({observed:item,workspaceRoot:root})))}return output2}async function inspectLocalSubagent(root,filesystem,session,sessionsRoot=join7(homedir5(),".codex"),expectedTurn,authenticatedParental=false){if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(session))throw new UsageError("A native child session UUID is required");const delegatedTaskOrchestrator=root.run.parent_run_id!==null&&root.run.run_role==="subagent"&&root.run.run_purpose==="orchestration"&&root.run.entrypoint==="task"&&root.run.agent==="agent-orchestrator"&&typeof root.run.task_id==="string"&&typeof root.run.spec_id==="string"&&typeof root.run.execution_id==="string";const boundParentalOrchestrator=authenticatedParental&&isParentalRelayShape(root);const delegatedOrchestrator=delegatedTaskOrchestrator||boundParentalOrchestrator;if(root.run.parent_run_id!==null&&!delegatedOrchestrator||typeof root.run.client_thread_id!=="string"||!root.run.client_thread_id||typeof root.run.client_turn_id!=="string"||!root.run.client_turn_id)throw new UsageError("An exactly correlated parent Run is required");const sessions=new WorkspaceFileSystem(sessionsRoot);const paths2=(await sessions.listFiles("sessions",".jsonl")).filter(path=>/^sessions\/\d{4}\/\d{2}\/\d{2}\/[A-Za-z0-9._-]+\.jsonl$/u.test(path)&&path.includes(session));if(paths2.length===0||paths2.length>128)throw new UsageError("Exact native child transcript is unavailable or ambiguous");const options={sessionsRoot,sessionPaths:paths2,threadId:session,...delegatedOrchestrator?{}:{parentThreadId:root.run.client_thread_id}};const observed=(await listCodexInvocationLifecycles(filesystem.root,options)).filter(item=>(delegatedOrchestrator?typeof item.parentThreadId==="string"&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(item.parentThreadId)&&item.agentPath?.startsWith(`${root.run.client_thread_id}/`):item.parentThreadId===root.run.client_thread_id)&&item.startedAt!==null&&Date.parse(item.startedAt)>=Date.parse(root.run.occurred_at)&&(root.finished===null||Date.parse(item.startedAt)<=Date.parse(root.finished.occurred_at)));const eligible=expectedTurn===void 0?observed:observed.filter(item=>item.turnId===expectedTurn);const active=eligible.filter(item=>item.status==="active");const candidates=expectedTurn===void 0&&active.length===1?active:eligible;const child=candidates[0];if(candidates.length!==1||child===void 0)throw new UsageError("Exactly one child invocation of this root is required");let parentHostSessionId=null;if(delegatedOrchestrator){const parentSession=child.parentThreadId;if(parentSession===null)throw new UsageError("Native parent session is unavailable");const parentPaths=(await sessions.listFiles("sessions",".jsonl")).filter(path=>/^sessions\/\d{4}\/\d{2}\/\d{2}\/[A-Za-z0-9._-]+\.jsonl$/u.test(path)&&path.includes(parentSession));if(parentPaths.length===0||parentPaths.length>128)throw new UsageError("Exact native parent transcript is unavailable or ambiguous");const parents=await listCodexInvocationLifecycles(filesystem.root,{sessionsRoot,sessionPaths:parentPaths,threadId:parentSession});const matches=parents.filter(item=>item.agentPath===root.run.client_thread_id&&item.turnId===root.run.client_turn_id&&item.status==="active"&&typeof item.parentThreadId==="string"&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(item.parentThreadId));if(matches.length!==1)throw new UsageError("Native parent transcript does not match the delegated orchestrator Run");parentHostSessionId=matches[0].parentThreadId}const identity2=child.agentPath??child.agentNickname;const agent=(await loadAgentCatalog(filesystem)).agents.find(entry2=>entry2.codex_name===child.agentRole&&entry2.codex_task_name===catalogTaskNameFromHostIdentity(identity2));if(agent===void 0||identity2===null)throw new UsageError("Native child identity does not match the canonical catalog");const metadata3=await readCodexInvocationMetadata(sessions,child.sessionPath,child.turnId);if(metadata3===null||metadata3.model===null)throw new UsageError("Exact observed child metadata is unavailable");return{read_only:true,capture_ready:root.status==="running"&&child.status==="active",capture_readiness_reason:root.status!=="running"?"parent-run-terminal":child.status!=="active"?"native-child-terminal":"observed-parent-and-child-active",parent_run_id:root.run.run_id,parent_agent_id:root.run.client_thread_id,parent_host_session_id:parentHostSessionId,session,turn:child.turnId,agent_id:identity2,agent_type:child.agentRole,status:child.status,model:metadata3.model,reasoning_effort:metadata3.reasoningEffort}}var init_subagent_local_inspection=__esm({"src/subagent-local-inspection.ts"(){"use strict";init_src();init_src4();init_cli_arguments();init_catalog_task_name();init_post_publication_parental();init_registered_git_worktrees();init_run_agent_identity()}});function historicalNativeCaptureParentMatches(root,delegatedParent,observed){return root.status==="running"&&delegatedParent.status==="running"&&delegatedParent.run.parent_run_id===root.run.run_id&&observed.parent_run_id===delegatedParent.run.run_id&&observed.parent_agent_id===delegatedParent.run.client_thread_id&&observed.parent_host_session_id===root.run.client_thread_id}async function historicalNativeParentMatches(root,macro,filesystem,nativeSession,inspect=inspectLocalSubagent){if(!macro.run.client_turn_id||!macro.run.client_thread_id)return false;const observed=await inspect(root,filesystem,nativeSession,void 0,macro.run.client_turn_id).catch(()=>null);return observed?.status==="active"&&observed.session===nativeSession&&observed.turn===macro.run.client_turn_id&&observed.agent_id===macro.run.client_thread_id&&observed.parent_run_id===root.run.run_id&&observed.parent_agent_id===root.run.client_thread_id&&observed.model===macro.run.model&&observed.reasoning_effort===macro.run.reasoning_effort}var init_historical_native_ancestry=__esm({"src/host-native-delegation/historical-native-ancestry.ts"(){"use strict";init_subagent_local_inspection()}});function reconciliationAgentId(runs,parent,session,turn,agent,hostIdentity){const candidates=runs.filter(fold=>fold.run.parent_run_id===parent&&fold.run.client_turn_id===turn&&fold.run.agent===agent&&[session,hostIdentity].includes(fold.run.client_thread_id??""));const identities=new Set(candidates.map(fold=>fold.run.client_thread_id));if(identities.size>1)throw new Error("Ambiguous existing Sub-Run identities; preserve both records for explicit reconciliation");return identities.values().next().value??hostIdentity}var init_reconciliation_identity=__esm({"src/host-native-delegation/reconciliation-identity.ts"(){"use strict"}});import{createHash as createHash66}from"node:crypto";async function persistNativeToolBinding(parsed,result2,filesystem,composition,inspect=inspectLocalSubagent){const id=result2.run?.run_id;const session=parsed.options["native-session"]??parsed.options.session;if(!id)return"not_required";const child=await composition.runs.read(id);if(child.status!=="running"||child.run.run_role!=="subagent"||child.run.run_purpose!=="execution"||!child.run.execution_eligibility?.includes("delivery")||!child.run.parent_run_id||!child.run.task_id)return"not_required";if(!session||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(session))return parsed.options["native-session"]===void 0?"not_required":"unavailable";const parent=await composition.runs.read(child.run.parent_run_id);const macro=parent.run.parent_run_id===null?null:await composition.runs.read(parent.run.parent_run_id).catch(()=>null);const historicalRoot=macro?.run.parent_run_id===null||macro===null?null:await composition.runs.read(macro.run.parent_run_id).catch(()=>null);const ownTaskRoot=parent.run.parent_run_id===null&&parent.run.run_role==="orchestrator"&&parent.run.entrypoint==="task";const delegatedTaskOrchestrator=macro!==null&&parent.run.run_role==="subagent"&&parent.run.run_purpose==="orchestration"&&parent.run.entrypoint==="task"&&typeof parent.run.spec_id==="string"&&parent.run.spec_id===child.run.spec_id&&parent.run.change_id===child.run.change_id&&macro.status==="running"&&macro.run.agent==="agent-orchestrator"&&macro.run.run_role==="orchestrator"&&macro.run.parent_run_id===null&&macro.run.entrypoint==="spec"&&macro.run.task_id===null&&macro.run.spec_id===parent.run.spec_id&&macro.run.execution_id===parent.run.execution_id;const historicalRelayTaskOrchestrator=historicalRoot!==null&&macro!==null&&parent.run.run_role==="subagent"&&parent.run.run_purpose==="orchestration"&&parent.run.entrypoint==="task"&&macro.status==="running"&&macro.run.run_role==="subagent"&&macro.run.run_purpose==="orchestration"&&macro.run.agent==="agent-orchestrator"&&historicalRoot.status==="running"&&historicalRoot.run.run_role==="orchestrator"&&historicalRoot.run.parent_run_id===null&&macro.run.parent_run_id===historicalRoot.run.run_id&&parent.run.parent_run_id===macro.run.run_id&&parent.run.task_id===child.run.task_id&&parent.run.change_id===child.run.change_id&&parent.run.execution_id===child.run.execution_id&&parent.run.spec_id===child.run.spec_id&&"decisions"in composition&&"executions"in composition&&"changes"in composition&&"specs"in composition&&await Promise.resolve().then(()=>(init_post_publication_relay(),post_publication_relay_exports)).then(({historicalRelayEvidenceIds:historicalRelayEvidenceIds3})=>historicalRelayEvidenceIds3(parent,composition)).then(ids2=>ids2.size>0).catch(()=>false);if(parent.status!=="running"||!(ownTaskRoot||delegatedTaskOrchestrator||historicalRelayTaskOrchestrator)||typeof parent.run.client_thread_id!=="string"||!parent.run.client_thread_id||parent.run.agent!=="agent-orchestrator")return"unavailable";if(typeof child.run.client_turn_id!=="string"||!child.run.client_turn_id)return"unavailable";const observed=await inspect(parent,filesystem,session,void 0,child.run.client_turn_id).catch(()=>null);const observedMacroMatches=historicalRelayTaskOrchestrator&&historicalRoot!==null&&macro!==null&&observed?.parent_host_session_id?await historicalNativeParentMatches(historicalRoot,macro,filesystem,observed.parent_host_session_id,inspect):false;if(observed?.status!=="active"||observed.session!==session||observed.turn!==child.run.client_turn_id||![observed.session,observed.agent_id].includes(child.run.client_thread_id??"")||observed.agent_type!==child.run.agent_name||observed.parent_run_id!==parent.run.run_id||observed.parent_agent_id!==parent.run.client_thread_id||delegatedTaskOrchestrator&&observed.parent_host_session_id!==macro?.run.client_thread_id||historicalRelayTaskOrchestrator&&!observedMacroMatches||observed.model!==child.run.model||observed.reasoning_effort!==child.run.reasoning_effort||parent.run.task_id!==child.run.task_id||parent.run.spec_id!==child.run.spec_id||parent.run.change_id!==child.run.change_id||parent.run.execution_id!==child.run.execution_id)return"unavailable";const{task}=await composition.tasks.read(child.run.task_id);if(!["executing","verifying"].includes(task.status))return"unavailable";if(historicalRelayTaskOrchestrator&&!task.write_scopes.includes(".agents/records/**"))return"unavailable";const hostSessionId=historicalRelayTaskOrchestrator?historicalRoot?.run.client_thread_id:delegatedTaskOrchestrator?macro?.run.client_thread_id:parent.run.client_thread_id;if(typeof hostSessionId!=="string"||!hostSessionId)return"unavailable";const authority={schema_version:2,native_session_id:session,parent_session_id:parent.run.client_thread_id,host_session_id:hostSessionId,turn_id:observed.turn,run_id:id,parent_run_id:parent.run.run_id,agent_id:child.run.client_thread_id,task_id:child.run.task_id,execution_id:child.run.execution_id,write_scopes:historicalRelayTaskOrchestrator?[".agents/records/**"]:task.write_scopes};for(const hostSession of new Set([session,parent.run.client_thread_id,hostSessionId])){const binding={...authority,session_id:hostSession};const key=createHash66("sha256").update(JSON.stringify([hostSession,observed.turn])).digest("hex");const path=`.local/codex-hook-native/v2/${key}.json`;try{await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify(binding)}
3641
- `)}catch(error51){if(error51.code!=="EEXIST"||JSON.stringify(JSON.parse(await filesystem.readText(path)))!==JSON.stringify(binding))throw error51}}return"persisted"}var init_tool_binding=__esm({"src/host-native-delegation/tool-binding.ts"(){"use strict";init_subagent_local_inspection();init_historical_native_ancestry()}});function localSubagentLifecycleIdentityKey(observed){return[observed.sessionId,observed.turnId,observed.agentPath??observed.agentNickname??"",observed.agentRole??""].join("")}var init_local_subagent_lifecycle_identity=__esm({"src/local-subagent-lifecycle-identity.ts"(){"use strict"}});async function subagentIdentity(filesystem,rawAgentType){const agentType=rawAgentType.trim();const catalog=await loadAgentCatalog(filesystem);const agent=catalog.agents.find(candidate=>candidate.codex_name===agentType||candidate.id===agentType);return agent===void 0?{agent:`unrecognized-subagent:${slug(agentType)}`,agentName:agentType,codexTaskName:null,role:null,capabilities:[],executionEligibility:[],cataloged:false}:{agent:agent.id,agentName:agent.codex_name,codexTaskName:agent.codex_task_name,role:agent.role,capabilities:agent.capabilities,executionEligibility:agent.execution_eligibility,cataloged:true}}var init_subagent_identity_v2=__esm({"src/subagent-identity-v2.ts"(){"use strict";init_capture_options();init_run_agent_identity()}});function terminalFinalizationRequest(parsed,finalizer){const outcome=parsed.options["task-outcome"];const requested=outcome!==void 0||parsed.options.summary!==void 0||parsed.options.evidence!==void 0||parsed.options["changed-files"]!==void 0;if(!requested)return null;if(!finalizer){throw new UsageError("capture-terminal finalization decision is restricted to zaip-agent-finalizer")}if(outcome!=="completed"&&outcome!=="blocked"&&outcome!=="failed"&&outcome!=="cancelled"){throw new UsageError("capture-terminal --task-outcome must be completed, blocked, failed, or cancelled")}const summary=parsed.options.summary?.trim();if(summary===void 0||summary.length===0){throw new UsageError("capture-terminal finalization requires --summary")}return{outcome,summary,evidenceIds:assertFinalizationEvidenceInput(csvOption(parsed.options.evidence)),changedFiles:csvOption(parsed.options["changed-files"])}}function sameStringSet2(left,right){return left.length===right.length&&left.every(value=>right.includes(value))}var init_subagent_terminal_fallback_v2=__esm({"src/subagent-terminal-fallback-v2.ts"(){"use strict";init_cli_arguments();init_finalization_evidence_input()}});async function captureTerminalFallback(parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted){requireOptions(parsed.options,["parent-run-id","agent-id","agent-type","status"]);const parentAgentId=parsed.options["parent-agent-id"]?.trim();const parentRunId=optionValue(parsed,"parent-run-id");const agentPath=optionValue(parsed,"agent-id");const status=terminalStatus(parsed.options.status);const identity2=await subagentIdentity(filesystem,optionValue(parsed,"agent-type"));const finalizer=identity2.agent==="agent-finalizer"||identity2.role==="execution-finalizer";const finalization=terminalFinalizationRequest(parsed,finalizer);const eligibleExecutor=identity2.cataloged&&identity2.executionEligibility.includes("delivery")&&identity2.capabilities.includes("task-delivery");const eligibleReviewer=identity2.cataloged&&identity2.agent==="agent-reviewer"&&identity2.role==="reviewer"&&identity2.capabilities.includes("independent-review");if(!identity2.cataloged||!finalizer&&!eligibleExecutor&&!eligibleReviewer)throw new UsageError("capture-terminal requires the cataloged finalizer, independent reviewer, or an eligible delivery executor");const agentPathTaskName=catalogTaskNameFromHostIdentity(agentPath);if(identity2.codexTaskName===null||agentPathTaskName!==identity2.codexTaskName){throw new UsageError("capture-terminal agent-id must end with the selected catalog identity codex_task_name")}const root=await composition.runs.read(parentRunId).catch(()=>void 0);if(root===void 0||root.run.parent_run_id!==null||(parentAgentId===void 0?root.run.client_thread_id!==null:root.run.client_thread_id!==parentAgentId)){throw new UsageError(`Cannot capture terminal Sub-Run without exact active root Run ${parentRunId}`)}if(root.finished!==null){const existing=terminalFallbackExisting(await composition.runs.list(),root.run.run_id,agentPath,identity2.agent);if(existing===void 0||existing.status!==status){throw new UsageError(`Cannot capture terminal Sub-Run without exact active root Run ${parentRunId}`)}if(finalization!==null){const decision=root.finalization_decision??null;if(decision===null||decision.finalizer_run_id!==existing.run.run_id||decision.outcome!==finalization.outcome||decision.summary!==finalization.summary||!sameStringSet2(decision.evidence_ids,finalization.evidenceIds)||!sameStringSet2(decision.changed_files,finalization.changedFiles)){throw new UsageError(`capture-terminal decision conflicts with the persisted Gui finalization for Run ${root.run.run_id}`)}}return captureResult(existing,true)}const capture2=await withLifecycleCanonicalMutationLock(filesystem,async()=>{const capture3=await composition.runs.withUsageAttributionLock(async()=>{const invocationIdentity=["codex-subagent-terminal-fallback-v1",root.run.run_id,agentPath,identity2.agent].join("");const captured2=await composition.runs.withSubagentInvocationClaim(invocationIdentity,async runId=>{const existing=await composition.runs.read(runId);if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return captureResult(existing,true)},async()=>{const runs=await composition.runs.list();const parent=await composition.runs.read(root.run.run_id).catch(()=>void 0);if(parent===void 0||parent.status!=="running"||parent.run.parent_run_id!==null||parent.run.client_thread_id!==root.run.client_thread_id){throw new Error(`Root Run is no longer active: ${root.run.run_id}`)}const existing=terminalFallbackExisting(runs,parent.run.run_id,agentPath,identity2.agent);if(existing!==void 0){if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return{runId:existing.run.run_id,value:captureResult(existing,true)}}const executionKind=parent.run.execution_kind??(parent.run.entrypoint!=="conversation"?"delivery":parent.run.execution_id===null?void 0:await composition.executions.read(parent.run.execution_id).then(({execution})=>execution.kind??"delivery").catch(()=>void 0));const runPurpose=finalizer?"finalization":eligibleReviewer?"review":"execution";const effectiveParent=executionKind===void 0?parent:{...parent,run:{...parent.run,execution_kind:executionKind}};assertChildRunMayStart(effectiveParent,runPurpose,identity2.agent,runs,identity2.executionEligibility);const input={shortName:`subagent-${slug(identity2.agent)}-fallback`,phase:latestRunV2Phase(parent.records),runRole:"subagent",runPurpose,...executionKind===void 0?{}:{executionKind},executionEligibility:identity2.executionEligibility,entrypoint:parent.run.entrypoint,workType:parent.run.work_type,client:"codex-subagent",agent:identity2.agent,agentName:identity2.agentName,provider:null,model:"unavailable",reasoningEffort:null,clientThreadId:agentPath,clientTurnId:null,conversationId:parent.run.conversation_id,executionId:parent.run.execution_id,taskId:parent.run.task_id,specId:parent.run.spec_id,prdId:parent.run.prd_id,changeId:parent.run.change_id,parentRunId:parent.run.run_id};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const started=writer.started;const current=await composition.runs.read(started.run_id);await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));const withUsage=await composition.runs.read(started.run_id);const sequence=withUsage.records.length+1;await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(started.run_id,sequence),run_id:started.run_id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(withUsage.records),status}));const finished=await composition.runs.read(started.run_id);return{runId:started.run_id,value:{...captureResult(finished,false),fallback:"terminal-agent-path",usage_source:"unavailable"}}},async()=>{const existing=terminalFallbackExisting(await composition.runs.list(),root.run.run_id,agentPath,identity2.agent);if(existing===void 0)return null;if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return{runId:existing.run.run_id,value:captureResult(existing,true)}});const terminalDecision2=finalizer?await persistTerminalFallbackDecision(root.run.run_id,captured2,finalization,composition):null;return{captured:captured2,terminalDecision:terminalDecision2}});return capture3});const{captured,terminalDecision}=capture2;const result2=finalizer?{...captured,...terminalDecision===null?{}:{finalization:terminalDecision},parent_closure:await reconcileOrchestratorStop(await composition.runs.read(root.run.run_id),composition,lifecycle)}:captured;await onTerminalMutationCommitted?.(result2);return result2}function terminalFallbackExisting(runs,parentRunId,agentPath,agent){const matches=runs.filter(fold=>fold.run.parent_run_id===parentRunId&&fold.run.client_thread_id===agentPath&&fold.run.agent===agent);if(matches.length>1){throw new UsageError(`capture-terminal is ambiguous for ${agentPath}; capture the exact child session and turn`)}return matches[0]}async function persistTerminalFallbackDecision(rootRunId,captured,request,composition){if(request===null)return null;const finalizerRunId=captured.run?.run_id;if(typeof finalizerRunId!=="string"){throw new Error("capture-terminal did not return its authenticated Gui Sub-Run")}const root=await composition.runs.read(rootRunId);const finalizer=await composition.runs.read(finalizerRunId);if(root.finished!==null||finalizer.run.parent_run_id!==root.run.run_id||finalizer.run.agent!=="agent-finalizer"||effectiveRunV2Purpose(finalizer.run)!=="finalization"||finalizer.finished===null){throw new UsageError("capture-terminal finalization requires its exact terminal Gui Sub-Run")}const existing=root.finalization_decision??null;if(existing!==null){if(existing.finalizer_run_id!==finalizerRunId||existing.outcome!==request.outcome||existing.summary!==request.summary||!sameStringSet2(existing.evidence_ids,request.evidenceIds)||!sameStringSet2(existing.changed_files,request.changedFiles)){throw new UsageError(`Run ${root.run.run_id} already has a different Gui finalization decision`)}return existing}const{outcome,evidenceIds,changedFiles}=request;await assertFinalizationCandidatePreflight(root,outcome,evidenceIds,changedFiles,composition);const record3=runFinalizationDecidedV2Schema.parse({schema_version:2,event_id:runV2EventId(root.run.run_id,root.records.length+1),run_id:root.run.run_id,sequence:root.records.length+1,occurred_at:new Date().toISOString(),type:"run.finalization.decided",finalizer_run_id:finalizerRunId,outcome:request.outcome,summary:request.summary,evidence_ids:request.evidenceIds,changed_files:request.changedFiles});await composition.runs.appendRecord(record3);return record3}var init_subagent_terminal_capture=__esm({"src/subagent-terminal-capture.ts"(){"use strict";init_src5();init_src8();init_attribution_v2();init_cli_arguments();init_finalization_candidate_preflight();init_capture_options();init_capture_result();init_catalog_task_name();init_stop_closure();init_run_conversation_v2();init_run_finalization_barrier();init_subagent_identity_v2();init_subagent_terminal_fallback_v2()}});async function captureStop(parsed,composition,filesystem,lifecycle,identity2){const[sessionId,turnId,agentId2]=baseValues(parsed);const runs=await composition.runs.list();const status=terminalStatus(parsed.options.status??"completed");const capturedOrchestrator=runs.find(candidate=>(isNativeTaskAttempt(candidate)||candidate.run.parent_run_id!==null&&candidate.run.agent==="agent-orchestrator")&&candidate.run.client_thread_id===agentId2&&candidate.run.client_turn_id===turnId);if(identity2.role==="orchestrator"&&capturedOrchestrator===void 0){if(lifecycle===void 0){throw new UsageError("Orchestrator reconciliation requires lifecycle services")}const root=selectParent(runs,sessionId,turnId,parsed.options["parent-agent-id"],parsed.options["parent-run-id"])??runs.find(candidate=>candidate.finished!==null&&candidate.run.parent_run_id===null&&candidate.run.agent==="agent-orchestrator"&&candidate.run.client_thread_id===sessionId&&candidate.run.client_turn_id===turnId);if(root===void 0||root.run.parent_run_id!==null||root.run.agent!=="agent-orchestrator"){return{captured:false,reason:"root-run-not-found",agent_id:agentId2}}const current2=root;const closure=await reconcileOrchestratorStop(current2,composition,lifecycle,status);const settled=closure===null?current2:await composition.runs.read(current2.run.run_id);return{...captureResult(settled,true),bound_to_root:true,closure}}const child=runs.find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent&&(parsed.options["parent-run-id"]===void 0||fold.run.parent_run_id===parsed.options["parent-run-id"]));if(child===void 0){if(parsed.options["parent-run-id"]!==void 0&&runs.some(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent)){throw new UsageError("Sub-Run identity conflicts with explicit --parent-run-id")}return{captured:false,reused:true,status,reason:"pending-subagent-start",agent_id:agentId2,recovery:"replay-stop-after-start"}}assertCapturedSubagentIdentity(child,runs,sessionId,parsed.options["parent-agent-id"]);await persistObservedFinalizerDecision(parsed,child,composition);if(child.finished!==null){if(child.status!==status){throw new UsageError(`subagent stop status conflicts with existing Sub-Run ${child.run.run_id}`)}await settleCausalCapture(child,composition);if(isNativeTaskAttempt(child)&&lifecycle!==void 0){const taskClosure=await reconcileOrchestratorStop(child,composition,lifecycle,status);await reconcilePendingAncestorStops(child,composition,lifecycle);return{...captureResult(await composition.runs.read(child.run.run_id),true),task_closure:taskClosure}}if(identity2.agent==="agent-finalizer"&&lifecycle!==void 0&&child.run.parent_run_id!==null){const parent=await composition.runs.read(child.run.parent_run_id);const closure=await reconcileOrchestratorStop(parent,composition,lifecycle);return{...captureResult(child,true),parent_closure:closure}}if(lifecycle!==void 0)await reconcilePendingAncestorStops(child,composition,lifecycle);return captureResult(child,true)}let current=child;if(isNativeTaskAttempt(current)&&lifecycle!==void 0){await composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);if(await hookTrackingEnabled(filesystem)&&fresh.finished===null&&fresh.effective_usage_records.length===0)await composition.runs.appendRecord(unavailableUsageRecord(fresh,parsed,fresh.records.length+1))});const taskClosure=await reconcileOrchestratorStop(current,composition,lifecycle,status);await reconcilePendingAncestorStops(current,composition,lifecycle);return{...captureResult(await composition.runs.read(current.run.run_id),false),task_closure:taskClosure}}const captured=await composition.runs.withUsageAttributionLock(async()=>{current=await composition.runs.read(child.run.run_id);if(current.finished!==null){if(current.status!==status){throw new UsageError(`subagent stop status conflicts with existing Sub-Run ${current.run.run_id}`)}return captureResult(current,true)}if(await hookTrackingEnabled(filesystem)&&current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const sequence=current.records.length+1;await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,sequence),run_id:current.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status}));return captureResult(await composition.runs.read(current.run.run_id),false)});await settleCausalCapture(await composition.runs.read(child.run.run_id),composition);if(identity2.agent==="agent-finalizer"){const parent=child.run.parent_run_id===null?void 0:await composition.runs.read(child.run.parent_run_id).catch(()=>void 0);if(parent!==void 0&&lifecycle!==void 0){const closure=await reconcileOrchestratorStop(parent,composition,lifecycle);return{...captured,parent_closure:closure}}}if(lifecycle!==void 0)await reconcilePendingAncestorStops(child,composition,lifecycle);return captured}var init_subagent_stop_capture=__esm({"src/subagent-stop-capture.ts"(){"use strict";init_src4();init_src5();init_attribution_v2();init_cli_arguments();init_hook_tracking_policy();init_capture_options();init_capture_result();init_catalog_task_name();init_causal_recovery();init_finalization_relay();init_historical_native_ancestry();init_orchestrator_binding();init_parent_selection();init_reconciliation_identity();init_stop_closure();init_task_attempt();init_task_attribution();init_tool_binding();init_local_subagent_lifecycle_identity();init_post_publication_parental();init_post_publication_relay();init_record_codex_telemetry();init_run_agent_identity();init_run_conversation_v2();init_run_finalization_barrier();init_stop_receipt();init_subagent_identity_v2();init_subagent_local_inspection();init_subagent_terminal_capture()}});async function runSubagentV2Command(action,parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted){parsed=normalizeSubagentSessionOption(parsed);if(action==="reconcile-stop")return reconcileVerifiedStop(parsed,filesystem,composition,lifecycle,reconcileOrchestratorStop);if(action==="reconcile-local"||action==="inspect-local"){requireOptions(parsed.options,["parent-run-id"]);const parentRunId=optionValue(parsed,"parent-run-id");const root=await composition.runs.read(parentRunId).catch(()=>void 0);if(root===void 0)throw new UsageError(`Root Run not found: ${parentRunId}`);const authenticatedParental=root.run.parent_run_id!==null&&isParentalRelayShape(root);if(root.run.parent_run_id!==null&&!isNativeTaskAttempt(root)){if(!isParentalRelayShape(root))throw new UsageError(`Root Run not found: ${parentRunId}`);await authenticatedParentalRelay(root,composition,root.finished===null)}return action==="inspect-local"?inspectLocalSubagent(root,filesystem,optionValue(parsed,"session"),void 0,void 0,authenticatedParental):reconcileLocalSubagentSessions(root,composition,filesystem,lifecycle)}if(action==="capture-terminal"){return captureTerminalFallback(parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted)}if(action!=="capture")throw new UsageError(`Unknown subagent action: ${action??""}`);requireOptions(parsed.options,["event","session","turn","agent-id","agent-type"]);const event=parsed.options.event;if(event!=="start"&&event!=="stop"){throw new UsageError("--event must be start or stop")}if(event==="start")requireOptions(parsed.options,["model"]);if(event==="start"&&parsed.options["native-session"]!==void 0&&!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(parsed.options["native-session"]))throw new UsageError("--native-session must be the observed native child UUID");parsed=await resolveOrchestratorBinding(parsed,composition,filesystem);const identity2=await subagentIdentity(filesystem,parsed.options["agent-type"]??"");const result2=await(event==="start"?captureStart(parsed,composition,filesystem,identity2):captureStop(parsed,composition,filesystem,lifecycle,identity2));if(event==="start")await persistOrchestratorBinding(parsed,result2,filesystem);if(event==="start"){const binding=await persistNativeToolBinding(parsed,result2,filesystem,composition);if(binding==="unavailable")throw new UsageError("Sub-Run exists but native tool binding is unavailable; replay the same capture after inspect-local readiness")}return result2}async function captureStart(parsed,composition,filesystem,identity2,observedHistoricalRecovery=false){const[sessionId,turnId,agentId2,,model]=startValues(parsed);const assertReplay=createCaptureReplay(parsed,composition,filesystem);return composition.runs.withUsageAttributionLock(async()=>{const invocationIdentity=["codex-subagent-v1",sessionId,parsed.options["parent-agent-id"]??"",parsed.options["parent-run-id"]??"",agentId2,turnId,identity2.agent].join("");return composition.runs.withSubagentInvocationClaim(invocationIdentity,async runId=>assertReplay(await composition.runs.read(runId),await composition.runs.list()),async()=>{const runs=await composition.runs.list();const existing=runs.find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent&&(parsed.options["parent-run-id"]===void 0||fold.run.parent_run_id===parsed.options["parent-run-id"]));if(existing!==void 0){return{runId:existing.run.run_id,value:await assertReplay(existing,runs)}}const parent=selectParent(runs,sessionId,turnId,parsed.options["parent-agent-id"],parsed.options["parent-run-id"],observedHistoricalRecovery);if(parent===void 0){throw new Error(`Cannot claim Sub-Run without parent Run for ${agentId2}`)}if(identity2.role==="orchestrator"&&parsed.options["parent-agent-id"]===void 0&&turnId===parent.run.client_turn_id&&parent.run.parent_run_id===null&&parent.run.agent==="agent-orchestrator"&&(parsed.options.task===void 0||parsed.options.task===parent.run.task_id)){return{runId:parent.run.run_id,value:{...captureResult(parent,true),bound_to_root:true}}}const source=parent.run;const executionKind=source.execution_kind??(source.entrypoint!=="conversation"?"delivery":source.execution_id===null?void 0:await composition.executions.read(source.execution_id).then(({execution})=>execution.kind??"delivery").catch(()=>void 0));const effectiveParent=executionKind===void 0?parent:{...parent,run:{...parent.run,execution_kind:executionKind}};const parental=parsed.options.relay!==void 0&&parsed.options.task===void 0&&identity2.role==="orchestrator";const parentalProof=parental?await parentalRelayProof(composition,effectiveParent,parsed.options.relay,true):null;if(parentalProof){const nativeSession=parsed.options["native-session"];if(!nativeSession)throw new UsageError("Parental relay needs its observed native child session");const observed=await inspectLocalSubagent(parent,filesystem,nativeSession,void 0,turnId);const macro=runs.find(run=>run.run.run_id===parent.run.parent_run_id);if(!macro||!historicalNativeCaptureParentMatches(macro,parent,observed)||!observed.capture_ready||![observed.session,observed.agent_id].includes(agentId2)||observed.turn!==turnId||observed.agent_type!==parsed.options["agent-type"]||observed.model!==model||observed.reasoning_effort!==parsed.options["reasoning-effort"])throw new UsageError("Parental native child does not match its observed parent chain")}const runPurpose=identity2.role==="orchestrator"?"orchestration":identity2.role==="execution-finalizer"?"finalization":identity2.role==="reviewer"?"review":identity2.role==="auditor"?"audit":"execution";assertChildRunMayStart(effectiveParent,runPurpose,identity2.agent,runs,identity2.executionEligibility,{allowObservedIneligibleInvocation:parsed.options["observed-local-recovery"]==="true",allowObservedHistoricalInvocation:observedHistoricalRecovery});if(parsed.options.task!==void 0&&source.task_id===null&&identity2.role!=="orchestrator")throw new UsageError("A macro must dispatch a Task orchestrator, not an executor owning finalization");if(parsed.options.task!==void 0&&identity2.role==="orchestrator"&&runs.some(candidate=>isNativeTaskAttempt(candidate)&&candidate.status==="running"&&candidate.run.task_id===parsed.options.task))throw new UsageError("Task already has an active orchestrator attempt; reuse it");const input={shortName:`subagent-${slug(identity2.agent)}`,phase:latestRunV2Phase(parent.records),runRole:"subagent",runPurpose,requiresFinalizer:(parsed.options.task!==void 0||parental)&&identity2.role==="orchestrator",...executionKind===void 0?{}:{executionKind},executionEligibility:identity2.executionEligibility,...parentalProof?{entrypoint:"spec",executionId:parentalProof.execution.id,taskId:null,changeId:null,specId:parentalProof.spec.id,prdId:null}:await nativeTaskAttribution(effectiveParent,parsed.options.task,composition,parsed.options.relay),workType:source.work_type,client:"codex-subagent",agent:identity2.agent,agentName:identity2.agentName,provider:source.provider??"openai",model,reasoningEffort:parsed.options["reasoning-effort"]===void 0?null:runV2ReasoningEffortSchema.parse(parsed.options["reasoning-effort"]),clientThreadId:agentId2,clientTurnId:turnId,conversationId:source.conversation_id,parentRunId:source.run_id};await validateRunV2Attribution(input,composition,{allowObservedHistoricalInvocation:observedHistoricalRecovery});if(parsed.options.task&&source.task_id&&source.task_id!==parsed.options.task){const nativeSession=parsed.options["native-session"];if(!nativeSession)throw new UsageError("Historical capture requires its observed native child session");const observed=await inspectLocalSubagent(parent,filesystem,nativeSession,void 0,turnId);const macro=runs.find(run=>run.run.run_id===parent.run.parent_run_id);const macroMatches=macro!==void 0&&historicalNativeCaptureParentMatches(macro,parent,observed);if(!observed.capture_ready||![observed.session,observed.agent_id].includes(agentId2)||observed.turn!==turnId||observed.agent_type!==parsed.options["agent-type"]||observed.model!==model||observed.reasoning_effort!==parsed.options["reasoning-effort"]||!macroMatches)throw new UsageError("Historical native child does not match its observed parent chain");await assertRelayNativeCapture(composition,parent,parsed.options.task,parsed.options.relay,parsed.options["native-session"],agentId2,turnId,true)}else if(parsed.options.relay&&!parentalProof){throw new UsageError("Relay intent requires exact historical Task capture")}const causalReservation=await assertCausalCapture(effectiveParent,parsed.options.task??input.taskId??void 0,parsed.options["recovery-reservation"],composition);if(causalReservation&&input.taskId)await prepareCausalCapture(effectiveParent,input.taskId,agentId2,turnId,causalReservation,composition);const writer=await composition.runs.start(input);if(causalReservation)await bindCausalCapture(await composition.runs.read(writer.started.run_id),causalReservation,composition);if(parentalProof){const captured=await composition.runs.read(writer.started.run_id);await bindParentalRelay(composition,parent,captured,parsed.options.relay,parsed.options["native-session"])}return{runId:writer.started.run_id,value:{captured:true,reused:false,run:writer.started,artifact_path:composition.runs.path(writer.started.run_id),cataloged:identity2.cataloged}}},async()=>{const existing=(await composition.runs.list()).find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent);if(existing===void 0)return null;return{runId:existing.run.run_id,value:await assertReplay(existing,await composition.runs.list())}})})}async function reconcileLocalSubagentSessions(root,composition,filesystem,lifecycle,sourceOptions={},stopOnConcurrentRootAmbiguity=false){const parentThreadId=root.run.client_thread_id;const turnId=root.run.client_turn_id;if(parentThreadId==null||turnId==null){return{captured:[],skipped:[{reason:"root-correlation-unavailable"}],parent_run_id:root.run.run_id}}const concurrentRoots=(await composition.runs.list()).filter(fold=>fold.finished===null&&fold.run.parent_run_id===null&&fold.run.client_thread_id===parentThreadId);if(concurrentRoots.length>1){if(stopOnConcurrentRootAmbiguity){return{captured:[],skipped:[{reason:"local-discovery-skipped-concurrent-roots"}],parent_run_id:root.run.run_id}}throw new UsageError(`Multiple active root Runs share ${parentThreadId}; local Sub-Run discovery is ambiguous`)}const catalog=await loadAgentCatalog(filesystem);const rootStartedAt=Date.parse(root.run.occurred_at);const rootFinishedAt=root.finished===null?null:Date.parse(root.finished.occurred_at);const discovered=await discoverRegisteredChildLifecycles(filesystem.root,parentThreadId,sourceOptions);const lifecycles=discovered.filter(({observed:item})=>{const startedAt=item.startedAt===null?Number.NaN:Date.parse(item.startedAt);return Number.isFinite(startedAt)&&startedAt>=rootStartedAt&&(rootFinishedAt===null||startedAt<=rootFinishedAt)});const unique2=new Map(lifecycles.map(item=>[localSubagentLifecycleIdentityKey(item.observed),item]));const ordered=[...unique2.values()].sort((left,right)=>{const leftFinalizer=left.observed.agentRole==="zaip-agent-finalizer"?1:0;const rightFinalizer=right.observed.agentRole==="zaip-agent-finalizer"?1:0;return leftFinalizer-rightFinalizer||(left.observed.startedAt??"").localeCompare(right.observed.startedAt??"")});const captured=[];const skipped=[];for(const item of ordered){const{observed,workspaceRoot}=item;if(observed.status==="active"||observed.status==="interrupted"){skipped.push({agent_type:observed.agentRole,agent_path:observed.agentPath,reason:observed.status==="active"?"subagent-still-active":"terminal-status-inconclusive"});continue}const observedAgentPath=observed.agentPath??observed.agentNickname;const taskName=catalogTaskNameFromHostIdentity(observedAgentPath);const catalogAgent=catalog.agents.find(candidate=>candidate.codex_name===observed.agentRole&&candidate.codex_task_name===taskName);if(catalogAgent===void 0||observedAgentPath===null){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"catalog-identity-mismatch"});continue}const knownRuns=await composition.runs.list();const bindingAgentId=reconciliationAgentId(knownRuns,root.run.run_id,observed.sessionId,observed.turnId,catalogAgent.id,observedAgentPath);const existingTerminal=knownRuns.find(fold=>fold.finished!==null&&fold.run.parent_run_id===root.run.run_id&&fold.run.client_thread_id===bindingAgentId&&(fold.run.client_turn_id===observed.turnId||fold.run.client_turn_id===null)&&fold.run.agent===catalogAgent.id);if(existingTerminal!==void 0){if(existingTerminal.status!==observed.status||existingTerminal.run.client_turn_id!==null&&!hasObservedUsage(existingTerminal)){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"existing-terminal-subrun-conflict"});continue}captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status});continue}const segment2=await findLatestCodexSegment(workspaceRoot,new Set,{...sourceOptions,agentPath:observed.agentPath,parentThreadId,turnId:observed.turnId});if(segment2===null||segment2.model===null){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"observed-model-or-segment-unavailable"});continue}const baseOptions={session:observed.sessionId,turn:observed.turnId,"agent-id":bindingAgentId,"agent-type":catalogAgent.codex_name,"parent-agent-id":parentThreadId,"parent-run-id":root.run.run_id,"observed-local-recovery":"true"};await captureStart({positionals:["subagent","capture"],flags:new Set,options:{...baseOptions,event:"start",model:segment2.model,...segment2.reasoningEffort===null?{}:{"reasoning-effort":segment2.reasoningEffort}}},composition,filesystem,await subagentIdentity(filesystem,catalogAgent.codex_name),true);const startedChild=(await composition.runs.list()).find(fold=>fold.run.parent_run_id===root.run.run_id&&fold.run.client_thread_id===bindingAgentId&&fold.run.client_turn_id===observed.turnId&&fold.run.agent===catalogAgent.id);if(startedChild===void 0){throw new Error(`Reconciled Sub-Run was not materialized for ${observedAgentPath}`)}if(startedChild.finished!==null){if(startedChild.status!==observed.status||!hasObservedUsage(startedChild)){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"existing-terminal-subrun-conflict"});continue}captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status});continue}if(process.env.ZAIP_HOOK_TRACKING_ENABLED!=="false")await recordCodexTelemetryIfAvailable(startedChild,composition,filesystem,{agentPath:observed.agentPath,parentThreadId,threadId:null,turnId:observed.turnId},[],async()=>segment2);await captureStop({positionals:["subagent","capture"],flags:new Set,options:{...baseOptions,event:"stop",status:observed.status}},composition,filesystem,lifecycle,await subagentIdentity(filesystem,catalogAgent.codex_name));captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status})}return{captured,skipped,parent_run_id:root.run.run_id}}var init_subagent_command_v2=__esm({"src/subagent-command-v2.ts"(){"use strict";init_src4();init_src5();init_attribution_v2();init_cli_arguments();init_hook_tracking_policy();init_capture_options();init_capture_replay();init_capture_result();init_catalog_task_name();init_causal_recovery();init_finalization_relay();init_historical_native_ancestry();init_orchestrator_binding();init_parent_selection();init_reconciliation_identity();init_stop_closure();init_task_attempt();init_task_attribution();init_tool_binding();init_local_subagent_lifecycle_identity();init_post_publication_parental();init_post_publication_relay();init_record_codex_telemetry();init_run_agent_identity();init_run_conversation_v2();init_run_finalization_barrier();init_stop_receipt();init_subagent_identity_v2();init_subagent_local_inspection();init_subagent_stop_capture();init_subagent_terminal_capture()}});import{createHash as createHash67}from"node:crypto";async function runTaskAssuranceCommand(parsed,filesystem,composition,hookArgv=process.argv.slice(2)){if(!parsed.flags.has("json"))throw new UsageError("task assurance requires --json");const id=requiredEntityId(parsed,2,"Task id");const{task}=await composition.tasks.read(id);if(task.id!==id)throw new UsageError("Assurance Task identity mismatch");const explicitMapPath=parsed.options["applicability-map"];const inheritedAttempt=parsed.options["inherit-applicability-attempt"];if(explicitMapPath!==void 0||inheritedAttempt!==void 0){if(explicitMapPath!==void 0&&inheritedAttempt!==void 0)throw new UsageError("Choose one applicability registration source");if(parsed.flags.has("preflight")||parsed.options.evidence!==void 0)throw new UsageError("Applicability registration cannot be combined with preflight");const runId=parsed.options.run;if(runId===void 0)throw new UsageError("Applicability registration requires --run");if(!["executing","verifying"].includes(task.status))throw new UsageError("Applicability registration requires an active Task");const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());const fold=await composition.runs.read(runId);if(fold.status!=="running"||fold.run.task_id!==task.id||fold.run.change_id!==task.change_id||fold.run.execution_id!==executionId)throw new UsageError("Applicability registration requires the active attributed Task Run");const cycle=await readReleaseCycle(filesystem);const targetRelease=cycle?await effectiveTaskRelease(task,composition):null;const historical=Boolean(cycle&&targetRelease&&targetRelease!==cycle.current_release);if(historical){if((await historicalRelayEvidenceIds(fold,composition)).size===0)throw new UsageError("Historical applicability requires an authenticated records-only relay");const bound=await authenticatedBoundRelay(fold,composition);if(!bound||bound.evidenceIds.size===0)throw new UsageError("Historical applicability requires an exact bound relay");await assertLiveRelayAuthority(composition,bound.intent);const hookIds=hookArgv.filter(value=>value.startsWith("--codex-hook-id="));const hookThreads=hookArgv.filter(value=>value.startsWith("--codex-hook-thread="));if(hookIds.length!==1||hookThreads.length!==1)throw new UsageError("Historical applicability requires a one-use native turn receipt");const macro=await composition.runs.read(bound.intent.macro_run_id);const observed=await resolveRunClientInvocation(filesystem,macro.run.client,{argv:[...hookArgv]});if(macro.status!=="running"||observed.clientThreadId!==macro.run.client_thread_id||observed.clientTurnId!==macro.run.client_turn_id||observed.observedModel!==macro.run.model||observed.observedReasoningEffort!==macro.run.reasoning_effort)throw new UsageError("Historical applicability requires the observed macro root turn")}else{if(inheritedAttempt!==void 0)throw new UsageError("Applicability inheritance requires a historical bound relay");await readReadyTaskWorkspaceClaim(filesystem,task.id,executionId,runId)}let provenance=null;let map2;if(inheritedAttempt!==void 0){const sourceAttempt=Number(inheritedAttempt);const targetAttempt=task.attempt_count??0;if(task.status!=="executing"||!/^[1-9]\d*$/.test(inheritedAttempt)||!Number.isSafeInteger(sourceAttempt)||!Number.isSafeInteger(targetAttempt)||sourceAttempt>=targetAttempt)throw new UsageError("Applicability inheritance requires an earlier attempt and executing Task");const sourcePath=taskMutationApplicabilityPath(task.id,sourceAttempt);const source=await filesystem.readText(sourcePath);const sourceMap=taskMutationApplicabilityV1Schema.parse(JSON.parse(source));await validateTaskMutationApplicabilityV1(filesystem,{...task,attempt_count:sourceAttempt},executionId,sourceMap);map2=taskMutationApplicabilityV1Schema.parse({...sourceMap,attempt_count:targetAttempt});provenance={source_path:sourcePath,source_sha256:createHash67("sha256").update(source).digest("hex"),source_attempt:sourceAttempt,target_attempt:targetAttempt}}else{map2=taskMutationApplicabilityV1Schema.parse(JSON.parse(await filesystem.readText(explicitMapPath)))}await validateTaskMutationApplicabilityV1(filesystem,task,executionId,map2);const path=taskMutationApplicabilityPath(task.id,task.attempt_count??0);const content=`${JSON.stringify(map2,null,2)}
3642
- `;if(provenance!==null){provenance.target_path=path;provenance.target_sha256=createHash67("sha256").update(content).digest("hex")}if(await filesystem.exists(path)){if(await filesystem.readText(path)!==content)throw new UsageError("Conflicting Task mutation applicability already registered")}else await filesystem.writeTextAtomicExclusive(path,content);return{task_id:task.id,execution_id:executionId,run_id:runId,mutation_acceptance_ids:map2.criteria.filter(criterion=>criterion.modalities.includes("mutation")).map(criterion=>criterion.acceptance_id),artifact_path:path,...provenance===null?{}:{inheritance:provenance}}}const config2=assuranceConfig(composition);const evidence_ids=csvOption(parsed.options.evidence);const effective=effectiveTaskAssurance(task,config2);const{standard_depth,contract}=effective;if(!parsed.flags.has("preflight")){return{task_id:task.id,contract,planning:assurancePlanning(task,effective),standard_depth,require_final_commit:effective.require_final_commit,risk_signals:effectiveTaskRiskSignals(task)??null,risk_signals_source:task.model_profile&&task.assurance_risk_signals_source!=="explicit"?"model_profile":task.assurance_risk_signals_source??"historical_fallback",preflight:false,evidence_ids}}if(evidence_ids.length===0)throw new UsageError("task assurance --preflight requires --evidence EVD-...");await assertTaskAssurancePreflightV1({filesystem,layout:composition.layout,task,evidence_ids,config:config2});return{task_id:task.id,contract,standard_depth,require_final_commit:effective.require_final_commit,risk_signals:effectiveTaskRiskSignals(task)??null,scope:"artifacts_only_commit_and_finalizer_still_required",preflight:"artifact-passed",evidence_ids}}function assuranceConfig(composition){const assurance=composition.layout.projectConfig?.assurance;return assurance?.version===1?assurance:{standard_depth:"auto",require_final_commit:false}}var init_task_assurance_command=__esm({"src/task-assurance-command.ts"(){"use strict";init_assurance();init_assurance_planning();init_cli_arguments();init_lifecycle_assurance_v2();init_post_publication_relay();init_post_publication_relay_contract();init_release_cycle();init_run_client_invocation();init_task_execution_resolution_v2();init_task_workspace_command()}});async function migrateTaskAutonomy(id,parsed,composition){requireOptions(parsed.options,["execution","expected-revision","legacy-attempts","legacy-replans","reason"]);const policy=composition.layout.projectConfig?.autonomy;if(!policy)throw new UsageError("Configure autonomy.version: 1 before migration");const executionId=parsed.options.execution;const{execution}=await composition.executions.read(executionId);const{task}=await composition.tasks.read(id);if(!execution.dag.nodes.some(node=>node.task_id===id))throw new UsageError("Task is outside the selected Execution");if(!["blocked","failed","planned"].includes(task.status))throw new UsageError("Migration requires an inactive nonterminal Task");if(task.revision!==Number(parsed.options["expected-revision"]))throw new UsageError("Task revision changed before migration");const attempts=Number(parsed.options["legacy-attempts"]);const replans=parsed.options["legacy-replans"]==="unknown"?null:Number(parsed.options["legacy-replans"]);const future=parsed.options["future-replans"];if(replans===null&&future===void 0)throw new UsageError("Unknown history requires --future-replans N (or unlimited for persistent)");if(replans!==null&&future!==void 0)throw new UsageError("--future-replans applies only to unknown historical replans");if(task.attempt_count===void 0)throw new UsageError("Legacy attempt count unavailable; reconcile historical accounting before migration");if(![attempts,...replans===null?[]:[replans]].every(n=>Number.isSafeInteger(n)&&n>=0)||attempts<task.attempt_count)throw new UsageError("Migration counts must be nonnegative and preserve canonical attempt_count");const store=new LifecycleManifestStore(composition.filesystem);if(!await store.readSummary())throw new UsageError("Migration needs a current manifest inventory");const inventory3=(await store.readEntities("run")).filter(entity=>entity.data?.task_id===id);const runs=await Promise.all(inventory3.map(entity=>composition.runs.read(entity.id)));if(runs.some(fold=>fold.run.task_id!==id||fold.finished===null))throw new UsageError("Task has active or mismatched Run identity; reconcile observed terminal events first");const executors=runs.filter(fold=>fold.run.run_purpose==="execution"&&fold.run.execution_eligibility?.includes("delivery"));if(attempts<executors.length)throw new UsageError("Migration cannot discard observed executor invocations");const localState=await new FileAutonomousStatePort(composition.filesystem).load(executionId);const prior=localState?.tasks.find(item=>item.id===id);if(prior?.active_invocation||prior?.recovery_invocation||prior?.active_diagnostic?.status==="requested")throw new UsageError("Migration cannot replace a pending invocation");const baseline=recoveryLedgerSchema.parse({...createRecoveryLedger(id,policy.preset,attempts),legacy_replans:replans,migration:{reason:parsed.options.reason.trim(),task_revision:task.revision,execution_id:executionId,run_ids:runs.map(fold=>fold.run.run_id).sort(),...replans===null?{future_replans:future==="unlimited"?null:Number(future)}:{}}});if(!baseline.migration?.reason)throw new UsageError("Migration needs an explicit historical accounting reason");if(!parsed.flags.has("confirm"))return{mode:"preview",baseline,progress:recoveryProgress(baseline),side_effects:false};const current=(await composition.tasks.read(id)).task;if(current.revision!==task.revision||current.status!==task.status)throw new UsageError("Task changed during migration");const ledger=await new FileRecoveryLedger(composition.filesystem).migrate(baseline);return{mode:"migrated",task_id:id,ledger,progress:recoveryProgress(ledger),lifecycle_changed:false}}var init_task_autonomy_migration=__esm({"src/task-autonomy-migration.ts"(){"use strict";init_src();init_src8();init_src7();init_cli_arguments()}});async function taskRecoveryStatus(id,composition){if(!id)throw new UsageError("task recovery-status requires a Task ID");const{task}=await composition.tasks.read(id);const ledger=await new FileRecoveryLedger(composition.filesystem).read(id);if(ledger===null)return{task_id:id,task_status:task.status,policy:"legacy_or_unmigrated",operation:null,progress:null,recovery_available:null,recovery_operation:null};const progress=recoveryProgress(ledger);const next=nextRecoveryOperation(ledger);return{task_id:id,task_status:task.status,policy:"frozen_autonomy_v1",operation:["blocked","failed"].includes(task.status)?next:null,recovery_available:["executing","verifying"].includes(task.status)?next!==null:null,recovery_operation:["executing","verifying"].includes(task.status)?next:null,progress}}var init_task_recovery_status=__esm({"src/task-recovery-status.ts"(){"use strict";init_src();init_src7();init_cli_arguments()}});import{createHash as createHash68}from"node:crypto";function runTaskVerificationRepairCommand(parsed,composition){return parsed.positionals[1]==="repair-verification"?repairTaskVerification(parsed,composition):settleVerificationRepair(parsed,composition)}async function repairTaskVerification(parsed,composition){requireOptions(parsed.options,["run","validation","commit","expected-revision","reason"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task repair-verification requires a Task id");const{task}=await composition.tasks.read(id);const root=await composition.runs.read(parsed.options.run);if(root.status!=="running"||root.finalization_decision!=null||root.run.agent!=="agent-orchestrator"||root.run.task_id!==id||root.run.change_id!==task.change_id||root.run.execution_kind!=="delivery")throw new UsageError("Verification repair requires this Task's active delivery orchestrator before Gui");if(["codex","codex-desktop"].includes(root.run.client)){const observed=await resolveRunClientInvocation(composition.filesystem,root.run.client);if(!observed.clientThreadId||!observed.clientTurnId||observed.clientThreadId!==root.run.client_thread_id||observed.clientTurnId!==root.run.client_turn_id)throw new UsageError("Verification repair requires the exact observed Codex thread/turn correlation")}const validationId=parsed.options.validation;if(!/^(?:TEST|CHECK|INT|EVAL|MUT|E2E|REVIEW)-[A-Z0-9-]+$/.test(validationId))throw new UsageError("Invalid failed validation ID");const reason=parsed.options.reason.trim();if(!reason||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(parsed.options.commit))throw new UsageError("Repair requires an observed failed candidate and an explicit reason");const fs=composition.filesystem;const directory2=composition.changes.path(task.change_id).replace(/\/change\.md$/,"");const validation=parseMarkdown(await fs.readText(`${directory2}/artifacts/tests/${validationId}.md`),validationArtifactV2Schema).metadata;const runs=await composition.runs.list();assertChildRunMayStart(root,"execution","agent-task-executor",runs,["delivery"]);const ownedRuns=new Set([root.run.run_id,...descendantRuns(root.run.run_id,runs).map(r=>r.run.run_id)]);if(validation.status!=="failed"||validation.task_id!==id||validation.change_id!==task.change_id||validation.execution_id!==root.run.execution_id||!ownedRuns.has(validation.run_id)||validation.commit_sha!==parsed.options.commit||!validation.acceptance_ids.every(ac=>task.acceptance_ids.includes(ac)))throw new UsageError("Repair requires failed verification from this exact Task, Execution, Run and candidate");if(activeDescendantRuns(root.run.run_id,runs).length)throw new UsageError("Finish active descendants before verification repair");const key=createHash68("sha256").update(JSON.stringify({task:id,run:root.run.run_id,validation:validationId})).digest("hex").slice(0,24);const path=`${directory2}/artifacts/rework/verification-${key}.json`;const previous=await fs.exists(path)?JSON.parse(await fs.readText(path)):null;if(previous&&(previous.reason!==reason||previous.commit_sha!==validation.commit_sha))throw new UsageError("Verification repair receipt is immutable");if(previous&&task.revision===previous.next_revision&&task.status==="executing")return{task,repair_path:path,recovery_attempt_id:previous.recovery_attempt_id,reused:true};if(task.status!=="verifying"||task.revision!==Number(parsed.options["expected-revision"])||previous&&previous.previous_revision!==task.revision)throw new UsageError("Inspect the current Task revision; only verifying can enter guarded repair");const store=new FileRecoveryLedger(fs);const ledger=await store.read(id);if(!ledger)throw new UsageError("Migrate or initialize this Task's frozen recovery ledger before repair");const attemptId=`verification-repair:${key}`;const replanId=`verification-plan:${key}`;if(ledger.entries.some(e=>e.status==="reserved"&&e.id!==attemptId))throw new UsageError("Reconcile the observed outcome of the pending recovery reservation first");let next=ledger;if(next.entries.find(e=>e.id===attemptId)?.status!==void 0&&next.entries.find(e=>e.id===attemptId)?.status!=="reserved")throw new UsageError("An unapplied repair cannot reuse a settled recovery reservation");if(!next.entries.some(e=>e.id===attemptId)){const operation=nextRecoveryOperation(next);if(operation===null||operation==="reconcile")throw new UsageError("Frozen recovery budget is exhausted or requires reconciliation");if(operation==="replan"){const summary=parsed.options["replan-summary"]?.trim();const selection2=replanModel(next.preset,recoveryProgress(next).replans+1);const planner=parsed.options["replan-run"]?await composition.runs.read(parsed.options["replan-run"]):root;if(!summary||!ownedRuns.has(planner.run.run_id)||planner.run.task_id!==id||planner.run.execution_id!==root.run.execution_id||planner.run.run_id!==root.run.run_id&&planner.status!=="completed"||planner.run.model!==selection2.model||planner.run.reasoning_effort!==selection2.reasoning_effort)throw new UsageError(`Observed replan required: ${selection2.model}/${selection2.reasoning_effort}; no silent model fallback`);next=settleRecovery(reserveRecovery(next,replanId,"replan"),replanId,"completed",summary)}next=reserveRecovery(next,attemptId,"attempt")}const repaired=taskV2Schema.parse({...task,status:"executing",revision:task.revision+1,updated_at:new Date().toISOString()});if(!previous)await fs.writeTextAtomicExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:root.run.run_id,execution_id:root.run.execution_id,validation_id:validationId,commit_sha:validation.commit_sha,previous_revision:task.revision,next_revision:repaired.revision,reason,recovery_attempt_id:attemptId,occurred_at:repaired.updated_at},null,2)}
3641
+ `)}catch(error51){if(error51.code!=="EEXIST"||JSON.stringify(JSON.parse(await filesystem.readText(path)))!==JSON.stringify(binding))throw error51}}return"persisted"}var init_tool_binding=__esm({"src/host-native-delegation/tool-binding.ts"(){"use strict";init_subagent_local_inspection();init_historical_native_ancestry()}});function localSubagentLifecycleIdentityKey(observed){return[observed.sessionId,observed.turnId,observed.agentPath??observed.agentNickname??"",observed.agentRole??""].join("")}var init_local_subagent_lifecycle_identity=__esm({"src/local-subagent-lifecycle-identity.ts"(){"use strict"}});async function subagentIdentity(filesystem,rawAgentType){const agentType=rawAgentType.trim();const catalog=await loadAgentCatalog(filesystem);const agent=catalog.agents.find(candidate=>candidate.codex_name===agentType||candidate.id===agentType);return agent===void 0?{agent:`unrecognized-subagent:${slug(agentType)}`,agentName:agentType,codexTaskName:null,role:null,capabilities:[],executionEligibility:[],cataloged:false}:{agent:agent.id,agentName:agent.codex_name,codexTaskName:agent.codex_task_name,role:agent.role,capabilities:agent.capabilities,executionEligibility:agent.execution_eligibility,cataloged:true}}var init_subagent_identity_v2=__esm({"src/subagent-identity-v2.ts"(){"use strict";init_capture_options();init_run_agent_identity()}});function terminalFinalizationRequest(parsed,finalizer){const outcome=parsed.options["task-outcome"];const requested=outcome!==void 0||parsed.options.summary!==void 0||parsed.options.evidence!==void 0||parsed.options["changed-files"]!==void 0;if(!requested)return null;if(!finalizer){throw new UsageError("capture-terminal finalization decision is restricted to zaip-agent-finalizer")}if(outcome!=="completed"&&outcome!=="blocked"&&outcome!=="failed"&&outcome!=="cancelled"){throw new UsageError("capture-terminal --task-outcome must be completed, blocked, failed, or cancelled")}const summary=parsed.options.summary?.trim();if(summary===void 0||summary.length===0){throw new UsageError("capture-terminal finalization requires --summary")}return{outcome,summary,evidenceIds:assertFinalizationEvidenceInput(csvOption(parsed.options.evidence)),changedFiles:csvOption(parsed.options["changed-files"])}}function sameStringSet2(left,right){return left.length===right.length&&left.every(value=>right.includes(value))}var init_subagent_terminal_fallback_v2=__esm({"src/subagent-terminal-fallback-v2.ts"(){"use strict";init_cli_arguments();init_finalization_evidence_input()}});async function captureTerminalFallback(parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted){requireOptions(parsed.options,["parent-run-id","agent-id","agent-type","status"]);const parentAgentId=parsed.options["parent-agent-id"]?.trim();const parentRunId=optionValue(parsed,"parent-run-id");const agentPath=optionValue(parsed,"agent-id");const status=terminalStatus(parsed.options.status);const identity2=await subagentIdentity(filesystem,optionValue(parsed,"agent-type"));const finalizer=identity2.agent==="agent-finalizer"||identity2.role==="execution-finalizer";const finalization=terminalFinalizationRequest(parsed,finalizer);const eligibleExecutor=identity2.cataloged&&identity2.executionEligibility.includes("delivery")&&identity2.capabilities.includes("task-delivery");const eligibleReviewer=identity2.cataloged&&identity2.agent==="agent-reviewer"&&identity2.role==="reviewer"&&identity2.capabilities.includes("independent-review");if(!identity2.cataloged||!finalizer&&!eligibleExecutor&&!eligibleReviewer)throw new UsageError("capture-terminal requires the cataloged finalizer, independent reviewer, or an eligible delivery executor");const agentPathTaskName=catalogTaskNameFromHostIdentity(agentPath);if(identity2.codexTaskName===null||agentPathTaskName!==identity2.codexTaskName){throw new UsageError("capture-terminal agent-id must end with the selected catalog identity codex_task_name")}const root=await composition.runs.read(parentRunId).catch(()=>void 0);if(root===void 0||root.run.parent_run_id!==null||(parentAgentId===void 0?root.run.client_thread_id!==null:root.run.client_thread_id!==parentAgentId)){throw new UsageError(`Cannot capture terminal Sub-Run without exact active root Run ${parentRunId}`)}if(root.finished!==null){const existing=terminalFallbackExisting(await composition.runs.list(),root.run.run_id,agentPath,identity2.agent);if(existing===void 0||existing.status!==status){throw new UsageError(`Cannot capture terminal Sub-Run without exact active root Run ${parentRunId}`)}if(finalization!==null){const decision=root.finalization_decision??null;if(decision===null||decision.finalizer_run_id!==existing.run.run_id||decision.outcome!==finalization.outcome||decision.summary!==finalization.summary||!sameStringSet2(decision.evidence_ids,finalization.evidenceIds)||!sameStringSet2(decision.changed_files,finalization.changedFiles)){throw new UsageError(`capture-terminal decision conflicts with the persisted Gui finalization for Run ${root.run.run_id}`)}}return captureResult(existing,true)}const capture2=await withLifecycleCanonicalMutationLock(filesystem,async()=>{const capture3=await composition.runs.withUsageAttributionLock(async()=>{const invocationIdentity=["codex-subagent-terminal-fallback-v1",root.run.run_id,agentPath,identity2.agent].join("");const captured2=await composition.runs.withSubagentInvocationClaim(invocationIdentity,async runId=>{const existing=await composition.runs.read(runId);if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return captureResult(existing,true)},async()=>{const runs=await composition.runs.list();const parent=await composition.runs.read(root.run.run_id).catch(()=>void 0);if(parent===void 0||parent.status!=="running"||parent.run.parent_run_id!==null||parent.run.client_thread_id!==root.run.client_thread_id){throw new Error(`Root Run is no longer active: ${root.run.run_id}`)}const existing=terminalFallbackExisting(runs,parent.run.run_id,agentPath,identity2.agent);if(existing!==void 0){if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return{runId:existing.run.run_id,value:captureResult(existing,true)}}const executionKind=parent.run.execution_kind??(parent.run.entrypoint!=="conversation"?"delivery":parent.run.execution_id===null?void 0:await composition.executions.read(parent.run.execution_id).then(({execution})=>execution.kind??"delivery").catch(()=>void 0));const runPurpose=finalizer?"finalization":eligibleReviewer?"review":"execution";const effectiveParent=executionKind===void 0?parent:{...parent,run:{...parent.run,execution_kind:executionKind}};assertChildRunMayStart(effectiveParent,runPurpose,identity2.agent,runs,identity2.executionEligibility);const input={shortName:`subagent-${slug(identity2.agent)}-fallback`,phase:latestRunV2Phase(parent.records),runRole:"subagent",runPurpose,...executionKind===void 0?{}:{executionKind},executionEligibility:identity2.executionEligibility,entrypoint:parent.run.entrypoint,workType:parent.run.work_type,client:"codex-subagent",agent:identity2.agent,agentName:identity2.agentName,provider:null,model:"unavailable",reasoningEffort:null,clientThreadId:agentPath,clientTurnId:null,conversationId:parent.run.conversation_id,executionId:parent.run.execution_id,taskId:parent.run.task_id,specId:parent.run.spec_id,prdId:parent.run.prd_id,changeId:parent.run.change_id,parentRunId:parent.run.run_id};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const started=writer.started;const current=await composition.runs.read(started.run_id);await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));const withUsage=await composition.runs.read(started.run_id);const sequence=withUsage.records.length+1;await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(started.run_id,sequence),run_id:started.run_id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(withUsage.records),status}));const finished=await composition.runs.read(started.run_id);return{runId:started.run_id,value:{...captureResult(finished,false),fallback:"terminal-agent-path",usage_source:"unavailable"}}},async()=>{const existing=terminalFallbackExisting(await composition.runs.list(),root.run.run_id,agentPath,identity2.agent);if(existing===void 0)return null;if(existing.status!==status){throw new UsageError(`capture-terminal status conflicts with existing Sub-Run ${existing.run.run_id}`)}return{runId:existing.run.run_id,value:captureResult(existing,true)}});const terminalDecision2=finalizer?await persistTerminalFallbackDecision(root.run.run_id,captured2,finalization,composition):null;return{captured:captured2,terminalDecision:terminalDecision2}});return capture3});const{captured,terminalDecision}=capture2;const result2=finalizer?{...captured,...terminalDecision===null?{}:{finalization:terminalDecision},parent_closure:await reconcileOrchestratorStop(await composition.runs.read(root.run.run_id),composition,lifecycle)}:captured;await onTerminalMutationCommitted?.(result2);return result2}function terminalFallbackExisting(runs,parentRunId,agentPath,agent){const matches=runs.filter(fold=>fold.run.parent_run_id===parentRunId&&fold.run.client_thread_id===agentPath&&fold.run.agent===agent);if(matches.length>1){throw new UsageError(`capture-terminal is ambiguous for ${agentPath}; capture the exact child session and turn`)}return matches[0]}async function persistTerminalFallbackDecision(rootRunId,captured,request,composition){if(request===null)return null;const finalizerRunId=captured.run?.run_id;if(typeof finalizerRunId!=="string"){throw new Error("capture-terminal did not return its authenticated Gui Sub-Run")}const root=await composition.runs.read(rootRunId);const finalizer=await composition.runs.read(finalizerRunId);if(root.finished!==null||finalizer.run.parent_run_id!==root.run.run_id||finalizer.run.agent!=="agent-finalizer"||effectiveRunV2Purpose(finalizer.run)!=="finalization"||finalizer.finished===null){throw new UsageError("capture-terminal finalization requires its exact terminal Gui Sub-Run")}const existing=root.finalization_decision??null;if(existing!==null){if(existing.finalizer_run_id!==finalizerRunId||existing.outcome!==request.outcome||existing.summary!==request.summary||!sameStringSet2(existing.evidence_ids,request.evidenceIds)||!sameStringSet2(existing.changed_files,request.changedFiles)){throw new UsageError(`Run ${root.run.run_id} already has a different Gui finalization decision`)}return existing}const{outcome,evidenceIds,changedFiles}=request;await assertFinalizationCandidatePreflight(root,outcome,evidenceIds,changedFiles,composition);const record3=runFinalizationDecidedV2Schema.parse({schema_version:2,event_id:runV2EventId(root.run.run_id,root.records.length+1),run_id:root.run.run_id,sequence:root.records.length+1,occurred_at:new Date().toISOString(),type:"run.finalization.decided",finalizer_run_id:finalizerRunId,outcome:request.outcome,summary:request.summary,evidence_ids:request.evidenceIds,changed_files:request.changedFiles});await composition.runs.appendRecord(record3);return record3}var init_subagent_terminal_capture=__esm({"src/subagent-terminal-capture.ts"(){"use strict";init_src5();init_src8();init_attribution_v2();init_cli_arguments();init_finalization_candidate_preflight();init_capture_options();init_capture_result();init_catalog_task_name();init_stop_closure();init_run_conversation_v2();init_run_finalization_barrier();init_subagent_identity_v2();init_subagent_terminal_fallback_v2()}});async function captureStop(parsed,composition,filesystem,lifecycle,identity2){const[sessionId,turnId,agentId2]=baseValues(parsed);const runs=await composition.runs.list();const status=terminalStatus(parsed.options.status??"completed");const capturedOrchestrator=runs.find(candidate=>(isNativeTaskAttempt(candidate)||candidate.run.parent_run_id!==null&&candidate.run.agent==="agent-orchestrator")&&candidate.run.client_thread_id===agentId2&&candidate.run.client_turn_id===turnId);if(identity2.role==="orchestrator"&&capturedOrchestrator===void 0){if(lifecycle===void 0){throw new UsageError("Orchestrator reconciliation requires lifecycle services")}const root=selectParent(runs,sessionId,turnId,parsed.options["parent-agent-id"],parsed.options["parent-run-id"])??runs.find(candidate=>candidate.finished!==null&&candidate.run.parent_run_id===null&&candidate.run.agent==="agent-orchestrator"&&candidate.run.client_thread_id===sessionId&&candidate.run.client_turn_id===turnId);if(root===void 0||root.run.parent_run_id!==null||root.run.agent!=="agent-orchestrator"){return{captured:false,reason:"root-run-not-found",agent_id:agentId2}}const current2=root;const closure=await reconcileOrchestratorStop(current2,composition,lifecycle,status);const settled=closure===null?current2:await composition.runs.read(current2.run.run_id);return{...captureResult(settled,true),bound_to_root:true,closure}}const child=runs.find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent&&(parsed.options["parent-run-id"]===void 0||fold.run.parent_run_id===parsed.options["parent-run-id"]));if(child===void 0){if(parsed.options["parent-run-id"]!==void 0&&runs.some(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent)){throw new UsageError("Sub-Run identity conflicts with explicit --parent-run-id")}return{captured:false,reused:true,status,reason:"pending-subagent-start",agent_id:agentId2,recovery:"replay-stop-after-start"}}assertCapturedSubagentIdentity(child,runs,sessionId,parsed.options["parent-agent-id"]);await persistObservedFinalizerDecision(parsed,child,composition);if(child.finished!==null){if(child.status!==status){throw new UsageError(`subagent stop status conflicts with existing Sub-Run ${child.run.run_id}`)}await settleCausalCapture(child,composition);if(isNativeTaskAttempt(child)&&lifecycle!==void 0){const taskClosure=await reconcileOrchestratorStop(child,composition,lifecycle,status);await reconcilePendingAncestorStops(child,composition,lifecycle);return{...captureResult(await composition.runs.read(child.run.run_id),true),task_closure:taskClosure}}if(identity2.agent==="agent-finalizer"&&lifecycle!==void 0&&child.run.parent_run_id!==null){const parent=await composition.runs.read(child.run.parent_run_id);const closure=await reconcileOrchestratorStop(parent,composition,lifecycle);return{...captureResult(child,true),parent_closure:closure}}if(lifecycle!==void 0)await reconcilePendingAncestorStops(child,composition,lifecycle);return captureResult(child,true)}let current=child;if(isNativeTaskAttempt(current)&&lifecycle!==void 0){await composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);if(await hookTrackingEnabled(filesystem)&&fresh.finished===null&&fresh.effective_usage_records.length===0)await composition.runs.appendRecord(unavailableUsageRecord(fresh,parsed,fresh.records.length+1))});const taskClosure=await reconcileOrchestratorStop(current,composition,lifecycle,status);await reconcilePendingAncestorStops(current,composition,lifecycle);return{...captureResult(await composition.runs.read(current.run.run_id),false),task_closure:taskClosure}}const captured=await composition.runs.withUsageAttributionLock(async()=>{current=await composition.runs.read(child.run.run_id);if(current.finished!==null){if(current.status!==status){throw new UsageError(`subagent stop status conflicts with existing Sub-Run ${current.run.run_id}`)}return captureResult(current,true)}if(await hookTrackingEnabled(filesystem)&&current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const sequence=current.records.length+1;await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,sequence),run_id:current.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status}));return captureResult(await composition.runs.read(current.run.run_id),false)});await settleCausalCapture(await composition.runs.read(child.run.run_id),composition);if(identity2.agent==="agent-finalizer"){const parent=child.run.parent_run_id===null?void 0:await composition.runs.read(child.run.parent_run_id).catch(()=>void 0);if(parent!==void 0&&lifecycle!==void 0){const closure=await reconcileOrchestratorStop(parent,composition,lifecycle);return{...captured,parent_closure:closure}}}if(lifecycle!==void 0)await reconcilePendingAncestorStops(child,composition,lifecycle);return captured}var init_subagent_stop_capture=__esm({"src/subagent-stop-capture.ts"(){"use strict";init_src4();init_src5();init_attribution_v2();init_cli_arguments();init_hook_tracking_policy();init_capture_options();init_capture_result();init_catalog_task_name();init_causal_recovery();init_finalization_relay();init_historical_native_ancestry();init_orchestrator_binding();init_parent_selection();init_reconciliation_identity();init_stop_closure();init_task_attempt();init_task_attribution();init_tool_binding();init_local_subagent_lifecycle_identity();init_post_publication_parental();init_post_publication_relay();init_record_codex_telemetry();init_run_agent_identity();init_run_conversation_v2();init_run_finalization_barrier();init_stop_receipt();init_subagent_identity_v2();init_subagent_local_inspection();init_subagent_terminal_capture()}});async function runSubagentV2Command(action,parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted){parsed=normalizeSubagentSessionOption(parsed);if(action==="reconcile-stop")return reconcileVerifiedStop(parsed,filesystem,composition,lifecycle,reconcileOrchestratorStop);if(action==="reconcile-local"||action==="inspect-local"){requireOptions(parsed.options,["parent-run-id"]);const parentRunId=optionValue(parsed,"parent-run-id");const root=await composition.runs.read(parentRunId).catch(()=>void 0);if(root===void 0)throw new UsageError(`Root Run not found: ${parentRunId}`);const authenticatedParental=root.run.parent_run_id!==null&&isParentalRelayShape(root);if(root.run.parent_run_id!==null&&!isNativeTaskAttempt(root)){if(!isParentalRelayShape(root))throw new UsageError(`Root Run not found: ${parentRunId}`);await authenticatedParentalRelay(root,composition,root.finished===null)}return action==="inspect-local"?inspectLocalSubagent(root,filesystem,optionValue(parsed,"session"),void 0,void 0,authenticatedParental):reconcileLocalSubagentSessions(root,composition,filesystem,lifecycle)}if(action==="capture-terminal"){return captureTerminalFallback(parsed,composition,filesystem,lifecycle,onTerminalMutationCommitted)}if(action!=="capture")throw new UsageError(`Unknown subagent action: ${action??""}`);requireOptions(parsed.options,["event","session","turn","agent-id","agent-type"]);const event=parsed.options.event;if(event!=="start"&&event!=="stop"){throw new UsageError("--event must be start or stop")}if(event==="start")requireOptions(parsed.options,["model"]);if(event==="start"&&parsed.options["native-session"]!==void 0&&!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(parsed.options["native-session"]))throw new UsageError("--native-session must be the observed native child UUID");parsed=await resolveOrchestratorBinding(parsed,composition,filesystem);const identity2=await subagentIdentity(filesystem,parsed.options["agent-type"]??"");const result2=await(event==="start"?captureStart(parsed,composition,filesystem,identity2):captureStop(parsed,composition,filesystem,lifecycle,identity2));if(event==="start")await persistOrchestratorBinding(parsed,result2,filesystem);if(event==="start"){const binding=await persistNativeToolBinding(parsed,result2,filesystem,composition);if(binding==="unavailable")throw new UsageError("Sub-Run exists but native tool binding is unavailable; replay the same capture after inspect-local readiness")}return result2}async function captureStart(parsed,composition,filesystem,identity2,observedHistoricalRecovery=false){const[sessionId,turnId,agentId2,,model]=startValues(parsed);const assertReplay=createCaptureReplay(parsed,composition,filesystem);return composition.runs.withUsageAttributionLock(async()=>{const invocationIdentity=["codex-subagent-v1",sessionId,parsed.options["parent-agent-id"]??"",parsed.options["parent-run-id"]??"",agentId2,turnId,identity2.agent].join("");return composition.runs.withSubagentInvocationClaim(invocationIdentity,async runId=>assertReplay(await composition.runs.read(runId),await composition.runs.list()),async()=>{const runs=await composition.runs.list();const existing=runs.find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent&&(parsed.options["parent-run-id"]===void 0||fold.run.parent_run_id===parsed.options["parent-run-id"]));if(existing!==void 0){return{runId:existing.run.run_id,value:await assertReplay(existing,runs)}}const parent=selectParent(runs,sessionId,turnId,parsed.options["parent-agent-id"],parsed.options["parent-run-id"],observedHistoricalRecovery);if(parent===void 0){throw new Error(`Cannot claim Sub-Run without parent Run for ${agentId2}`)}if(identity2.role==="orchestrator"&&parsed.options["parent-agent-id"]===void 0&&turnId===parent.run.client_turn_id&&parent.run.parent_run_id===null&&parent.run.agent==="agent-orchestrator"&&(parsed.options.task===void 0||parsed.options.task===parent.run.task_id)){return{runId:parent.run.run_id,value:{...captureResult(parent,true),bound_to_root:true}}}const source=parent.run;const executionKind=source.execution_kind??(source.entrypoint!=="conversation"?"delivery":source.execution_id===null?void 0:await composition.executions.read(source.execution_id).then(({execution})=>execution.kind??"delivery").catch(()=>void 0));const effectiveParent=executionKind===void 0?parent:{...parent,run:{...parent.run,execution_kind:executionKind}};const parental=parsed.options.relay!==void 0&&parsed.options.task===void 0&&identity2.role==="orchestrator";const parentalProof=parental?await parentalRelayProof(composition,effectiveParent,parsed.options.relay,true):null;if(parentalProof){const nativeSession=parsed.options["native-session"];if(!nativeSession)throw new UsageError("Parental relay needs its observed native child session");const observed=await inspectLocalSubagent(parent,filesystem,nativeSession,void 0,turnId);const macro=runs.find(run=>run.run.run_id===parent.run.parent_run_id);if(!macro||!historicalNativeCaptureParentMatches(macro,parent,observed)||!observed.capture_ready||![observed.session,observed.agent_id].includes(agentId2)||observed.turn!==turnId||observed.agent_type!==parsed.options["agent-type"]||observed.model!==model||observed.reasoning_effort!==parsed.options["reasoning-effort"])throw new UsageError("Parental native child does not match its observed parent chain")}const runPurpose=identity2.role==="orchestrator"?"orchestration":identity2.role==="execution-finalizer"?"finalization":identity2.role==="reviewer"?"review":identity2.role==="auditor"?"audit":"execution";assertChildRunMayStart(effectiveParent,runPurpose,identity2.agent,runs,identity2.executionEligibility,{allowObservedIneligibleInvocation:parsed.options["observed-local-recovery"]==="true",allowObservedHistoricalInvocation:observedHistoricalRecovery});if(parsed.options.task!==void 0&&source.task_id===null&&identity2.role!=="orchestrator")throw new UsageError("A macro must dispatch a Task orchestrator, not an executor owning finalization");if(parsed.options.task!==void 0&&identity2.role==="orchestrator"&&runs.some(candidate=>isNativeTaskAttempt(candidate)&&candidate.status==="running"&&candidate.run.task_id===parsed.options.task))throw new UsageError("Task already has an active orchestrator attempt; reuse it");const input={shortName:`subagent-${slug(identity2.agent)}`,phase:latestRunV2Phase(parent.records),runRole:"subagent",runPurpose,requiresFinalizer:(parsed.options.task!==void 0||parental)&&identity2.role==="orchestrator",...executionKind===void 0?{}:{executionKind},executionEligibility:identity2.executionEligibility,...parentalProof?{entrypoint:"spec",executionId:parentalProof.execution.id,taskId:null,changeId:null,specId:parentalProof.spec.id,prdId:null}:await nativeTaskAttribution(effectiveParent,parsed.options.task,composition,parsed.options.relay),workType:source.work_type,client:"codex-subagent",agent:identity2.agent,agentName:identity2.agentName,provider:source.provider??"openai",model,reasoningEffort:parsed.options["reasoning-effort"]===void 0?null:runV2ReasoningEffortSchema.parse(parsed.options["reasoning-effort"]),clientThreadId:agentId2,clientTurnId:turnId,conversationId:source.conversation_id,parentRunId:source.run_id};await validateRunV2Attribution(input,composition,{allowObservedHistoricalInvocation:observedHistoricalRecovery});if(parsed.options.task&&source.task_id&&source.task_id!==parsed.options.task){const nativeSession=parsed.options["native-session"];if(!nativeSession)throw new UsageError("Historical capture requires its observed native child session");const observed=await inspectLocalSubagent(parent,filesystem,nativeSession,void 0,turnId);const macro=runs.find(run=>run.run.run_id===parent.run.parent_run_id);const macroMatches=macro!==void 0&&historicalNativeCaptureParentMatches(macro,parent,observed);if(!observed.capture_ready||![observed.session,observed.agent_id].includes(agentId2)||observed.turn!==turnId||observed.agent_type!==parsed.options["agent-type"]||observed.model!==model||observed.reasoning_effort!==parsed.options["reasoning-effort"]||!macroMatches)throw new UsageError("Historical native child does not match its observed parent chain");await assertRelayNativeCapture(composition,parent,parsed.options.task,parsed.options.relay,parsed.options["native-session"],agentId2,turnId,true)}else if(parsed.options.relay&&!parentalProof){throw new UsageError("Relay intent requires exact historical Task capture")}const causalReservation=await assertCausalCapture(effectiveParent,parsed.options.task??input.taskId??void 0,parsed.options["recovery-reservation"],composition);if(causalReservation&&input.taskId)await prepareCausalCapture(effectiveParent,input.taskId,agentId2,turnId,causalReservation,composition);const writer=await composition.runs.start(input);if(causalReservation)await bindCausalCapture(await composition.runs.read(writer.started.run_id),causalReservation,composition);if(parentalProof){const captured=await composition.runs.read(writer.started.run_id);await bindParentalRelay(composition,parent,captured,parsed.options.relay,parsed.options["native-session"])}return{runId:writer.started.run_id,value:{captured:true,reused:false,run:writer.started,artifact_path:composition.runs.path(writer.started.run_id),cataloged:identity2.cataloged}}},async()=>{const existing=(await composition.runs.list()).find(fold=>fold.run.client_thread_id===agentId2&&fold.run.client_turn_id===turnId&&fold.run.agent===identity2.agent);if(existing===void 0)return null;return{runId:existing.run.run_id,value:await assertReplay(existing,await composition.runs.list())}})})}async function reconcileLocalSubagentSessions(root,composition,filesystem,lifecycle,sourceOptions={},stopOnConcurrentRootAmbiguity=false){const parentThreadId=root.run.client_thread_id;const turnId=root.run.client_turn_id;if(parentThreadId==null||turnId==null){return{captured:[],skipped:[{reason:"root-correlation-unavailable"}],parent_run_id:root.run.run_id}}const concurrentRoots=(await composition.runs.list()).filter(fold=>fold.finished===null&&fold.run.parent_run_id===null&&fold.run.client_thread_id===parentThreadId);if(concurrentRoots.length>1){if(stopOnConcurrentRootAmbiguity){return{captured:[],skipped:[{reason:"local-discovery-skipped-concurrent-roots"}],parent_run_id:root.run.run_id}}throw new UsageError(`Multiple active root Runs share ${parentThreadId}; local Sub-Run discovery is ambiguous`)}const catalog=await loadAgentCatalog(filesystem);const rootStartedAt=Date.parse(root.run.occurred_at);const rootFinishedAt=root.finished===null?null:Date.parse(root.finished.occurred_at);const discovered=await discoverRegisteredChildLifecycles(filesystem.root,parentThreadId,sourceOptions);const lifecycles=discovered.filter(({observed:item})=>{const startedAt=item.startedAt===null?Number.NaN:Date.parse(item.startedAt);return Number.isFinite(startedAt)&&startedAt>=rootStartedAt&&(rootFinishedAt===null||startedAt<=rootFinishedAt)});const unique2=new Map(lifecycles.map(item=>[localSubagentLifecycleIdentityKey(item.observed),item]));const ordered=[...unique2.values()].sort((left,right)=>{const leftFinalizer=left.observed.agentRole==="zaip-agent-finalizer"?1:0;const rightFinalizer=right.observed.agentRole==="zaip-agent-finalizer"?1:0;return leftFinalizer-rightFinalizer||(left.observed.startedAt??"").localeCompare(right.observed.startedAt??"")});const captured=[];const skipped=[];for(const item of ordered){const{observed,workspaceRoot}=item;if(observed.status==="active"||observed.status==="interrupted"){skipped.push({agent_type:observed.agentRole,agent_path:observed.agentPath,reason:observed.status==="active"?"subagent-still-active":"terminal-status-inconclusive"});continue}const observedAgentPath=observed.agentPath??observed.agentNickname;const taskName=catalogTaskNameFromHostIdentity(observedAgentPath);const catalogAgent=catalog.agents.find(candidate=>candidate.codex_name===observed.agentRole&&candidate.codex_task_name===taskName);if(catalogAgent===void 0||observedAgentPath===null){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"catalog-identity-mismatch"});continue}const knownRuns=await composition.runs.list();const bindingAgentId=reconciliationAgentId(knownRuns,root.run.run_id,observed.sessionId,observed.turnId,catalogAgent.id,observedAgentPath);const existingTerminal=knownRuns.find(fold=>fold.finished!==null&&fold.run.parent_run_id===root.run.run_id&&fold.run.client_thread_id===bindingAgentId&&(fold.run.client_turn_id===observed.turnId||fold.run.client_turn_id===null)&&fold.run.agent===catalogAgent.id);if(existingTerminal!==void 0){if(existingTerminal.status!==observed.status||existingTerminal.run.client_turn_id!==null&&!hasObservedUsage(existingTerminal)){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"existing-terminal-subrun-conflict"});continue}captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status});continue}const segment2=await findLatestCodexSegment(workspaceRoot,new Set,{...sourceOptions,agentPath:observed.agentPath,parentThreadId,turnId:observed.turnId});if(segment2===null||segment2.model===null){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"observed-model-or-segment-unavailable"});continue}const baseOptions={session:observed.sessionId,turn:observed.turnId,"agent-id":bindingAgentId,"agent-type":catalogAgent.codex_name,"parent-agent-id":parentThreadId,"parent-run-id":root.run.run_id,"observed-local-recovery":"true"};await captureStart({positionals:["subagent","capture"],flags:new Set,options:{...baseOptions,event:"start",model:segment2.model,...segment2.reasoningEffort===null?{}:{"reasoning-effort":segment2.reasoningEffort}}},composition,filesystem,await subagentIdentity(filesystem,catalogAgent.codex_name),true);const startedChild=(await composition.runs.list()).find(fold=>fold.run.parent_run_id===root.run.run_id&&fold.run.client_thread_id===bindingAgentId&&fold.run.client_turn_id===observed.turnId&&fold.run.agent===catalogAgent.id);if(startedChild===void 0){throw new Error(`Reconciled Sub-Run was not materialized for ${observedAgentPath}`)}if(startedChild.finished!==null){if(startedChild.status!==observed.status||!hasObservedUsage(startedChild)){skipped.push({agent_type:observed.agentRole,agent_path:observedAgentPath,reason:"existing-terminal-subrun-conflict"});continue}captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status});continue}if(process.env.ZAIP_HOOK_TRACKING_ENABLED!=="false")await recordCodexTelemetryIfAvailable(startedChild,composition,filesystem,{agentPath:observed.agentPath,parentThreadId,threadId:null,turnId:observed.turnId},[],async()=>segment2);await captureStop({positionals:["subagent","capture"],flags:new Set,options:{...baseOptions,event:"stop",status:observed.status}},composition,filesystem,lifecycle,await subagentIdentity(filesystem,catalogAgent.codex_name));captured.push({agent_type:catalogAgent.codex_name,agent_path:observedAgentPath,status:observed.status})}return{captured,skipped,parent_run_id:root.run.run_id}}var init_subagent_command_v2=__esm({"src/subagent-command-v2.ts"(){"use strict";init_src4();init_src5();init_attribution_v2();init_cli_arguments();init_hook_tracking_policy();init_capture_options();init_capture_replay();init_capture_result();init_catalog_task_name();init_causal_recovery();init_finalization_relay();init_historical_native_ancestry();init_orchestrator_binding();init_parent_selection();init_reconciliation_identity();init_stop_closure();init_task_attempt();init_task_attribution();init_tool_binding();init_local_subagent_lifecycle_identity();init_post_publication_parental();init_post_publication_relay();init_record_codex_telemetry();init_run_agent_identity();init_run_conversation_v2();init_run_finalization_barrier();init_stop_receipt();init_subagent_identity_v2();init_subagent_local_inspection();init_subagent_stop_capture();init_subagent_terminal_capture()}});import{createHash as createHash67}from"node:crypto";async function runTaskAssuranceCommand(parsed,filesystem,composition,hookArgv=process.argv.slice(2)){if(!parsed.flags.has("json"))throw new UsageError("task assurance requires --json");const id=requiredEntityId(parsed,2,"Task id");const{task}=await composition.tasks.read(id);if(task.id!==id)throw new UsageError("Assurance Task identity mismatch");const explicitMapPath=parsed.options["applicability-map"];const inheritedAttempt=parsed.options["inherit-applicability-attempt"];if(explicitMapPath!==void 0||inheritedAttempt!==void 0){if(explicitMapPath!==void 0&&inheritedAttempt!==void 0)throw new UsageError("Choose one applicability registration source");if(parsed.flags.has("preflight")||parsed.options.evidence!==void 0)throw new UsageError("Applicability registration cannot be combined with preflight");const runId=parsed.options.run;if(runId===void 0)throw new UsageError("Applicability registration requires --run");if(!["executing","verifying"].includes(task.status))throw new UsageError("Applicability registration requires an active Task");const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());const fold=await composition.runs.read(runId);if(fold.status!=="running"||fold.run.task_id!==task.id||fold.run.change_id!==task.change_id||fold.run.execution_id!==executionId)throw new UsageError("Applicability registration requires the active attributed Task Run");const cycle=await readReleaseCycle(filesystem);const targetRelease=cycle?await effectiveTaskRelease(task,composition):null;const historical=Boolean(cycle&&targetRelease&&targetRelease!==cycle.current_release);if(historical){const taskFirst=await taskFirstPublishedBoundary(fold,composition);if(taskFirst===null&&(await historicalRelayEvidenceIds(fold,composition)).size===0)throw new UsageError("Historical applicability requires an authenticated records-only relay");const bound=taskFirst===null?await authenticatedBoundRelay(fold,composition):null;if(taskFirst===null&&(!bound||bound.evidenceIds.size===0))throw new UsageError("Historical applicability requires an exact bound relay");if(bound!==null)await assertLiveRelayAuthority(composition,bound.intent);const hookIds=hookArgv.filter(value=>value.startsWith("--codex-hook-id="));const hookThreads=hookArgv.filter(value=>value.startsWith("--codex-hook-thread="));if(hookIds.length!==1||hookThreads.length!==1)throw new UsageError("Historical applicability requires a one-use native turn receipt");const macro=bound===null?fold:await composition.runs.read(bound.intent.macro_run_id);const observed=await resolveRunClientInvocation(filesystem,macro.run.client,{argv:[...hookArgv]});if(macro.status!=="running"||observed.clientThreadId!==macro.run.client_thread_id||observed.clientTurnId!==macro.run.client_turn_id||observed.observedModel!==macro.run.model||observed.observedReasoningEffort!==macro.run.reasoning_effort)throw new UsageError("Historical applicability requires the observed macro root turn or Task-first root turn")}else{if(inheritedAttempt!==void 0)throw new UsageError("Applicability inheritance requires a historical bound relay");await readReadyTaskWorkspaceClaim(filesystem,task.id,executionId,runId)}let provenance=null;let map2;if(inheritedAttempt!==void 0){const sourceAttempt=Number(inheritedAttempt);const targetAttempt=task.attempt_count??0;if(task.status!=="executing"||!/^[1-9]\d*$/.test(inheritedAttempt)||!Number.isSafeInteger(sourceAttempt)||!Number.isSafeInteger(targetAttempt)||sourceAttempt>=targetAttempt)throw new UsageError("Applicability inheritance requires an earlier attempt and executing Task");const sourcePath=taskMutationApplicabilityPath(task.id,sourceAttempt);const source=await filesystem.readText(sourcePath);const sourceMap=taskMutationApplicabilityV1Schema.parse(JSON.parse(source));await validateTaskMutationApplicabilityV1(filesystem,{...task,attempt_count:sourceAttempt},executionId,sourceMap);map2=taskMutationApplicabilityV1Schema.parse({...sourceMap,attempt_count:targetAttempt});provenance={source_path:sourcePath,source_sha256:createHash67("sha256").update(source).digest("hex"),source_attempt:sourceAttempt,target_attempt:targetAttempt}}else{map2=taskMutationApplicabilityV1Schema.parse(JSON.parse(await filesystem.readText(explicitMapPath)))}await validateTaskMutationApplicabilityV1(filesystem,task,executionId,map2);const path=taskMutationApplicabilityPath(task.id,task.attempt_count??0);const content=`${JSON.stringify(map2,null,2)}
3642
+ `;if(provenance!==null){provenance.target_path=path;provenance.target_sha256=createHash67("sha256").update(content).digest("hex")}if(await filesystem.exists(path)){if(await filesystem.readText(path)!==content)throw new UsageError("Conflicting Task mutation applicability already registered")}else await filesystem.writeTextAtomicExclusive(path,content);return{task_id:task.id,execution_id:executionId,run_id:runId,mutation_acceptance_ids:map2.criteria.filter(criterion=>criterion.modalities.includes("mutation")).map(criterion=>criterion.acceptance_id),artifact_path:path,...provenance===null?{}:{inheritance:provenance}}}const config2=assuranceConfig(composition);const evidence_ids=csvOption(parsed.options.evidence);const effective=effectiveTaskAssurance(task,config2);const{standard_depth,contract}=effective;if(!parsed.flags.has("preflight")){return{task_id:task.id,contract,planning:assurancePlanning(task,effective),standard_depth,require_final_commit:effective.require_final_commit,risk_signals:effectiveTaskRiskSignals(task)??null,risk_signals_source:task.model_profile&&task.assurance_risk_signals_source!=="explicit"?"model_profile":task.assurance_risk_signals_source??"historical_fallback",preflight:false,evidence_ids}}if(evidence_ids.length===0)throw new UsageError("task assurance --preflight requires --evidence EVD-...");await assertTaskAssurancePreflightV1({filesystem,layout:composition.layout,task,evidence_ids,config:config2});return{task_id:task.id,contract,standard_depth,require_final_commit:effective.require_final_commit,risk_signals:effectiveTaskRiskSignals(task)??null,scope:"artifacts_only_commit_and_finalizer_still_required",preflight:"artifact-passed",evidence_ids}}function assuranceConfig(composition){const assurance=composition.layout.projectConfig?.assurance;return assurance?.version===1?assurance:{standard_depth:"auto",require_final_commit:false}}var init_task_assurance_command=__esm({"src/task-assurance-command.ts"(){"use strict";init_assurance();init_assurance_planning();init_cli_arguments();init_lifecycle_assurance_v2();init_post_publication_relay();init_post_publication_relay_contract();init_post_publication_task_first();init_release_cycle();init_run_client_invocation();init_task_execution_resolution_v2();init_task_workspace_command()}});async function migrateTaskAutonomy(id,parsed,composition){requireOptions(parsed.options,["execution","expected-revision","legacy-attempts","legacy-replans","reason"]);const policy=composition.layout.projectConfig?.autonomy;if(!policy)throw new UsageError("Configure autonomy.version: 1 before migration");const executionId=parsed.options.execution;const{execution}=await composition.executions.read(executionId);const{task}=await composition.tasks.read(id);if(!execution.dag.nodes.some(node=>node.task_id===id))throw new UsageError("Task is outside the selected Execution");if(!["blocked","failed","planned"].includes(task.status))throw new UsageError("Migration requires an inactive nonterminal Task");if(task.revision!==Number(parsed.options["expected-revision"]))throw new UsageError("Task revision changed before migration");const attempts=Number(parsed.options["legacy-attempts"]);const replans=parsed.options["legacy-replans"]==="unknown"?null:Number(parsed.options["legacy-replans"]);const future=parsed.options["future-replans"];if(replans===null&&future===void 0)throw new UsageError("Unknown history requires --future-replans N (or unlimited for persistent)");if(replans!==null&&future!==void 0)throw new UsageError("--future-replans applies only to unknown historical replans");if(task.attempt_count===void 0)throw new UsageError("Legacy attempt count unavailable; reconcile historical accounting before migration");if(![attempts,...replans===null?[]:[replans]].every(n=>Number.isSafeInteger(n)&&n>=0)||attempts<task.attempt_count)throw new UsageError("Migration counts must be nonnegative and preserve canonical attempt_count");const store=new LifecycleManifestStore(composition.filesystem);if(!await store.readSummary())throw new UsageError("Migration needs a current manifest inventory");const inventory3=(await store.readEntities("run")).filter(entity=>entity.data?.task_id===id);const runs=await Promise.all(inventory3.map(entity=>composition.runs.read(entity.id)));if(runs.some(fold=>fold.run.task_id!==id||fold.finished===null))throw new UsageError("Task has active or mismatched Run identity; reconcile observed terminal events first");const executors=runs.filter(fold=>fold.run.run_purpose==="execution"&&fold.run.execution_eligibility?.includes("delivery"));if(attempts<executors.length)throw new UsageError("Migration cannot discard observed executor invocations");const localState=await new FileAutonomousStatePort(composition.filesystem).load(executionId);const prior=localState?.tasks.find(item=>item.id===id);if(prior?.active_invocation||prior?.recovery_invocation||prior?.active_diagnostic?.status==="requested")throw new UsageError("Migration cannot replace a pending invocation");const baseline=recoveryLedgerSchema.parse({...createRecoveryLedger(id,policy.preset,attempts),legacy_replans:replans,migration:{reason:parsed.options.reason.trim(),task_revision:task.revision,execution_id:executionId,run_ids:runs.map(fold=>fold.run.run_id).sort(),...replans===null?{future_replans:future==="unlimited"?null:Number(future)}:{}}});if(!baseline.migration?.reason)throw new UsageError("Migration needs an explicit historical accounting reason");if(!parsed.flags.has("confirm"))return{mode:"preview",baseline,progress:recoveryProgress(baseline),side_effects:false};const current=(await composition.tasks.read(id)).task;if(current.revision!==task.revision||current.status!==task.status)throw new UsageError("Task changed during migration");const ledger=await new FileRecoveryLedger(composition.filesystem).migrate(baseline);return{mode:"migrated",task_id:id,ledger,progress:recoveryProgress(ledger),lifecycle_changed:false}}var init_task_autonomy_migration=__esm({"src/task-autonomy-migration.ts"(){"use strict";init_src();init_src8();init_src7();init_cli_arguments()}});async function taskRecoveryStatus(id,composition){if(!id)throw new UsageError("task recovery-status requires a Task ID");const{task}=await composition.tasks.read(id);const ledger=await new FileRecoveryLedger(composition.filesystem).read(id);if(ledger===null)return{task_id:id,task_status:task.status,policy:"legacy_or_unmigrated",operation:null,progress:null,recovery_available:null,recovery_operation:null};const progress=recoveryProgress(ledger);const next=nextRecoveryOperation(ledger);return{task_id:id,task_status:task.status,policy:"frozen_autonomy_v1",operation:["blocked","failed"].includes(task.status)?next:null,recovery_available:["executing","verifying"].includes(task.status)?next!==null:null,recovery_operation:["executing","verifying"].includes(task.status)?next:null,progress}}var init_task_recovery_status=__esm({"src/task-recovery-status.ts"(){"use strict";init_src();init_src7();init_cli_arguments()}});import{createHash as createHash68}from"node:crypto";function runTaskVerificationRepairCommand(parsed,composition){return parsed.positionals[1]==="repair-verification"?repairTaskVerification(parsed,composition):settleVerificationRepair(parsed,composition)}async function repairTaskVerification(parsed,composition){requireOptions(parsed.options,["run","validation","commit","expected-revision","reason"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task repair-verification requires a Task id");const{task}=await composition.tasks.read(id);const root=await composition.runs.read(parsed.options.run);if(root.status!=="running"||root.finalization_decision!=null||root.run.agent!=="agent-orchestrator"||root.run.task_id!==id||root.run.change_id!==task.change_id||root.run.execution_kind!=="delivery")throw new UsageError("Verification repair requires this Task's active delivery orchestrator before Gui");if(["codex","codex-desktop"].includes(root.run.client)){const observed=await resolveRunClientInvocation(composition.filesystem,root.run.client);if(!observed.clientThreadId||!observed.clientTurnId||observed.clientThreadId!==root.run.client_thread_id||observed.clientTurnId!==root.run.client_turn_id)throw new UsageError("Verification repair requires the exact observed Codex thread/turn correlation")}const validationId=parsed.options.validation;if(!/^(?:TEST|CHECK|INT|EVAL|MUT|E2E|REVIEW)-[A-Z0-9-]+$/.test(validationId))throw new UsageError("Invalid failed validation ID");const reason=parsed.options.reason.trim();if(!reason||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(parsed.options.commit))throw new UsageError("Repair requires an observed failed candidate and an explicit reason");const fs=composition.filesystem;const directory2=composition.changes.path(task.change_id).replace(/\/change\.md$/,"");const validation=parseMarkdown(await fs.readText(`${directory2}/artifacts/tests/${validationId}.md`),validationArtifactV2Schema).metadata;const runs=await composition.runs.list();assertChildRunMayStart(root,"execution","agent-task-executor",runs,["delivery"]);const ownedRuns=new Set([root.run.run_id,...descendantRuns(root.run.run_id,runs).map(r=>r.run.run_id)]);if(validation.status!=="failed"||validation.task_id!==id||validation.change_id!==task.change_id||validation.execution_id!==root.run.execution_id||!ownedRuns.has(validation.run_id)||validation.commit_sha!==parsed.options.commit||!validation.acceptance_ids.every(ac=>task.acceptance_ids.includes(ac)))throw new UsageError("Repair requires failed verification from this exact Task, Execution, Run and candidate");if(activeDescendantRuns(root.run.run_id,runs).length)throw new UsageError("Finish active descendants before verification repair");const key=createHash68("sha256").update(JSON.stringify({task:id,run:root.run.run_id,validation:validationId})).digest("hex").slice(0,24);const path=`${directory2}/artifacts/rework/verification-${key}.json`;const previous=await fs.exists(path)?JSON.parse(await fs.readText(path)):null;if(previous&&(previous.reason!==reason||previous.commit_sha!==validation.commit_sha))throw new UsageError("Verification repair receipt is immutable");if(previous&&task.revision===previous.next_revision&&task.status==="executing")return{task,repair_path:path,recovery_attempt_id:previous.recovery_attempt_id,reused:true};if(task.status!=="verifying"||task.revision!==Number(parsed.options["expected-revision"])||previous&&previous.previous_revision!==task.revision)throw new UsageError("Inspect the current Task revision; only verifying can enter guarded repair");const store=new FileRecoveryLedger(fs);const ledger=await store.read(id);if(!ledger)throw new UsageError("Migrate or initialize this Task's frozen recovery ledger before repair");const attemptId=`verification-repair:${key}`;const replanId=`verification-plan:${key}`;if(ledger.entries.some(e=>e.status==="reserved"&&e.id!==attemptId))throw new UsageError("Reconcile the observed outcome of the pending recovery reservation first");let next=ledger;if(next.entries.find(e=>e.id===attemptId)?.status!==void 0&&next.entries.find(e=>e.id===attemptId)?.status!=="reserved")throw new UsageError("An unapplied repair cannot reuse a settled recovery reservation");if(!next.entries.some(e=>e.id===attemptId)){const operation=nextRecoveryOperation(next);if(operation===null||operation==="reconcile")throw new UsageError("Frozen recovery budget is exhausted or requires reconciliation");if(operation==="replan"){const summary=parsed.options["replan-summary"]?.trim();const selection2=replanModel(next.preset,recoveryProgress(next).replans+1);const planner=parsed.options["replan-run"]?await composition.runs.read(parsed.options["replan-run"]):root;if(!summary||!ownedRuns.has(planner.run.run_id)||planner.run.task_id!==id||planner.run.execution_id!==root.run.execution_id||planner.run.run_id!==root.run.run_id&&planner.status!=="completed"||planner.run.model!==selection2.model||planner.run.reasoning_effort!==selection2.reasoning_effort)throw new UsageError(`Observed replan required: ${selection2.model}/${selection2.reasoning_effort}; no silent model fallback`);next=settleRecovery(reserveRecovery(next,replanId,"replan"),replanId,"completed",summary)}next=reserveRecovery(next,attemptId,"attempt")}const repaired=taskV2Schema.parse({...task,status:"executing",revision:task.revision+1,updated_at:new Date().toISOString()});if(!previous)await fs.writeTextAtomicExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:root.run.run_id,execution_id:root.run.execution_id,validation_id:validationId,commit_sha:validation.commit_sha,previous_revision:task.revision,next_revision:repaired.revision,reason,recovery_attempt_id:attemptId,occurred_at:repaired.updated_at},null,2)}
3643
3643
  `);await store.update(id,ledger.preset,ledger.legacy_attempts,current=>{if(JSON.stringify(current)!==JSON.stringify(ledger))throw new UsageError("Recovery ledger changed before repair");return next});await composition.tasks.write(repaired);return{task:repaired,repair_path:path,recovery_attempt_id:attemptId,reused:false}}async function settleVerificationRepair(parsed,composition){requireOptions(parsed.options,["run","validation","commit","repair","rerun-of"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task settle-repair requires a Task id");const{task}=await composition.tasks.read(id);const root=await composition.runs.read(parsed.options.run);if(root.status!=="running"||root.finalization_decision!=null||root.run.task_id!==id||root.run.agent!=="agent-orchestrator"||root.run.change_id!==task.change_id)throw new UsageError("Settlement requires this Task's active delivery orchestrator before Gui");if(["codex","codex-desktop"].includes(root.run.client)){const observed=await resolveRunClientInvocation(composition.filesystem,root.run.client);if(!observed.clientThreadId||!observed.clientTurnId||observed.clientThreadId!==root.run.client_thread_id||observed.clientTurnId!==root.run.client_turn_id)throw new UsageError("Settlement requires the exact observed Codex thread/turn correlation")}if(!/^[a-f0-9]{24}$/.test(parsed.options.repair)||!/^(?:TEST|CHECK|INT|EVAL|MUT|E2E|REVIEW)-[A-Z0-9-]+$/.test(parsed.options.validation))throw new UsageError("Invalid repair or validation identity");const fs=composition.filesystem;const directory2=composition.changes.path(task.change_id).replace(/\/change\.md$/,"");const receipt=JSON.parse(await fs.readText(`${directory2}/artifacts/rework/verification-${parsed.options.repair}.json`));const validation=parseMarkdown(await fs.readText(`${directory2}/artifacts/tests/${parsed.options.validation}.md`),validationArtifactV2Schema).metadata;if(parsed.options["rerun-of"]!==receipt.validation_id||!/^(?:TEST|CHECK|INT|EVAL|MUT|E2E|REVIEW)-[A-Z0-9-]+$/.test(receipt.validation_id))throw new UsageError("Settlement must identify the exact failed gate being rerun");const failedGate=parseMarkdown(await fs.readText(`${directory2}/artifacts/tests/${receipt.validation_id}.md`),validationArtifactV2Schema).metadata;const runs=await composition.runs.list();assertChildRunMayStart(root,"execution","agent-task-executor",runs,["delivery"]);const owners2=new Set([root.run.run_id,...descendantRuns(root.run.run_id,runs).map(r=>r.run.run_id)]);if(receipt.task_id!==id||receipt.run_id!==root.run.run_id||receipt.execution_id!==root.run.execution_id||!Number.isSafeInteger(receipt.next_revision)||task.revision<receipt.next_revision||!["executing","verifying"].includes(task.status)||validation.task_id!==id||validation.change_id!==task.change_id||validation.execution_id!==root.run.execution_id||!owners2.has(validation.run_id)||validation.commit_sha!==parsed.options.commit||validation.kind!==failedGate.kind||validation.command!==failedGate.command||!failedGate.acceptance_ids.every(ac=>validation.acceptance_ids.includes(ac))||!validation.acceptance_ids.every(ac=>task.acceptance_ids.includes(ac))||validation.status==="not_applicable"||Date.parse(validation.executed_at)<Date.parse(receipt.occurred_at)||activeDescendantRuns(root.run.run_id,runs).length)throw new UsageError("Settlement requires an observed post-repair validation of this Task and candidate");const store=new FileRecoveryLedger(fs);const ledger=await store.read(id);if(!ledger)throw new UsageError("Missing recovery ledger");const settled=await store.update(id,ledger.preset,ledger.legacy_attempts,current=>settleRecovery(current,receipt.recovery_attempt_id,validation.status==="passed"?"completed":"failed",validation.id));return{task,repair_path:`${directory2}/artifacts/rework/verification-${parsed.options.repair}.json`,progress:recoveryProgress(settled)}}var init_task_verification_repair=__esm({"src/task-verification-repair.ts"(){"use strict";init_src();init_src6();init_src7();init_cli_arguments();init_run_client_invocation();init_run_finalization_barrier();init_run_hierarchy()}});import{execFile as execFile22}from"node:child_process";import{createHash as createHash69}from"node:crypto";import{constants as constants2}from"node:fs";import{copyFile,lstat as lstat15,mkdir as mkdir7,mkdtemp as mkdtemp3,readFile as readFile14,realpath as realpath15,rm as rm8}from"node:fs/promises";import{dirname as dirname13,isAbsolute as isAbsolute13,join as join8,relative as relative14,resolve as resolve21,sep as sep6}from"node:path";import{promisify as promisify22}from"node:util";async function maybeCloseTerminalTaskWorkspace(filesystem,composition,runId,result2){if(!runId)return result2;const folded=await composition.runs.read(runId);const taskId=folded.run.task_id;if(folded.finished===null||folded.run.parent_run_id!==null||!taskId||!await filesystem.exists(`.local/task-workspaces/claims/${taskId}.json`))return result2;const cleanup=await closeTaskWorkspace(filesystem,composition,taskId,runId);return{...result2,workspace_cleanup:cleanup}}async function closeTaskWorkspace(filesystem,composition,taskId,runId,operations={}){if(!/^TASK-[A-Z0-9-]+$/.test(taskId)||!/^RUN-[A-Z0-9-]+$/.test(runId))throw new UsageError("Closing a Task workspace requires exact Task and Run ids");return withLifecycleCanonicalMutationLock(filesystem,async()=>{const root=resolve21(filesystem.root);const primary=resolve21(await git5(root,["rev-parse","--show-toplevel"]));const common=resolve21(await git5(root,["rev-parse","--path-format=absolute","--git-common-dir"]));if(root!==primary||common!==resolve21(root,".git"))throw new UsageError("Close the Task workspace from its primary Git checkout");const{task}=await composition.tasks.read(taskId);const{run,finished}=await composition.runs.read(runId);if(!["completed","failed","blocked","cancelled"].includes(task.status)||finished===null||run.task_id!==taskId||!run.execution_id||activeDescendantRuns(runId,await composition.runs.list()).length)throw new UsageError("Workspace closure requires a terminal exact Task Run with no active descendants");const claim=await readReadyTaskWorkspaceClaim(filesystem,taskId,run.execution_id,runId);if(!claim?.path||!claim.branch||claim.mode==="shared")throw new UsageError("No isolated Task workspace is ready to close");const expected=new GitAutonomousWorktreePort(root,".local/task-workspaces/trees").describeTaskWorkspace(run.execution_id,taskId);if(resolve21(claim.path)!==resolve21(expected.path)||claim.branch!==expected.branch)throw new UsageError("Isolated workspace claim differs from the registered Task front");const branchTip=await git5(root,["rev-parse",claim.branch]);const worktreeTip=await git5(claim.path,["rev-parse","HEAD"]);if(branchTip!==worktreeTip)throw new UsageError("Task branch moved away from its workspace");if(task.status==="completed"){const merged=await git5(root,["merge-base","--is-ancestor",branchTip,"HEAD"]).then(()=>true,()=>false);if(!merged)throw new UsageError("Completed Task branch must be integrated before closure")}const ignored=(await git5(claim.path,["ls-files","-o","-i","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const unknownIgnored=ignored.filter(path=>!discardableIgnored(path));if(unknownIgnored.length)throw new UsageError("Workspace has ignored files outside known disposable caches; inspect them before archival cleanup");const branchRelative=`.local/backup-branchs/${taskId}/${runId}.bundle`;const worktreeRelative=`.local/backup-worktrees/${taskId}/${runId}`;const bundle=resolve21(root,branchRelative);const backup=resolve21(root,worktreeRelative);assertChild(resolve21(root,".local/backup-branchs"),bundle);assertChild(resolve21(root,".local/backup-worktrees"),backup);const receiptPath2=`${worktreeRelative}/manifest.json`;if(await filesystem.exists(receiptPath2))throw new UsageError("Existing backup receipt requires manual inspection before retry");if(await filesystem.exists(branchRelative)||await filesystem.exists(worktreeRelative))throw new UsageError("Partial Task backup already exists; inspect it before retry");await mkdir7(dirname13(bundle),{recursive:true});await mkdir7(join8(backup,"files"),{recursive:true});for(const directory2 of[dirname13(bundle),backup,join8(backup,"files")]){const info=await lstat15(directory2);if(!info.isDirectory()||info.isSymbolicLink()||resolve21(await realpath15(directory2))!==directory2)throw new UsageError("Task backup directory is not a verified physical directory")}await git5(root,["bundle","create",bundle,claim.branch]);await git5(root,["bundle","verify",bundle]);const bundleSha=digest11(await readFile14(bundle));const entries=(await git5(claim.path,["ls-files","-c","-o","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const files=[];for(const path of entries){const source=resolve21(claim.path,path);const target=resolve21(backup,"files",path);assertChild(claim.path,source);assertChild(resolve21(backup,"files"),target);const info=await lstat15(source);if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1)throw new UsageError(`Workspace snapshot contains an unsafe file: ${path}`);await mkdir7(dirname13(target),{recursive:true});if(resolve21(await realpath15(dirname13(target)))!==dirname13(target))throw new UsageError("Task backup destination traverses a link");await copyFile(source,target,constants2.COPYFILE_EXCL);const sha2568=digest11(await readFile14(source));if(digest11(await readFile14(target))!==sha2568)throw new UsageError(`Workspace snapshot verification failed: ${path}`);files.push({path:path.replaceAll("\\","/"),sha256:sha2568})}const receipt={schema_version:1,task_id:taskId,execution_id:run.execution_id,run_id:runId,branch:claim.branch,branch_tip:branchTip,bundle_sha256:bundleSha,source_status:await git5(claim.path,["status","--porcelain","-z"]),discarded_ignored:ignored.map(path=>path.replaceAll("\\","/")),files};const probeParent=resolve21(root,".local/backup-worktrees");const probe=await mkdtemp3(join8(probeParent,"restore-probe-"));assertChild(probeParent,probe);try{await git5(root,["clone","--quiet","--no-checkout",branchRelative,relative14(root,probe)]);await git5(probe,["cat-file","-e",`${branchTip}^{commit}`]);for(const entry2 of files){if(digest11(await readFile14(resolve21(backup,"files",entry2.path)))!==entry2.sha256)throw new UsageError(`Workspace restore probe failed: ${entry2.path}`)}}finally{await rm8(probe,{recursive:true,force:true})}await filesystem.writeTextAtomicExclusive(receiptPath2,`${JSON.stringify(receipt,null,2)}
3644
3644
  `);await operations.beforeRemove?.();const currentTask=(await composition.tasks.read(taskId)).task;const currentRun=await composition.runs.read(runId);if(currentTask.status!==task.status||currentRun.finished===null||currentRun.run.task_id!==taskId||currentRun.run.execution_id!==run.execution_id||activeDescendantRuns(runId,await composition.runs.list()).length)throw new UsageError("Task ownership or terminal state changed after backup");const currentClaim=await readReadyTaskWorkspaceClaim(filesystem,taskId,run.execution_id,runId);if(JSON.stringify(currentClaim)!==JSON.stringify(claim))throw new UsageError("Task workspace ownership changed after backup");const claimedPath=claim.path;const registered=await git5(root,["worktree","list","--porcelain"]);if(!registered.split(/\r?\n\r?\n/).some(block2=>{const lines2=block2.split(/\r?\n/);return lines2.some(line=>line.startsWith("worktree ")&&resolve21(line.slice(9))===resolve21(claimedPath))&&lines2.includes(`branch refs/heads/${claim.branch}`)&&lines2.includes(`HEAD ${branchTip}`)})||await git5(claim.path,["branch","--show-current"])!==claim.branch||await git5(claim.path,["rev-parse","HEAD"])!==branchTip||await git5(root,["rev-parse",claim.branch])!==branchTip||digest11(await readFile14(bundle))!==bundleSha)throw new UsageError("Task branch, worktree or bundle changed after backup");const currentEntries=(await git5(claim.path,["ls-files","-c","-o","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const currentIgnored=(await git5(claim.path,["ls-files","-o","-i","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const currentStatus=await git5(claim.path,["status","--porcelain","-z"]);if(JSON.stringify(currentEntries)!==JSON.stringify(entries)||JSON.stringify(currentIgnored)!==JSON.stringify(ignored)||currentStatus!==receipt.source_status)throw new UsageError("Task worktree contents changed after backup");for(const entry2 of files){const source=resolve21(claim.path,entry2.path);const info=await lstat15(source);if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||digest11(await readFile14(source))!==entry2.sha256||digest11(await readFile14(resolve21(backup,"files",entry2.path)))!==entry2.sha256)throw new UsageError(`Task snapshot changed after backup: ${entry2.path}`)}await git5(root,["worktree","remove",...currentStatus||ignored.length?["--force"]:[],claim.path]);await git5(root,["branch",task.status==="completed"?"-d":"-D",claim.branch]);await filesystem.writeTextAtomic(`.local/task-workspaces/closed/${taskId}.json`,`${JSON.stringify({...receipt,backup_branch:branchRelative,backup_worktree:worktreeRelative})}
3645
3645
  `);await filesystem.removeFileIfContentMatches(`.local/task-workspaces/claims/${taskId}.json`,`${JSON.stringify(claim,null,2)}
@@ -3649,7 +3649,7 @@ ${attempt.run.run_id}`).digest("hex")}});for(const delegation of delegations){co
3649
3649
  `;const receipt={schema_version:1,action,payload,decision_id:decisionId,decision_scope_type:context2.decisionScopeType,decision_scope_id:context2.decisionScopeId,path:cyclePath6,original_source:originalSource,target_source:targetSource,original_sha256:digest6(originalSource),target_sha256:digest6(targetSource)};await filesystem.writeTextAtomicExclusive(receiptPath2,`${JSON.stringify(receipt)}
3650
3650
  `);if(digest6(await filesystem.readText(cyclePath6))!==receipt.original_sha256)throw new UsageError("Release cycle changed after journal creation");const refreshed=await recoveryContext(filesystem,composition,actorTaskId,actorRunId,targetTaskId,actorExecutionId);if(refreshed.stateSha256!==context2.stateSha256)throw new UsageError("Recovery state changed before grant application");if(renew)await assertRenewableGrant(await readReleaseCycle(filesystem),refreshed,composition);await filesystem.writeTextAtomic(cyclePath6,targetSource);return{journal_path:receiptPath2,authorization_payload:payload,applied:true,target_status:"blocked",original_sha256:receipt.original_sha256,target_sha256:receipt.target_sha256,requires:"release-refreeze-and-candidate-requalification"}}var init_controlled_recovery_command=__esm({"src/controlled-recovery-command.ts"(){"use strict";init_src();init_src6();init_cli_arguments();init_controlled_recovery_authority();init_controlled_recovery_journal();init_controlled_recovery_renewal();init_controlled_recovery_snapshot();init_release_cycle()}});function macroExecutionContinuation(executionId){return{required:true,execution_id:executionId,implementation_started:false,user_confirmation_required:false,instruction:"Continue execution now using the configured runtime or native DAG orchestration. Materialization and activation do not implement the product. Do not end the turn or ask the user to continue after preparation; run eligible Tasks and then parental verification and finalization. Recover from eligible failures automatically under the frozen Task autonomy profile and ledger, without resetting counters or requesting renewed permission. Wait for active work instead of ending the flow. Stop only for a real blocker, human cancellation, or a terminal failure after permitted recovery; preserve scope, authority and the DAG failure policy."}}var init_macro_execution_continuation=__esm({"src/macro-execution-continuation.ts"(){"use strict"}});async function resolveTaskFirstExecutionId(explicitExecutionId,taskId,listExecutions){if(explicitExecutionId!==void 0)return explicitExecutionId;const deliveryIntake=(await listExecutions()).find(execution=>execution.kind==="delivery"&&execution.plan_hash===null&&execution.origin.type==="task"&&execution.origin.task_id===taskId);return deliveryIntake?.id}function assertTaskFirstExecutable(status,kind,id){if(status==="planned"||status==="executing"||status==="running")return;const guidance=status==="blocked"?"resume the Task before starting a new orchestrator agent call":status==="failed"?"rework the Task before starting a new orchestrator agent call":"terminal work is immutable";throw new UsageError(`${kind} ${id} cannot execute from status ${status}; ${guidance}`)}async function existingTaskFirstMaterialization(plan,composition){if(plan.source.type!=="task")return null;const existing=await Promise.all([composition.tasks.read(plan.source.task_id).catch(()=>null),composition.executions.read(plan.execution_id).catch(()=>null)]);const task=existing[0]?.task;const execution=existing[1]?.execution;if(task===void 0||execution===void 0||task.plan_hash!==plan.hash||execution.plan_hash!==plan.hash||!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){return null}const change=await composition.changes.read(task.change_id).catch(()=>null);if(change===null||change.change.plan_hash!==plan.hash)return null;const reusedPaths=[composition.executions.path(execution.id),composition.changes.path(change.change.id),composition.tasks.path(task.id)];return{execution,changes:[change.change],tasks:[task],created_paths:[],reused_paths:reusedPaths}}async function ensureTaskOrchestratorRun(task,changeId,executionId,parsed,filesystem,composition){const runs=await composition.runs.list();const existing=runs.filter(candidate=>candidate.finished===null&&effectiveRunV2Role(candidate.run)==="orchestrator"&&candidate.run.parent_run_id===null&&candidate.run.task_id===task.id&&candidate.run.execution_id===executionId).sort((left,right)=>right.run.occurred_at.localeCompare(left.run.occurred_at))[0];if(existing!==void 0)return existing.run;const invocation2=await resolveRunClientInvocation(filesystem,"codex");const intake2=await findIntakeForExactTurn(composition,"codex",invocation2);if(invocation2.clientTurnId!==null){await composition.executions.claimClientTurn(executionId,invocation2.clientTurnId)}const source=intake2?.run;const developerIdentity=await resolveDeveloperIdentityForRoot(filesystem);const writer=await composition.runs.start({...parsed.options.run===void 0?{}:{id:parsed.options.run},shortName:task.short_name,phase:"execution",runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:true,executionKind:"delivery",executionEligibility:[],entrypoint:"task",workType:source?.work_type??"new",client:"codex",agent:"agent-orchestrator",agentName:"zaip-agent-orchestrator",provider:source?.provider??null,model:parsed.options.model??source?.model??"unknown",reasoningEffort:source?.reasoning_effort??null,...invocation2,conversationId:source?.conversation_id??createConversationId(task.short_name),executionId,taskId:task.id,changeId,developerIdentity});return writer.started}async function ensureTaskDraftChange(composition,task){const existing=await composition.changes.read(task.change_id).catch(()=>null);if(existing!==null)return existing.change;return composition.changes.createDraft({id:task.change_id,title:task.title,risk:task.risk,taskId:task.id,requirementIds:task.requirement_ids,acceptanceIds:task.acceptance_ids})}function plannedChangeFromBlueprint(blueprint,plan,taskId){return{schema_version:2,id:blueprint.id,revision:1,title:blueprint.title,status:"planned",risk:blueprint.risk,source:blueprint.source,requirement_ids:[...blueprint.requirement_ids],acceptance_ids:[...blueprint.acceptance_ids],requirement_impact:blueprint.requirement_impact,task_ids:[taskId],plan_revision:plan.revision,plan_hash:plan.hash,created_at:plan.prepared_at,updated_at:plan.prepared_at,started_at:null,finished_at:null,result:null}}function materializationOutput(result2,composition,continueExecution=false){return{execution:result2.execution,...continueExecution?{continuation:macroExecutionContinuation(result2.execution.id)}:{},changes:result2.changes,tasks:result2.tasks,artifact_path:composition.executions.path(result2.execution.id),change_paths:result2.changes.map(change=>composition.changes.path(change.id)),task_paths:result2.tasks.map(task=>composition.tasks.path(task.id)),created_paths:result2.created_paths,reused_paths:result2.reused_paths}}async function preparedPlanForReadyOrExecute(entity,kind,id,materializer){if(entity.prepared_plan!==null)return entity.prepared_plan;if(entity.plan_ref!==null)return materializer.readPreparedPlan(entity.plan_ref.execution_id);throw new UsageError(`${kind} is not prepared: ${id}`)}function executionOutput(result2,composition){return materializationOutput(result2,composition,true)}var init_v2_lifecycle_materialization=__esm({"src/commands/v2-lifecycle-materialization.ts"(){"use strict";init_src5();init_cli_arguments();init_conversation_intake();init_developer_identity_command();init_macro_execution_continuation();init_run_client_invocation()}});import{execFile as execFile23}from"node:child_process";import{lstat as lstat16}from"node:fs/promises";import{resolve as resolve22}from"node:path";import{promisify as promisify23}from"node:util";function message(error51){return error51 instanceof Error?error51.message:String(error51)}async function check2(blockers,rule,command2,humanAction,inspect){try{await inspect()}catch(error51){blockers.push({rule,state:message(error51),command:command2,human_action:humanAction})}}async function inspectDefinitionPreflight(entity,id,filesystem,composition){const blockers=[];const recovery=[];const record3=entity==="SPEC"?(await composition.specs.read(id)).spec:(await composition.prds.read(id)).prd;await check2(blockers,"RELEASE_CURRENT",`${entity.toLowerCase()} show ${id}`,null,()=>assertCurrentReleaseForExecution(filesystem,record3.target_release,entity));if(!new Set(["draft","ready"]).has(record3.status)){blockers.push({rule:"DEFINITION_STATUS",state:`${entity} status is ${record3.status}`,command:`${entity.toLowerCase()} show ${id}`,human_action:null})}let plan=null;await check2(blockers,"PREPARED_PLAN",`${entity.toLowerCase()} prepare ${id} --plan <path>`,null,async()=>{plan=await preparedPlanForReadyOrExecute(record3,entity,id,composition.materializer)});if(plan!==null){const prepared=plan;await check2(blockers,"PLAN_REFERENCES",`plan validate --plan <path>`,null,()=>assertPreparedPlanReferences(filesystem,prepared));if(entity==="PRD"){for(const specId of specIdsForPrdPlanV2(prepared,id)){await check2(blockers,"SELECTED_SPEC",`spec show ${specId}`,null,async()=>{const{spec}=await composition.specs.read(specId);await assertCurrentReleaseForExecution(filesystem,spec.target_release,"SPEC");if(!new Set(["draft","ready"]).has(spec.status))throw new Error(`SPEC status is ${spec.status}: ${specId}`);await assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout)})}}}if(entity==="SPEC"){const spec=record3;await check2(blockers,"STACK_PROFILE",`spec show ${id}`,null,()=>assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout))}await inspectWriter(filesystem,composition,blockers,recovery);await inspectGitLock(filesystem,blockers);return{kind:"definition_preflight",entity,id,allowed:blockers.length===0,blockers,recovery}}function assertDefinitionPreflight(report){if(report.allowed)return;throw new UsageError(`Definition preflight blocked before materialization: ${JSON.stringify(report.blockers)}`)}async function inspectWriter(filesystem,composition,blockers,recovery){const path=".local/task-workspaces/shared-writer.json";if(!await filesystem.exists(path))return;await check2(blockers,"WRITER_CLAIM","task workspace <TASK-ID> --run <RUN-ID>",null,async()=>{const claim=JSON.parse(await filesystem.readText(path));if(claim.mode!=="shared"||claim.status!=="ready"||typeof claim.run_id!=="string"||typeof claim.task_id!=="string"||typeof claim.execution_id!=="string")throw new Error("Shared writer claim is incomplete; inspect before recovery");const owner=await composition.runs.read(claim.run_id);if(owner.run.task_id!==claim.task_id||owner.run.execution_id!==claim.execution_id)throw new Error("Shared writer claim does not match its Run");if(owner.finished===null)throw new Error(`Shared checkout is owned by active Run ${claim.run_id}`);recovery.push({rule:"WRITER_TERMINAL",state:`Previous writer ${claim.run_id} is terminal; transfer requires an active new Task Run and preserved product changes`,command:"task workspace <TASK-ID> --run <RUN-ID>",human_action:null})})}async function inspectGitLock(filesystem,blockers){if(!await filesystem.exists(".git"))return;await check2(blockers,"GIT_INDEX_LOCK","git-lock recover --task <TASK-ID> --run <RUN-ID> --decision <DEC-HUMAN-ID>","A confirmed human Decision for the exact inert index.lock is required before recovery",async()=>{const{stdout}=await execute2("git",["-C",filesystem.root,"rev-parse","--path-format=absolute","--absolute-git-dir"],{cwd:filesystem.root,windowsHide:true,timeout:5e3});const lock2=resolve22(stdout.trim(),"index.lock");try{await lstat16(lock2)}catch(error51){if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return;throw error51}throw new Error(`Git index.lock exists at ${lock2}; recovery checks age, process inventory and backup before moving it`)})}var execute2;var init_definition_preflight=__esm({"src/definition-preflight.ts"(){"use strict";init_src6();init_cli_arguments();init_v2_lifecycle_materialization();init_prepared_plan_v22();init_release_cycle();execute2=promisify23(execFile23)}});import{createHash as createHash70}from"node:crypto";async function inspectSameTurnSpecHandoff(spec,composition,filesystem){const invocation2=await resolveRunClientInvocation(filesystem,"codex");if(invocation2.clientThreadId===null||invocation2.clientTurnId===null)return null;const roots2=(await composition.runs.list()).filter(fold=>fold.run.parent_run_id===null&&fold.run.client_thread_id===invocation2.clientThreadId&&fold.run.client_turn_id===invocation2.clientTurnId&&(fold.run.client==="codex"||fold.run.client==="codex-desktop"));if(roots2.length===0)return null;const predecessor=roots2.find(fold=>fold.run.intake?.reason_codes.includes("definition-spec-authorized")===true);if(predecessor===void 0&&roots2.length===1)return null;if(predecessor===void 0||roots2.length>2){throw new UsageError("Exact turn is owned by another Run; SPEC handoff is unavailable")}const creation=spec.creation_run_id===null?null:await composition.runs.read(spec.creation_run_id).catch(()=>null);if(creation===null||creation.finished?.status!=="completed"||creation.run.run_id!==predecessor.run.run_id&&creation.run.parent_run_id!==predecessor.run.run_id||predecessor.finished?.status!=="completed"||predecessor.finalization_decision?.outcome!=="completed"||predecessor.run.execution_kind!=="interaction"||predecessor.run.intake?.classification_source!=="explicit"||predecessor.run.execution_id===null){throw new UsageError("SPEC handoff requires its completed definition and Gui decision")}const authored=(await composition.specs.list()).filter(candidate=>candidate.creation_run_id===spec.creation_run_id);const authorizationSha256=explicitSpecExecuteAuthorization(invocation2.userMessage,spec.id,spec.title,authored.length===1);if(authorizationSha256===null){throw new UsageError("SPEC handoff requires an observed explicit execute request for this SPEC")}const successor=roots2.find(fold=>fold.run.run_id!==predecessor.run.run_id)??null;if(successor!==null&&(successor.run.continuation_of_run_id!==predecessor.run.run_id||successor.run.same_turn_handoff?.predecessor_run_id!==predecessor.run.run_id||successor.run.same_turn_handoff.target_spec_id!==spec.id||successor.run.same_turn_handoff.authorization_sha256!==authorizationSha256||successor.run.execution_kind!=="delivery")){throw new UsageError("Exact turn already has an incompatible delivery owner")}return{predecessor,successor,clientThreadId:invocation2.clientThreadId,clientTurnId:invocation2.clientTurnId,authorizationSha256}}function explicitSpecExecuteAuthorization(message2,specId,shortName,soleAuthoredSpec){if(message2===null)return null;const source=message2.replace(/\r\n?/g,"\n").trim();const first=source.split("\n",1)[0]?.trim()??"";const normalized=first.toLocaleLowerCase("pt-BR");if(!first||first.includes("?")||/^[>"'“]/.test(first)||/\b(n[aã]o|nunca|jamais|never|do not|sem)\b/.test(normalized)||!/^(?:(?:por favor|please),?\s+)?(?:(?:pode|favor)\s+)?(?:execute|executar|implemente|implement|inicie a execu[cç][aã]o)\b/.test(normalized))return null;const mentionedIds=first.match(/SPEC-[A-Za-z0-9-]+/g)??[];if(mentionedIds.some(id=>id!==specId))return null;const exact=mentionedIds.includes(specId)||normalized.includes(shortName.toLocaleLowerCase("pt-BR"));if(!exact&&!(soleAuthoredSpec&&/\bspec\b/i.test(first)))return null;return createHash70("sha256").update(source.normalize("NFC"),"utf8").digest("hex")}var init_same_turn_spec_handoff=__esm({"src/same-turn-spec-handoff.ts"(){"use strict";init_cli_arguments();init_run_client_invocation()}});async function retargetOwnerSpecRelease(filesystem,composition,input){const cycle=await readReleaseCycle(filesystem);if(cycle?.state!=="open"||cycle.current_release!==input.to)throw new UsageError("SPEC retarget requires the adopted open release cycle");const raw=JSON.parse(await filesystem.readText(".agents/config/release-cycle.json"));const adoption=raw.history?.at(-1);if(adoption?.mode!=="published-legacy-adoption"||adoption.from!==input.from||adoption.to!==input.to||adoption.owner_spec_id!==input.specId||adoption.actor_run_id!==input.actorRunId||!/^[a-f0-9]{40}$/i.test(adoption.main_sha??"")||!Number.isFinite(Date.parse(adoption.adopted_at??"")))throw new UsageError("SPEC retarget does not match the canonical adoption record");const{spec}=await composition.specs.read(input.specId);const{execution}=await composition.executions.read(adoption.owner_execution_id);const{task:releaseTask}=await composition.tasks.read(adoption.release_task_id);const actor=await composition.runs.read(input.actorRunId);const macro=await composition.runs.read(adoption.owner_run_id);const actorTaskId=actor.run.task_id;if(spec.status!=="active"||spec.target_release!==input.from||spec.plan_ref?.execution_id!==execution.id||spec.plan_ref?.hash!==execution.plan_hash||execution.status!=="running"||execution.origin.type!=="spec"||execution.origin.spec_id!==spec.id||!execution.dag.nodes.some(node=>node.task_id===actorTaskId)||!execution.dag.nodes.some(node=>node.task_id===releaseTask.id)||releaseTask.status!=="planned"||actor.status!=="running"||actor.run.entrypoint!=="task"||actor.run.agent!=="agent-orchestrator"||actor.run.run_role!=="subagent"||actor.run.parent_run_id!==macro.run.run_id||actor.run.spec_id!==spec.id||actor.run.execution_id!==execution.id||macro.status!=="running"||macro.run.entrypoint!=="spec"||macro.run.agent!=="agent-orchestrator"||macro.run.parent_run_id!==null||macro.run.spec_id!==spec.id||macro.run.execution_id!==execution.id)throw new UsageError("SPEC retarget actor, macro Run and DAG lineage do not match");const specAfter=await composition.specs.retargetPublishedRelease(spec.id,{from:input.from,to:input.to,adoptionMainSha:adoption.main_sha,actorRunId:input.actorRunId,adoptedAt:adoption.adopted_at});return{spec:specAfter,artifact_path:composition.specs.path(spec.id)}}var init_spec_release_retarget=__esm({"src/spec-release-retarget.ts"(){"use strict";init_cli_arguments();init_release_cycle()}});import{createHash as createHash71,randomBytes as randomBytes2}from"node:crypto";function lifecycleActionAlias(area,action){if(action===void 0)return action;const normalized=action.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase();if(area==="prd"||area==="spec"){if(["pronto","pronto-para-executar","ready-to-execute"].includes(normalized))return"ready";if(["finalizar","finalize","concluir","conclude"].includes(normalized))return"finalize"}return normalized}function resolveMacroFinalizeAction(status){if(status==="draft"||status==="ready")return"ready";if(status==="active"||status==="verifying")return"continue";return null}function maxCostUsdOption(value){if(value===void 0)return null;const parsed=Number(value);if(!Number.isFinite(parsed)||parsed<0){throw new UsageError("--max-cost-usd must be a non-negative number")}return parsed}async function finalizeMacro(area,parsed,composition,makeReady){const id=requiredEntityId(parsed,2,`${area.toUpperCase()} id`);const entity=area==="prd"?(await composition.prds.read(id)).prd:(await composition.specs.read(id)).spec;const resolution=resolveMacroFinalizeAction(entity.status);if(resolution==="ready")return makeReady();if(resolution==="continue"){return{[area]:entity,next_action:"continue",message:`${area.toUpperCase()} ${id} remains active; finish its Tasks and parent gates before deliver`}}throw new UsageError(`${area.toUpperCase()} ${id} cannot finalize from status ${entity.status}`)}async function createPrdWithOptionalPlan(input){const{parsed,filesystem,composition,creationRunId}=input;requireOptions(parsed.options,["title","short-name","problem"]);const plan=parsed.options.plan===void 0?null:await readPreparedPlan(filesystem,parsed);if(plan!==null&&plan.blueprints.specs===void 0){throw new UsageError("Composite PRD creation requires technical SPEC blueprints; create canonical SPECs first, then use prd prepare for legacy plans")}if(plan!==null&&parsed.options.id===void 0){throw new UsageError("Composite PRD creation requires --id matching the PreparedPlan source")}if(plan!==null&&(plan.source.type!=="prd"||plan.source.prd_id!==parsed.options.id)){throw new UsageError(`Composite PRD plan must have source prd ${parsed.options.id}`)}const specIds=plan===null?[]:specIdsForPrdPlanV2(plan,parsed.options.id);const specCreationRunId=plan===null?null:await assertActiveDefinitionRun({area:"spec",runId:parsed.options["spec-run"]??null,filesystem,composition});if(plan!==null){await assertPreparedPlanReferences(filesystem,plan);await Promise.all((plan.blueprints.specs??[]).map(blueprint=>assertSpecImplementationMatchesProject(blueprint.implementation,filesystem,composition.layout)));const occupied=await Promise.all([filesystem.exists(composition.prds.path(parsed.options.id)),...specIds.map(id=>filesystem.exists(composition.specs.path(id)))]);if(occupied.some(Boolean)){throw new UsageError("Composite PRD creation requires unused PRD and SPEC artifact ids")}}const prd=await composition.prds.create({...parsed.options.id===void 0?{}:{id:parsed.options.id},title:parsed.options.title,targetRelease:await releaseTargetForDraft(filesystem,parsed.options["target-release"]),shortName:parsed.options["short-name"],problem:parsed.options.problem,audiences:csvOption(parsed.options.audiences),outcomes:csvOption(parsed.options.outcomes),constraints:csvOption(parsed.options.constraints),nonGoals:csvOption(parsed.options["non-goals"]),creationRunId});if(plan===null)return{prd,artifact_path:composition.prds.path(prd.id)};const createdFiles=new Map([[composition.prds.path(prd.id),await filesystem.readText(composition.prds.path(prd.id))]]);const specBlueprints=new Map((plan.blueprints.specs??[]).map(blueprint=>[blueprint.id,blueprint]));try{const specs=[];for(const specId of specIds){const blueprint=specBlueprints.get(specId);if(blueprint===void 0){throw new UsageError(`Composite PRD plan lacks technical SPEC blueprint ${specId}`)}const spec=await composition.specs.create({id:specId,prdId:prd.id,title:blueprint.title,targetRelease:prd.target_release,shortName:blueprint.short_name,objective:blueprint.objective,includedScope:blueprint.included_scope,excludedScope:blueprint.excluded_scope,requirementIds:blueprint.requirement_ids,acceptanceIds:blueprint.acceptance_ids,implementation:blueprint.implementation,creationRunId:specCreationRunId});specs.push(spec);const path=composition.specs.path(spec.id);createdFiles.set(path,await filesystem.readText(path))}const prepared=await composition.prds.setPreparedPlan(prd.id,plan);return{prd:prepared,specs,artifact_path:composition.prds.path(prepared.id),plan_hash:plan.hash,spec_blueprints:plan.blueprints.specs,materialized:false}}catch(error51){const recovered=await rollbackCompositeCreation(filesystem,createdFiles);if(recovered.length>0){throw new AggregateError([error51],`Composite PRD creation rolled back; concurrent edits were preserved at ${recovered.join(", ")}`)}throw error51}}async function createPrdRework(input){const{parsed,composition,creationRunId}=input;requireOptions(parsed.options,["title","short-name","problem"]);const sourceId=requiredPosition(parsed.positionals,2,"Cancelled PRD id");const prd=await composition.prds.createReworkSuccessor(sourceId,{...parsed.options.id===void 0?{}:{id:parsed.options.id},title:parsed.options.title,...parsed.options["target-release"]===void 0?{}:{targetRelease:parsed.options["target-release"]},shortName:parsed.options["short-name"],problem:parsed.options.problem,audiences:csvOption(parsed.options.audiences),outcomes:csvOption(parsed.options.outcomes),constraints:csvOption(parsed.options.constraints),nonGoals:csvOption(parsed.options["non-goals"]),creationRunId});return{prd,artifact_path:composition.prds.path(prd.id),rework_of_prd_id:sourceId}}async function createSpecWithOptionalPlan(input){const{parsed,filesystem,composition,creationRunId}=input;requireOptions(parsed.options,["title","short-name","objective"]);const plan=parsed.options.plan===void 0?null:await readPreparedPlan(filesystem,parsed);if(plan!==null&&parsed.options.id===void 0){throw new UsageError("Composite SPEC creation requires --id matching the PreparedPlan source")}if(plan!==null&&(plan.source.type!=="spec"||plan.source.spec_id!==parsed.options.id)){throw new UsageError(`Composite SPEC plan must have source spec ${parsed.options.id}`)}const sourceSpecId=plan?.source.type==="spec"?plan.source.spec_id:null;const blueprint=plan===null||sourceSpecId===null?null:(plan.blueprints.specs??[]).find(candidate=>candidate.id===sourceSpecId);if(plan!==null){if(blueprint===void 0||blueprint===null){throw new UsageError(`Composite SPEC plan lacks technical SPEC blueprint ${sourceSpecId}`)}await assertPreparedPlanReferences(filesystem,plan);await assertSpecImplementationMatchesProject(blueprint.implementation,filesystem,composition.layout);if(await filesystem.exists(composition.specs.path(parsed.options.id))){throw new UsageError("Composite SPEC creation requires an unused SPEC artifact id")}}const parentRelease=parsed.options.prd===void 0?null:(await composition.prds.read(parsed.options.prd)).prd.target_release;const requestedRelease=parsed.options["target-release"]??parentRelease??void 0;if(parentRelease!==null&&parsed.options["target-release"]!==void 0&&parsed.options["target-release"]!==parentRelease)throw new UsageError("SPEC target release must match its parent PRD");const spec=await composition.specs.create({...parsed.options.id===void 0?{}:{id:parsed.options.id},...parsed.options.prd===void 0?{}:{prdId:parsed.options.prd},title:blueprint?.title??parsed.options.title,targetRelease:await releaseTargetForDraft(filesystem,requestedRelease),shortName:blueprint?.short_name??parsed.options["short-name"],objective:blueprint?.objective??parsed.options.objective,includedScope:blueprint?.included_scope??csvOption(parsed.options.scope),excludedScope:blueprint?.excluded_scope??csvOption(parsed.options["out-of-scope"]),requirementIds:blueprint?.requirement_ids??csvOption(parsed.options.requirements),acceptanceIds:blueprint?.acceptance_ids??csvOption(parsed.options.acceptance),...blueprint===null||blueprint===void 0?{}:{implementation:blueprint.implementation},creationRunId});if(plan===null)return{spec,artifact_path:composition.specs.path(spec.id)};const path=composition.specs.path(spec.id);const original=await filesystem.readText(path);try{const prepared=await composition.specs.setPreparedPlan(spec.id,plan);return{spec:prepared,artifact_path:composition.specs.path(prepared.id),plan_hash:plan.hash,materialized:false}}catch(error51){const recovered=await rollbackCompositeCreation(filesystem,new Map([[path,original]]));if(recovered.length>0){throw new AggregateError([error51],`Composite SPEC creation rolled back; concurrent edits were preserved at ${recovered.join(", ")}`)}throw error51}}async function rollbackCompositeCreation(filesystem,createdFiles){const recovered=[];for(const[path,original]of createdFiles){if(!await filesystem.exists(path))continue;const digest14=createHash71("sha256").update(`${path}\0${randomBytes2(16).toString("hex")}`).digest("hex").slice(0,24);const recoveryPath=`.local/recovery/composite-create/${digest14}.md`;await filesystem.moveFileAtomic(path,recoveryPath);if(await filesystem.readText(recoveryPath)===original){await filesystem.removeFile(recoveryPath)}else recovered.push(recoveryPath)}return recovered}var init_v2_lifecycle_support=__esm({"src/commands/v2-lifecycle-support.ts"(){"use strict";init_src6();init_cli_arguments();init_prepared_plan_v22();init_release_cycle();init_definition_run_gate()}});function taskFirstCommandPlan(task,parsed,executionId,timeZone){return createTaskFirstPreparedPlan({task,modelSignals:taskModelSignalsOption(parsed.options["model-signals"]),executionId:executionId??createId("RUN",task.short_name,{timeZone}).replace(/^RUN-/,"EXEC-"),preparedAt:new Date().toISOString(),policy:defaultExecutionPolicy(task.risk,{independent_branches:parsed.flags.has("independent-branches"),max_cost_usd:maxCostUsdOption(parsed.options["max-cost-usd"])}),...parsed.options["requirement-impact"]===void 0?{}:{requirementImpactReason:parsed.options["requirement-impact"]}})}var init_task_first_command_plan=__esm({"src/task-first-command-plan.ts"(){"use strict";init_src();init_v2_lifecycle_support();init_prepared_plan_v22();init_run_budget()}});async function runTaskStartCommand(id,mode,composition,lifecycle){const snapshot=await lifecycle.startTaskWithSnapshot(id,mode);return{...snapshot,artifact_path:composition.tasks.path(id)}}var init_task_start_command=__esm({"src/task-start-command.ts"(){"use strict"}});import{createHash as createHash72}from"node:crypto";async function retargetOpenTaskRelease(parsed,filesystem,composition){requireOptions(parsed.options,["run","from","to","expected-revision"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task retarget-open-release requires a Task id");const{from,to}=parsed.options;const revision=Number(parsed.options["expected-revision"]);if(!/^[1-9]\d*\.(?:0|[1-9]\d*)$/.test(from??"")||to!==`${Number(from?.split(".")[0])+1}.0`||!Number.isSafeInteger(revision)||revision<1)throw new UsageError("Retarget requires the next explicit major .0 and exact Task revision");const{task}=await composition.tasks.read(id);const actor=await composition.runs.read(parsed.options.run);const execution=await executionForTask(task,composition);const invocation2=await resolveRunClientInvocation(filesystem,actor.run.client);if(actor.status!=="running"||actor.finalization_decision!=null||actor.run.parent_run_id!==null||actor.run.agent!=="agent-orchestrator"||actor.run.run_role!=="orchestrator"||actor.run.execution_kind!=="delivery"||actor.run.task_id!==id||actor.run.change_id!==task.change_id||actor.run.execution_id!==execution.id||execution.status!=="running"||execution.origin.type!=="task"||execution.origin.task_id!==id||execution.dag.nodes.length!==1||task.status!=="executing"||task.plan_hash!==execution.plan_hash||!invocation2.clientThreadId||!invocation2.clientTurnId||invocation2.clientThreadId!==actor.run.client_thread_id||invocation2.clientTurnId!==actor.run.client_turn_id)throw new UsageError("Retarget requires this Task's active observed delivery root");if(!task.write_scopes.some(scope=>[cyclePath5,".agents/config/**",".agents/**"].includes(scope)))throw new UsageError("Retarget requires release-cycle configuration in the Task write scopes");const cycle=JSON.parse(await filesystem.readText(cyclePath5));if(cycle.schema_version!==1||cycle.state!=="open"||cycle.recovery_grant!=null||!Array.isArray(cycle.history))throw new UsageError("Retarget requires an open cycle without a recovery grant");const request={kind:"planned-major-retarget",from,to,task_id:id,run_id:actor.run.run_id,expected_revision:revision};const path=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework/release-${digest12(request)}.json`;const receipt=await filesystem.exists(path)?JSON.parse(await filesystem.readText(path)):null;const beforeTask=receipt?.previous_task??task;const beforeCycle=receipt?.previous_cycle??cycle;const payload={...request,task_sha256:digest12(beforeTask),cycle_sha256:digest12(beforeCycle)};if(beforeTask.id!==id||beforeTask.revision!==revision||beforeTask.target_release!==from||beforeCycle.current_release!==from||beforeCycle.state!=="open"||beforeCycle.recovery_grant!=null||beforeCycle.history.some(row=>row.from===from||row.from===to))throw new UsageError("Retarget preimage differs from the unpublished open release");if(!parsed.flags.has("apply"))return{applied:false,authorization_payload:payload};requireOptions(parsed.options,["decision"]);const decisionId=parsed.options.decision;await assertRecoveryDecision(composition,"change",task.change_id,decisionId,payload);if(receipt&&(receipt.schema_version!==1||receipt.decision_id!==decisionId||receipt.authorization_sha256!==digest12(payload)||typeof receipt.occurred_at!=="string"||!Number.isFinite(Date.parse(receipt.occurred_at))||Date.parse(receipt.occurred_at)>Date.now()))throw new UsageError("Retarget journal differs from the exact human authorization");const occurredAt=receipt?.occurred_at??new Date().toISOString();const nextTask=taskV2Schema.parse({...beforeTask,target_release:to,revision:revision+1,updated_at:occurredAt});const nextCycle={...beforeCycle,current_release:to,history:[...beforeCycle.history,{...request,decision_id:decisionId,authorization_sha256:digest12(payload),occurred_at:occurredAt}]};if(![digest12(beforeTask),digest12(nextTask)].includes(digest12(task))||![digest12(beforeCycle),digest12(nextCycle)].includes(digest12(cycle)))throw new UsageError("Task or cycle changed; retarget cannot overwrite unrelated work");const competitors=(await composition.tasks.list()).filter(other=>other.id!==id&&[from,to].includes(other.target_release??"")&&!["completed","cancelled","failed","draft"].includes(other.status));if(competitors.length>0)throw new UsageError("Retarget requires resolving other materialized work for this release");if(activeDescendantRuns(actor.run.run_id,await composition.runs.list()).length>0)throw new UsageError("Finish active descendants before retargeting the release");if(!receipt)await filesystem.writeTextAtomicExclusive(path,`${JSON.stringify({schema_version:1,decision_id:decisionId,authorization_sha256:digest12(payload),occurred_at:occurredAt,previous_task:beforeTask,previous_cycle:beforeCycle},null,2)}
3651
3651
  `);if(digest12(cycle)!==digest12(nextCycle))await filesystem.writeTextAtomic(cyclePath5,`${JSON.stringify(nextCycle,null,2)}
3652
- `);if(digest12(task)!==digest12(nextTask))await composition.tasks.write(nextTask);return{applied:true,task:nextTask,current_release:to,amendment_path:path,reused:digest12(task)===digest12(nextTask)&&digest12(cycle)===digest12(nextCycle)}}var cyclePath5,digest12;var init_task_release_retarget=__esm({"src/task-release-retarget.ts"(){"use strict";init_src7();init_cli_arguments();init_controlled_recovery_authority();init_lifecycle_run_attribution();init_run_client_invocation();init_run_hierarchy();cyclePath5=".agents/config/release-cycle.json";digest12=value=>createHash72("sha256").update(JSON.stringify(value)).digest("hex")}});function selectReadyQueueItem(input){const order2=manualPriority(input.priority);const materialized=new Set(input.executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id)));const completed=new Set(input.tasks.filter(task2=>task2.status==="completed").map(task2=>task2.id));const changes=new Map(input.changes.map(change=>[change.id,change]));const byOrder=(left,right)=>{const leftRank=order2.get(left.id);const rightRank=order2.get(right.id);if(leftRank!==void 0||rightRank!==void 0){if(leftRank===void 0)return 1;if(rightRank===void 0)return-1;if(leftRank!==rightRank)return leftRank-rightRank}return left.created_at.localeCompare(right.created_at)||left.id.localeCompare(right.id)};const prd=input.prds.filter(item=>item.status==="ready").sort(byOrder)[0];if(prd!==void 0)return{kind:"prd",id:prd.id};const spec=input.specs.filter(item=>item.status==="ready"&&item.prd_id===null).sort(byOrder)[0];if(spec!==void 0)return{kind:"spec",id:spec.id};const task=input.tasks.filter(item=>{const change=changes.get(item.change_id);return item.status==="planned"&&item.started_at===null&&(item.attempt_count??0)===0&&!materialized.has(item.id)&&item.prepared_plan===void 0!==(item.plan_ref===void 0)&&item.depends_on.every(id=>completed.has(id))&&change?.source.type==="task"&&change.source.task_id===item.id&&change.task_ids.includes(item.id)}).sort(byOrder)[0];return task===void 0?null:{kind:"task",id:task.id}}function manualPriority(value){if(typeof value!=="object"||value===null||!("schema_version"in value))return new Map;const priority2=value;if(priority2.schema_version!==1||!Array.isArray(priority2.item_ids)||!priority2.item_ids.every(id=>typeof id==="string"&&/^(PRD|SPEC|TASK)-[A-Z0-9-]+$/.test(id))||new Set(priority2.item_ids).size!==priority2.item_ids.length)return new Map;return new Map(priority2.item_ids.map((id,index)=>[id,index]))}var init_ready_queue_selection=__esm({"src/ready-queue-selection.ts"(){"use strict"}});async function readyNextItem(filesystem,composition){const priorityPath=".agents/dashboard/work-priority.json";const priorityText=await filesystem.exists(priorityPath)?await filesystem.readText(priorityPath):"null";const[prds,specs,tasks,changes,executions]=await Promise.all([composition.prds.list(),composition.specs.list(),composition.tasks.list(),composition.changes.list(),composition.executions.list()]);let priority2=null;try{priority2=JSON.parse(priorityText)}catch{}const selected=selectReadyQueueItem({prds,specs,tasks,changes,executions,priority:priority2});if(selected===null)return{selected:null,reason:"no_eligible_work"};if(selected.kind==="task"){const task=tasks.find(item=>item.id===selected.id);if(task===void 0)throw new UsageError(`Ready Task disappeared: ${selected.id}`);const plan=task.prepared_plan??(task.plan_ref===void 0?null:await composition.materializer.readPreparedPlan(task.plan_ref.execution_id));if(plan===null||plan.source.type!=="task"||plan.source.task_id!==task.id||plan.hash!==task.plan_hash)throw new UsageError(`Ready Task has an inconsistent PreparedPlan: ${task.id}`);await assertPreparedPlanReferences(filesystem,plan)}else{const entity=selected.kind==="prd"?prds.find(item=>item.id===selected.id):specs.find(item=>item.id===selected.id);if(entity===void 0)throw new UsageError(`Ready item disappeared: ${selected.id}`);const plan=await preparedPlanForReadyOrExecute(entity,selected.kind==="prd"?"PRD":"SPEC",selected.id,composition.materializer);if(selected.kind==="prd"&&(plan.source.type!=="prd"||plan.source.prd_id!==selected.id)||selected.kind==="spec"&&(plan.source.type!=="spec"||plan.source.spec_id!==selected.id))throw new UsageError(`Ready ${selected.kind.toUpperCase()} has an inconsistent PreparedPlan: ${selected.id}`);await assertPreparedPlanReferences(filesystem,plan)}return{selected}}var init_v2_ready_queue=__esm({"src/commands/v2-ready-queue.ts"(){"use strict";init_cli_arguments();init_prepared_plan_v22();init_ready_queue_selection();init_v2_lifecycle_materialization()}});async function runTaskV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="recover-release")return runControlledRecoveryCommand("recover-task-release",parsed,filesystem,composition);if(action==="recover-post-publication")return preparePostPublicationRecovery(parsed,filesystem,composition);if(action==="resume-post-publication")return resumePostPublicationClosure(parsed,filesystem,composition,lifecycle);if(action==="relay-post-publication")return preparePostPublicationRelay(parsed,filesystem,composition,lifecycle);if(action==="authorize-post-publication")return authorizePostPublicationRelay(parsed,filesystem,composition,lifecycle);if(action==="bind-post-publication")return bindPostPublicationRelay(parsed,filesystem,composition);if(action==="ready-next")return readyNextItem(filesystem,composition);if(action==="amend-scopes")return amendTaskScopes(parsed,filesystem,composition);if(action==="retarget-open-release")return retargetOpenTaskRelease(parsed,filesystem,composition);if(action==="create"){requireOptions(parsed.options,["title","short-name","objective","requirements","acceptance"]);const timeZone=composition.layout.project.timezone;const taskId=parsed.options.id??createId("TASK",parsed.options["short-name"],{timeZone});const changeId=parsed.options.change??createId("CHG",parsed.options["short-name"],{timeZone});const requirementIds=csvOption(parsed.options.requirements);const acceptanceIds=csvOption(parsed.options.acceptance);const risk2=riskOption(parsed.options.risk);const shortName=parsed.options["short-name"];const{task,change}=await createTaskAndChangeAtomically(filesystem,composition,{id:taskId,changeId,title:parsed.options.title,shortName,objective:parsed.options.objective,targetRelease:await releaseTargetForDraft(filesystem,parsed.options["target-release"]),risk:risk2,priority:priorityOption(parsed.options.priority),owner:parsed.options.owner??null,requirementIds,acceptanceIds,dependsOn:csvOption(parsed.options["depends-on"]),writeScopes:csvOption(parsed.options["write-scopes"]),assuranceRiskSignals:taskAssuranceRiskSignalsOption(parsed.options["assurance-risk-signals"])});return{task,change,artifact_path:composition.tasks.path(task.id),change_path:composition.changes.path(change.id)}}if(action==="prepare"){const id2=requiredEntityId(parsed,2,"Task id");const current=await composition.tasks.read(id2);if(current.task.status==="planned"&&current.task.prepared_plan!==void 0){await assertPreparedPlanReferences(filesystem,current.task.prepared_plan);return{task:current.task,artifact_path:composition.tasks.path(id2),plan_hash:current.task.prepared_plan.hash}}if(parsed.options.plan===void 0&&current.task.depends_on.length>0){throw new UsageError("task prepare with dependencies requires --plan containing the complete DAG")}const timeZone=composition.layout.project.timezone;const executionId=await resolveTaskFirstExecutionId(parsed.options.execution,current.task.id,()=>composition.executions.list());const plan=parsed.options.plan===void 0?taskFirstCommandPlan(current.task,parsed,executionId,timeZone):await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const task=await composition.tasks.setPreparedPlan(id2,plan);const change=plan.blueprints.changes.find(candidate=>candidate.id===task.change_id);if(change===void 0)throw new UsageError(`Prepared plan does not contain Change ${task.change_id}`);await ensureTaskDraftChange(composition,task);await composition.changes.promoteDraft(task.change_id,plannedChangeFromBlueprint(change,plan,task.id));return{task,artifact_path:composition.tasks.path(id2),plan_hash:plan.hash}}if(action==="recover-intake"){requireOptions(parsed.options,["execution"]);const taskId=requiredEntityId(parsed,2,"Task id");const{task}=await composition.tasks.read(taskId);if(task.status!=="executing"||task.plan_ref===void 0)throw new UsageError(`Task has no active canonical plan reference: ${taskId}`);const plan=await composition.materializer.readPreparedPlan(task.plan_ref.execution_id);if(plan.hash!==task.plan_ref.hash||plan.source.type!=="task"||plan.source.task_id!==task.id)throw new UsageError(`Task plan reference cannot be resolved canonically: ${taskId}`);const intake2=(await composition.executions.read(parsed.options.execution)).execution;if(intake2.kind!=="delivery"||intake2.origin.type!=="task"||intake2.origin.task_id!==task.id)throw new UsageError(`Delivery intake does not belong to Task: ${intake2.id}`);const current=intake2;const nodes=plan.dag.nodes.map(node=>{const blueprint=plan.blueprints.tasks.find(candidate=>candidate.id===node.task_id);if(blueprint===void 0)throw new UsageError(`Prepared plan DAG lacks Task blueprint: ${node.task_id}`);return{task_id:node.task_id,change_id:blueprint.change_id,depends_on:node.depends_on}});const planned={...current,kind:"delivery",status:"planned",status_reason:null,plan_revision:plan.revision,plan_hash:plan.hash,policy:plan.policy,dag:{nodes,topological_order:plan.dag.topological_order}};const execution=await composition.executions.promoteDeliveryIntake(current.id,planned);return{task,execution,artifact_path:composition.executions.path(execution.id),recovered:true}}if(action==="execute"){const requestedTaskId=parsed.positionals[2];const plan=parsed.options.plan!==void 0?await readPreparedPlan(filesystem,parsed):await preparedTaskPlan(composition.tasks,composition.materializer,requiredEntityId(parsed,2,"Task id"));await assertPreparedPlanReferences(filesystem,plan);if(plan.source.type!=="task"){throw new UsageError("task execute requires a task-first prepared plan")}if(requestedTaskId!==void 0&&requestedTaskId!==plan.source.task_id)throw new UsageError("Requested Task does not match the prepared plan source");const currentTask=await composition.tasks.read(plan.source.task_id);await assertCurrentReleaseForExecution(filesystem,currentTask.task.target_release,"Task");if(composition.layout.projectConfig?.assurance?.require_final_commit===true)await assertGitDeliveryReady(filesystem.root);await assertTaskExecutionIntakeCompatibleBeforeMutation(filesystem,composition,plan.source.task_id,plan.execution_id);const materialized=await existingTaskFirstMaterialization(plan,composition)??await composition.materializer.execute(plan);const taskId=plan.source.task_id;const task=materialized.tasks.find(candidate=>candidate.id===taskId);if(task===void 0){throw new UsageError(`Task-first plan did not materialize its source Task ${taskId}`)}const change=materialized.changes.find(candidate=>candidate.id===task.change_id);if(change===void 0){throw new UsageError(`Task-first plan did not materialize Change ${task.change_id}`)}assertTaskFirstExecutable(task.status,"Task",task.id);assertTaskFirstExecutable(materialized.execution.status,"Execution",materialized.execution.id);assertTaskFirstExecutable(change.status,"Change",change.id);const run=await ensureTaskOrchestratorRun(task,change.id,materialized.execution.id,parsed,filesystem,composition);let execution=(await composition.executions.read(materialized.execution.id)).execution;if(execution.status==="planned"){execution=await composition.executions.transition(execution.id,"running")}let activeChange=(await composition.changes.read(change.id)).change;if(activeChange.status==="planned"){activeChange=await composition.changes.transition(activeChange.id,"executing")}let activeTask=(await composition.tasks.read(task.id)).task;if(activeTask.status==="planned"){activeTask=await lifecycle.startTask(activeTask.id)}return{...materializationOutput(materialized,composition),execution,changes:[activeChange],tasks:[activeTask],run,run_path:composition.runs.path(run.run_id)}}if(action==="list"){const[tasks,changes]=await Promise.all([composition.tasks.list(),parsed.options.prd===void 0&&parsed.options.spec===void 0?Promise.resolve([]):composition.changes.list()]);const relatedChangeIds=new Set(changes.filter(change=>(parsed.options.prd===void 0||change.source.type==="prd"&&change.source.prd_id===parsed.options.prd)&&(parsed.options.spec===void 0||change.source.type==="spec"&&change.source.spec_id===parsed.options.spec||change.source.type==="prd"&&change.source.spec_id===parsed.options.spec)).map(change=>change.id));const filtered=tasks.filter(task=>parsed.options.prd===void 0&&parsed.options.spec===void 0||relatedChangeIds.has(task.change_id));return listLifecyclePage(filtered,parsed).map(task=>({task:compactPreparedEntity(task),artifact_path:composition.tasks.path(task.id)}))}if(action==="next"){const[tasks,executions]=await Promise.all([composition.tasks.list(),composition.executions.list()]);const completed=new Set(tasks.filter(task=>task.status==="completed").map(task=>task.id));const materialized=new Set(executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id)));return tasks.filter(task=>task.status==="planned"&&materialized.has(task.id)&&task.depends_on.every(dependency=>completed.has(dependency))).map(task=>({task,artifact_path:composition.tasks.path(task.id)}))}const id=requiredEntityId(parsed,2,"Task id");if(action==="show"){return{...await composition.tasks.read(id),artifact_path:composition.tasks.path(id)}}if(action==="start"||action==="resume"||action==="rework"){return runTaskStartCommand(id,action,composition,lifecycle)}if(action==="verify"){const task=await lifecycle.verifyTask(id,csvOption(parsed.options.evidence));return{task,artifact_path:composition.tasks.path(id)}}if(["block","complete","fail"].includes(action??"")){throw new UsageError("Task terminal status is applied only by Gui through run finish")}if(action==="cancel"){const cancelled_run_ids=await cancelTaskRunsForHuman(id,composition,parsed);const result2=await lifecycle.cancelTask(id,"Explicit human cancellation",null);return{...result2,cancelled_run_ids,artifact_path:composition.tasks.path(id)}}throw new UsageError(`Unknown V2 Task action: ${action??""}`)}var init_v2_lifecycle_task=__esm({"src/commands/v2-lifecycle-task.ts"(){"use strict";init_src();init_cli_arguments();init_controlled_recovery_command();init_execution_intake_compatibility();init_git_delivery_preflight();init_post_publication_recovery();init_post_publication_relay();init_prepared_plan_v22();init_release_cycle();init_v2_run_cancellation_and_aggregate();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_release_retarget();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();init_v2_ready_queue()}});async function runPrdV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="finalize"){return finalizeMacro("prd",parsed,composition,()=>runLifecycleV2Command("prd","ready",parsed,filesystem,composition,lifecycle))}if(action==="create"){const creationRunId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);return createPrdWithOptionalPlan({parsed,filesystem,composition,creationRunId})}if(action==="rework"){return createPrdRework({parsed,composition,creationRunId:await creationRunIdForCurrentTurn(parsed,filesystem,composition)})}if(action==="list"){return listLifecyclePage(await composition.prds.list(),parsed).map(prd=>({prd:compactPreparedEntity(prd),artifact_path:composition.prds.path(prd.id)}))}const id=requiredEntityId(parsed,2,"PRD id");if(action==="preflight")return inspectDefinitionPreflight("PRD",id,filesystem,composition);if(action==="show"){return{...await composition.prds.read(id),artifact_path:composition.prds.path(id)}}if(action==="prepare"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const prd=await composition.prds.setPreparedPlan(id,plan);const specs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));return{prd,specs,artifact_path:composition.prds.path(id),plan_hash:plan.hash}}if(action==="ready"){assertDefinitionPreflight(await inspectDefinitionPreflight("PRD",id,filesystem,composition));const current=await composition.prds.read(id);await assertCurrentReleaseForExecution(filesystem,current.prd.target_release,"PRD");const plan=await preparedPlanForReadyOrExecute(current.prd,"PRD",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.prd.status)){throw new UsageError(`PRD cannot move to ready from status ${current.prd.status}: ${id}`)}const selectedSpecs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));for(const spec of selectedSpecs){await assertCurrentReleaseForExecution(filesystem,spec.target_release,"SPEC");if(!new Set(["draft","ready"]).has(spec.status)){throw new UsageError(`SPEC cannot move to ready from status ${spec.status}: ${spec.id}`)}await assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout)}const materialized=materializationOutput(await composition.materializer.execute(plan),composition);const prd=current.prd.status==="draft"?await composition.prds.transition(id,"ready"):current.prd;const specs=await Promise.all(selectedSpecs.map(spec=>spec.status==="draft"?composition.specs.transition(spec.id,"ready"):spec));return{...materialized,prd,specs,artifact_path:composition.prds.path(id)}}if(action==="execute"){assertDefinitionPreflight(await inspectDefinitionPreflight("PRD",id,filesystem,composition));const current=await composition.prds.read(id);await assertCurrentReleaseForExecution(filesystem,current.prd.target_release,"PRD");const plan=await preparedPlanForReadyOrExecute(current.prd,"PRD",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.prd.status)){throw new UsageError(`PRD cannot execute from status ${current.prd.status}: ${id}`)}const selectedSpecs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));for(const spec of selectedSpecs){await assertCurrentReleaseForExecution(filesystem,spec.target_release,"SPEC");if(!new Set(["draft","ready"]).has(spec.status)){throw new UsageError(`SPEC cannot execute from status ${spec.status}: ${spec.id}`)}await assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout)}const output2=executionOutput(await composition.materializer.execute(plan),composition);const specs=await Promise.all(selectedSpecs.map(async selectedSpec=>{let spec=selectedSpec;if(spec.status==="draft")spec=await composition.specs.transition(spec.id,"ready");return spec.status==="ready"?composition.specs.transition(spec.id,"active"):spec}));if(current.prd.status==="draft")await composition.prds.transition(id,"ready");const preparedPrd=(await composition.prds.read(id)).prd;if(preparedPrd.status==="ready")await composition.prds.transition(id,"active");return{...output2,specs}}if(action==="deliver"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="block"||action==="fail"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="cancel"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="activate"){const prd=await composition.prds.transition(id,"active");return{prd,artifact_path:composition.prds.path(id)}}throw new UsageError(`Unknown V2 PRD action: ${action??""}`)}var init_v2_lifecycle_prd=__esm({"src/commands/v2-lifecycle-prd.ts"(){"use strict";init_src();init_src6();init_attribution_v2();init_cli_arguments();init_controlled_recovery_command();init_conversation_intake();init_definition_preflight();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();init_same_turn_spec_handoff();init_v2_run_cancellation_and_aggregate();init_spec_release_retarget();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle();init_v2_lifecycle_materialization();init_v2_lifecycle_support();init_v2_lifecycle_task();init_v2_ready_queue()}});async function runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle){action=lifecycleActionAlias(area,action);if(area==="prd")return runPrdV2Command(action,parsed,filesystem,composition,lifecycle);if(area==="spec")return runSpecV2Command(action,parsed,filesystem,composition,lifecycle);return runTaskV2Command(action,parsed,filesystem,composition,lifecycle)}async function runSpecV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="revise-implementation")return runControlledRecoveryCommand("revise-spec-implementation",parsed,filesystem,composition);if(action==="finalize"){return finalizeMacro("spec",parsed,composition,()=>runLifecycleV2Command("spec","ready",parsed,filesystem,composition,lifecycle))}if(action==="create"){const creationRunId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);return createSpecWithOptionalPlan({parsed,filesystem,composition,creationRunId})}if(action==="list"){const specs=(await composition.specs.list()).filter(spec=>parsed.options.prd===void 0||spec.prd_id===parsed.options.prd);return listLifecyclePage(specs,parsed).map(spec=>({spec:compactPreparedEntity(spec),artifact_path:composition.specs.path(spec.id)}))}const id=requiredEntityId(parsed,2,"SPEC id");if(action==="preflight")return inspectDefinitionPreflight("SPEC",id,filesystem,composition);if(action==="show"){return{...await composition.specs.read(id),artifact_path:composition.specs.path(id)}}if(action==="retarget-release"){requireOptions(parsed.options,["from","to","run"]);return retargetOwnerSpecRelease(filesystem,composition,{specId:id,from:parsed.options.from,to:parsed.options.to,actorRunId:parsed.options.run})}if(action==="prepare"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const spec=await composition.specs.setPreparedPlan(id,plan);return{spec,artifact_path:composition.specs.path(id),plan_hash:plan.hash}}if(action==="ready"){assertDefinitionPreflight(await inspectDefinitionPreflight("SPEC",id,filesystem,composition));const current=await composition.specs.read(id);await assertCurrentReleaseForExecution(filesystem,current.spec.target_release,"SPEC");const plan=await preparedPlanForReadyOrExecute(current.spec,"SPEC",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.spec.status)){throw new UsageError(`SPEC cannot move to ready from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const materialized=materializationOutput(await composition.materializer.execute(plan),composition);const spec=current.spec.status==="draft"?await composition.specs.transition(id,"ready"):current.spec;return{...materialized,spec,artifact_path:composition.specs.path(id)}}if(action==="execute"){const current=await composition.specs.read(id);const sameTurn=await inspectSameTurnSpecHandoff(current.spec,composition,filesystem);if(sameTurn?.successor===null||sameTurn?.successor===void 0){assertDefinitionPreflight(await inspectDefinitionPreflight("SPEC",id,filesystem,composition))}await assertCurrentReleaseForExecution(filesystem,current.spec.target_release,"SPEC");const plan=await preparedPlanForReadyOrExecute(current.spec,"SPEC",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(sameTurn?.successor!==null&&sameTurn?.successor!==void 0){const execution=(await composition.executions.read(plan.execution_id)).execution;if(sameTurn.successor.run.execution_id!==execution.id){throw new UsageError("Same-turn handoff replay targets a different Execution")}const claimedRunId=await composition.executions.claimSpecHandoff({clientTurnId:sameTurn.clientTurnId,interactionExecutionId:sameTurn.predecessor.run.execution_id,executionId:execution.id,specId:id,predecessorRunId:sameTurn.predecessor.run.run_id,proposedSuccessorRunId:sameTurn.successor.run.run_id,authorizationSha256:sameTurn.authorizationSha256});if(claimedRunId!==sameTurn.successor.run.run_id){throw new UsageError("Same-turn handoff claim identifies another delivery owner")}return{execution,run:sameTurn.successor.run,run_path:composition.runs.path(sameTurn.successor.run.run_id),artifact_path:composition.executions.path(execution.id),reused:true}}if(sameTurn!==null&&current.spec.status!=="ready"){throw new UsageError("Same-turn SPEC handoff requires ready status")}if(!new Set(["draft","ready"]).has(current.spec.status)){throw new UsageError(`SPEC cannot execute from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const materialized=await composition.materializer.execute(plan);const output2=executionOutput(materialized,composition);let deliveryRun=null;if(sameTurn!==null){let execution=(await composition.executions.read(plan.execution_id)).execution;if(execution.status==="planned"){execution=await composition.executions.transition(execution.id,"running")}const predecessor=sameTurn.predecessor.run;const runId=await composition.executions.claimSpecHandoff({clientTurnId:sameTurn.clientTurnId,interactionExecutionId:predecessor.execution_id,executionId:execution.id,specId:id,predecessorRunId:predecessor.run_id,proposedSuccessorRunId:createId("RUN","spec-delivery",{timeZone:composition.layout.project.timezone}),authorizationSha256:sameTurn.authorizationSha256});const existing=await composition.runs.read(runId).catch(()=>null);if(existing!==null){throw new UsageError("Same-turn successor exists without a matching active owner")}const start={id:runId,shortName:"spec-delivery",phase:"execution",runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:true,executionKind:"delivery",executionEligibility:[],entrypoint:"spec",workType:predecessor.work_type,client:predecessor.client,agent:predecessor.agent,...predecessor.agent_name===void 0?{}:{agentName:predecessor.agent_name},provider:predecessor.provider,model:predecessor.model,...predecessor.reasoning_effort===void 0?{}:{reasoningEffort:predecessor.reasoning_effort},clientThreadId:sameTurn.clientThreadId,clientTurnId:sameTurn.clientTurnId,conversationId:predecessor.conversation_id,executionId:execution.id,specId:id,prdId:current.spec.prd_id,continuationOfRunId:predecessor.run_id,sameTurnHandoff:{predecessor_run_id:predecessor.run_id,target_spec_id:id,authorization_sha256:sameTurn.authorizationSha256},...predecessor.developer_identity===void 0?{}:{developerIdentity:predecessor.developer_identity}};await validateRunV2Attribution(start,composition);deliveryRun=(await composition.runs.start(start)).started}if(current.spec.status==="draft")await composition.specs.transition(id,"ready");const preparedSpec=(await composition.specs.read(id)).spec;if(preparedSpec.status==="ready")await composition.specs.transition(id,"active");return deliveryRun===null?output2:{...output2,execution:(await composition.executions.read(plan.execution_id)).execution,run:deliveryRun,run_path:composition.runs.path(deliveryRun.run_id)}}if(action==="deliver"){throw new UsageError("SPEC terminal status is applied only by Gui through run finish")}if(action==="block"||action==="fail"){throw new UsageError("SPEC terminal status is applied only by Gui through run finish")}if(action==="cancel"){const changes=(await composition.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const executions=(await composition.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id);const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const cancelled_run_ids=(await Promise.all([...taskIds].map(taskId=>cancelTaskRunsForHuman(taskId,composition,parsed)))).flat();const result2=await lifecycle.cancelSpec(id);return{...result2,cancelled_run_ids,artifact_path:composition.specs.path(id)}}if(action==="activate"){const spec=await composition.specs.transition(id,"active");return{spec,artifact_path:composition.specs.path(id)}}throw new UsageError(`Unknown V2 SPEC action: ${action??""}`)}async function creationRunIdForCurrentTurn(parsed,filesystem,composition){if(parsed.options.run!==void 0){return(await composition.runs.read(parsed.options.run)).run.run_id}const invocation2=await resolveRunClientInvocation(filesystem,"codex");const intake2=await findIntakeForExactTurn(composition,"codex",invocation2);return intake2?.run.run_id??null}var init_v2_lifecycle=__esm({"src/commands/v2-lifecycle.ts"(){"use strict";init_src();init_src6();init_attribution_v2();init_cli_arguments();init_controlled_recovery_command();init_conversation_intake();init_definition_preflight();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();init_same_turn_spec_handoff();init_v2_run_cancellation_and_aggregate();init_spec_release_retarget();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();init_v2_lifecycle_prd();init_v2_lifecycle_support();init_v2_lifecycle_task();init_v2_ready_queue();init_v2_lifecycle_materialization()}});function isHostTerminalOnlyOpenReconciliation(area,action,parsed){return(area==="run"||area==="run-v2")&&action==="reconcile"&&parsed.flags.has("open")&&parsed.flags.has("host-terminal-only")}function isBoundedActiveTelemetryCapture(area,action,parsed){return(area==="run"||area==="run-v2")&&action==="usage"&&(parsed.flags.has("active")||parsed.flags.has("recent"))&&parsed.flags.has("disable-codex-raw")}function isIdempotentLifecycleReplay(area,action,result2){if(!((area==="run"||area==="run-v2"||area==="conversation")&&action==="start")){return false}return typeof result2==="object"&&result2!==null&&"reused"in result2&&result2.reused===true}function isNarrowSubagentTerminalCapture(area,action){return area==="subagent"&&(action==="capture-terminal"||action==="reconcile-stop")}function isNarrowRunFinish(area,action){return(area==="run"||area==="run-v2")&&action==="finish"}var init_v2_router_classification=__esm({"src/commands/v2-router-classification.ts"(){"use strict"}});var V2_COMMAND_AREAS;var init_v2_command_areas=__esm({"src/commands/v2-command-areas.ts"(){"use strict";V2_COMMAND_AREAS=new Set(["plan","prd","spec","change","task","execution","decision","evidence","validation","run","run-v2","conversation","developer","subagent"])}});var v2_router_exports={};__export(v2_router_exports,{V2_COMMAND_AREAS:()=>V2_COMMAND_AREAS,createV2Composition:()=>createV2Composition,runHostTerminalOnlyReconcile:()=>runHostTerminalOnlyReconcile,runV2Command:()=>runV2Command});function createV2Composition(filesystem,layout){const storageMode=layout.projectConfig?.tracking.storage_mode??"tracked_sanitized";return{filesystem,layout,prds:new PrdV2Repository(filesystem,layout),specs:new DeliverySpecV2Repository(filesystem,layout),changes:new ChangeV2Repository(filesystem,layout),tasks:new TaskV2Repository(filesystem,layout),executions:new ExecutionV2Repository(filesystem,layout),materializer:new PreparedPlanV2Materializer(filesystem,layout),decisions:new DecisionV2Repository(filesystem,layout),runs:new RunV2Repository(filesystem,storageMode==="local_only"?{storageMode:"local_only",localBasePath:".local/runs"}:{storageMode:"tracked_sanitized",layout})}}async function runV2Command(area,action,parsed,filesystem,layout){if(area==="conversation"&&action==="resolve"){return preview(parsed,filesystem,layout)}if(area==="change"&&action==="narrative"&&!parsed.flags.has("apply"))return runV2CommandUnlocked(area,action,parsed,filesystem,layout);if((area==="spec"&&action==="revise-implementation"||area==="task"&&["recover-release","recover-post-publication"].includes(action??""))&&!parsed.flags.has("apply"))return runV2CommandUnlocked(area,action,parsed,filesystem,layout);if(isHostTerminalOnlyOpenReconciliation(area,action,parsed)){return runHostTerminalOnlyReconcile(parsed,filesystem,layout)}if(area==="conversation"&&action==="start"){return capture(parsed,filesystem,layout,intake2=>runV2CommandUnlocked(area,action,parsed,filesystem,layout,intake2))}if(area==="task"&&action==="migrate-autonomy"&&parsed.flags.has("confirm"))return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout));if(area==="task"&&action==="assurance"&&(parsed.options["applicability-map"]!==void 0||parsed.options["inherit-applicability-attempt"]!==void 0))return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout));if(!isLifecycleManifestMutation(action)||area==="validation"&&["execute","batch"].includes(action??"")||area==="task"&&["commit","workspace","assurance","recovery-status"].includes(action??"")||isNarrowSubagentTerminalCapture(area,action)||isNarrowRunFinish(area,action)||isBoundedActiveTelemetryCapture(area,action,parsed)){return runV2CommandUnlocked(area,action,parsed,filesystem,layout)}return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout),area==="conversation"&&action==="start"?{timeout_ms:15e3}:{})}async function runHostTerminalOnlyReconcile(parsed,filesystem,layout,dependencies={}){const createComposition=dependencies.createComposition??(()=>createV2Composition(filesystem,layout));const preflight=dependencies.preflight??hostTerminalOnlyPreflight;const withLock=dependencies.withLock??(operation=>withLifecycleCanonicalMutationLock(filesystem,operation));const execute4=dependencies.execute??(()=>runV2CommandUnlocked("run","reconcile",parsed,filesystem,layout));const initial=await preflight(createComposition(),filesystem);if(initial.kind==="no-op")return initial.result;return withLock(execute4)}async function runV2CommandUnlocked(area,action,parsed,filesystem,layout,intake2){const composition=createV2Composition(filesystem,layout);if(area==="task"&&action==="recovery-status")return taskRecoveryStatus(parsed.positionals[2]??parsed.options.id??"",composition);if(area==="task"&&action==="assurance")return runTaskAssuranceCommand(parsed,filesystem,composition);if(area==="task"&&action==="workspace")return runTaskWorkspaceAction(parsed,filesystem,composition);if(area==="validation"&&action==="batch")return runValidationBatchCommand(parsed,filesystem,composition);if(action==="list"&&parsed.options.view!=="full"){return manifestList(area==="run-v2"?"run":area,parsed,filesystem)}const lifecycle=new LifecycleV2Gate(filesystem,layout,composition);let result2;let manifestSyncedDuringMutation=false;if(area==="plan")return runPlanV2Command(action,parsed,filesystem,layout);if(area==="developer")return runDeveloperIdentityCommand(action,parsed,filesystem);if(area==="prd")result2=await runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle);else if(area==="spec")result2=await runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle);else if(area==="change")result2=await runChangeV2Command(action,parsed,composition,lifecycle);if(area==="conversation"){result2=await command(action,parsed,composition,filesystem,lifecycle,intake2)}else if(area==="subagent"){result2=await runSubagentV2Command(action,parsed,composition,filesystem,lifecycle,async captured=>{await syncLifecycleManifestResult(captured,"subagent",parsed,composition,filesystem);manifestSyncedDuringMutation=true})}else if(area==="task"){if(action==="migrate-autonomy")return migrateTaskAutonomy(parsed.positionals[2]??parsed.options.id??"",parsed,composition);result2=["repair-verification","settle-repair"].includes(action??"")?await runTaskVerificationRepairCommand(parsed,composition):action==="commit"?await runTaskCommitCommand(parsed,filesystem,composition):await runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}else if(area==="execution")result2=await runExecutionV2Command(action,parsed,composition,lifecycle,async(id,options)=>{const source=(await composition.executions.read(id)).execution.origin.type;const config2=layout.projectConfig;const managed=config2!==null&&!options.flags.has("materialize-only")&&resolveExecutionRuntime(config2,void 0,source).runtime==="autonomous";return runAutonomousExecutionCommand(id,options,composition,managed?createAutonomousProductionDriver(filesystem,config2,source):void 0,await loadAgentCatalog(filesystem))});else if(area==="decision")result2=await runDecisionV2Command(action,parsed,filesystem,composition);else if(area==="evidence")result2=parsed.options.spec!==void 0||parsed.options.execution!==void 0?await runParentEvidenceCommand(action??"",parsed,filesystem,composition):await runEvidenceV2Command(action,parsed,filesystem,composition);else if(area==="validation")result2=parsed.options.spec!==void 0||parsed.options.execution!==void 0?await runParentValidationCommand(action??"",parsed,filesystem,composition):await runValidationV2Command(action,parsed,filesystem,composition);else if(area==="run"||area==="run-v2"){result2=await runRunV2Command(action,parsed,composition,filesystem,lifecycle)}else if(!["prd","spec","change","task","conversation","subagent","evidence","validation"].includes(area)){throw new UsageError(`Unknown V2 command: ${area} ${action??""}`.trim())}if(isLifecycleManifestMutation(action)&&!(area==="change"&&action==="narrative")&&!manifestSyncedDuringMutation&&!isIdempotentLifecycleReplay(area,action,result2)){if(area==="validation"&&action==="execute"){return syncValidationProjection(result2,parsed.options.id,()=>syncLifecycleManifestResult(result2,area,parsed,composition,filesystem))}await syncLifecycleManifestResult(result2,area==="run-v2"?"run":area,parsed,composition,filesystem)}if((area==="run"||area==="run-v2")&&action==="finish")return maybeCloseTerminalTaskWorkspace(filesystem,composition,parsed.positionals[2]??parsed.options.id,result2);return result2}async function runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle){const definitionActions=new Set(["create","rework","prepare"]);if(!definitionActions.has(action??"")){return runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}const runId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);await assertActiveDefinitionRun({area,runId,filesystem,composition,reworkAuthoring:action==="rework"});return runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}var init_v2_router=__esm({"src/commands/v2-router.ts"(){"use strict";init_src5();init_src6();init_src7();init_autonomous_execution_command();init_autonomous_production_driver();init_candidate_commit_command();init_candidate_validation_batch_command();init_cli_arguments();init_conversation_stop_intake();init_developer_identity_command();init_evidence_commands_v2();init_execution_commands_v2();init_execution_runtime_config();init_governance_commands_v2();init_lifecycle_manifest_commands();init_lifecycle_v2();init_open_work_host_preflight();init_parent_assurance_v1();init_prepared_plan_v22();init_run_agent_identity();init_subagent_command_v2();init_task_assurance_command();init_task_autonomy_migration();init_task_recovery_status();init_task_verification_repair();init_task_workspace_closure();init_task_workspace_routing();init_validation_commands_v2();init_validation_projection();init_definition_run_gate();init_v2_lifecycle();init_v2_router_classification();init_v2_run();init_v2_command_areas()}});init_src2();import{basename as basename9,dirname as dirname21,resolve as resolve31}from"node:path";import{pathToFileURL}from"node:url";var import_parser=__toESM(require_lib(),1);function resolveSupabaseProfile(value){if(!isRecord(value)||value.id!==SUPABASE_EDGE_PROFILE.id){return unsupported2("explicit supabase-edge-functions profile is required")}if(value.workspaces!==void 0||value.scopes!==void 0||value.importMap!==void 0){return unsupported2("unsupported workspace, scope, or importMap configuration")}const map2=parseDenoImportMap(value.deno_json??value.deno_import_map);return map2===null?unsupported2("missing or malformed deno.json or deno_import_map"):{profile:{...SUPABASE_EDGE_PROFILE,denoImportMap:map2},diagnostics:[]}}function supabaseEntrypointFindings(units,profile){if(profile.id!==SUPABASE_EDGE_PROFILE.id)return[];const endpoints=new Set(units.map(unit=>normalizePath(unit.path).match(/^supabase\/functions\/([^/]+)\//)?.[1]).filter(name=>name!==void 0&&name!=="_shared"));return[...endpoints].flatMap(endpoint=>{const entrypoint=profile.functionEntrypoints?.[endpoint]??"index.ts";return units.some(unit=>normalizePath(unit.path)===`supabase/functions/${endpoint}/${entrypoint}`)?[]:[finding("supabase-function-missing-entrypoint",`supabase/functions/${endpoint}`,1,`Function ${endpoint} has no ${entrypoint}`)]})}function isSupabasePrivateFunctionImport(source,target){const sourceFunction=source.match(/^supabase\/functions\/([^/]+)\//)?.[1];const targetFunction=target.match(/^supabase\/functions\/([^/]+)\//)?.[1];if(sourceFunction===void 0||targetFunction===void 0)return false;if(sourceFunction==="_shared"&&targetFunction==="_shared")return false;if(targetFunction==="_shared")return!/^supabase\/functions\/_shared\/index\.(?:[cm]?ts|[cm]?js)$/.test(target);return sourceFunction!==targetFunction}function aliasesForSource(profile,sourcePath){const imports=profile.denoImportMap;if(imports===void 0)return profile.importAliases??[];const functionName=sourcePath.match(/^supabase\/functions\/([^/]+)\//)?.[1];const scoped=functionName===void 0?void 0:imports.functionImports?.[functionName];return[...toImportAliases(scoped??{},`supabase/functions/${functionName??""}`),...toImportAliases(imports.imports,"supabase/functions")]}function unsupported2(reason){return{profile:{...SUPABASE_EDGE_PROFILE,supported:false,notApplicableReason:reason},diagnostics:[`supabase-profile: ${reason}`]}}function toImportAliases(entries,basePath){return Object.entries(entries).map(([prefix,target])=>({prefix,target:normalizeImportTarget(target,basePath)}))}function normalizeImportTarget(target,basePath){const trailingSlash=target.endsWith("/");const normalized=target.startsWith(".")?normalizePath(`${basePath}/${target}`):target;return trailingSlash&&!normalized.endsWith("/")?`${normalized}/`:normalized}function parseDenoImportMap(value){if(!isRecord(value)||!isStringMap(value.imports))return null;if(value.scopes!==void 0||value.workspace!==void 0||value.workspaces!==void 0||value.importMap!==void 0)return null;if(value.function_imports===void 0)return{imports:value.imports};if(!isRecord(value.function_imports))return null;const functionImports={};for(const[functionName,imports]of Object.entries(value.function_imports)){if(!isStringMap(imports))return null;functionImports[functionName]=imports}return{imports:value.imports,functionImports}}function isStringMap(value){return isRecord(value)&&Object.entries(value).every(([prefix,target])=>typeof target==="string"&&prefix.length>0&&target.length>0&&prefix.endsWith("/")===target.endsWith("/"))}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizePath(path){const segments2=[];for(const segment2 of path.replace(/\\/g,"/").split("/")){if(segment2===""||segment2===".")continue;if(segment2==="..")segments2.pop();else segments2.push(segment2)}return segments2.join("/")}function finding(rule,path,line,message2){return{rule,path,line,message:message2}}function resolvedImports(unit,resolveImport){const imports=[];const add=(source,line,unverifiedDynamic=false)=>{const specifier=staticModuleSpecifier(source);if(specifier===void 0){if(unverifiedDynamic)imports.push({module:"<dynamic import>",resolvedModule:null,line:typeof line==="number"?line:1,unverified:true});return}const module=specifier.replace(/\\/g,"/");imports.push({module,resolvedModule:resolveImport(unit.path,module),line:typeof line==="number"?line:1})};const visit=node=>{if(!isRecord2(node))return;const line=sourceLine(node);if(["ImportDeclaration","ExportNamedDeclaration","ExportAllDeclaration","ImportExpression","TSImportType"].includes(String(node.type))){add(node.type==="TSImportType"?node.argument:node.source,line,node.type==="ImportExpression")}else if(node.type==="CallExpression"&&isRecord2(node.callee)&&node.callee.type==="Import"){add(Array.isArray(node.arguments)?node.arguments[0]:void 0,line,true)}else if(node.type==="CallExpression"&&isRecord2(node.callee)&&node.callee.type==="Identifier"&&node.callee.name==="require"){add(Array.isArray(node.arguments)?node.arguments[0]:void 0,line,true)}else if(node.type==="TSImportEqualsDeclaration"&&isRecord2(node.moduleReference)){add(node.moduleReference.expression,line)}for(const value of Object.values(node)){if(Array.isArray(value))for(const child of value)visit(child);else if(value!==node.loc)visit(value)}};visit((0,import_parser.parse)(unit.content,{sourceType:"unambiguous",plugins:unit.path.endsWith(".tsx")||unit.path.endsWith(".jsx")?["typescript","jsx"]:["typescript"]}));return imports}function importResolver(units,profile){const knownPaths=new Set(units.map(unit=>normalizePath2(unit.path)));const sourceAliases=new Map(units.map(unit=>[normalizePath2(unit.path),unit.importAliases??[]]));return(sourcePath,specifier)=>{const candidates=importCandidates(normalizePath2(sourcePath),specifier.replace(/\\/g,"/"),[...sourceAliases.get(normalizePath2(sourcePath))??[],...aliasesForSource(profile,normalizePath2(sourcePath))]);for(const candidate of candidates){const resolved=resolveKnownPath(candidate,knownPaths);if(resolved!==null)return resolved}return candidates[0]??null}}function normalizePath2(path){const segments2=[];for(const segment2 of path.replace(/\\/g,"/").split("/")){if(segment2===""||segment2===".")continue;if(segment2==="..")segments2.pop();else segments2.push(segment2)}return segments2.join("/")}function importCandidates(sourcePath,specifier,aliases){if(specifier.startsWith("."))return[normalizePath2(`${dirname2(sourcePath)}/${specifier}`)];return aliases.filter(alias=>specifier===alias.prefix||alias.prefix.endsWith("/")&&specifier.startsWith(alias.prefix)).sort((left,right)=>right.prefix.length-left.prefix.length).map(alias=>normalizePath2(`${alias.target}${specifier.slice(alias.prefix.length)}`))}function resolveKnownPath(candidate,knownPaths){const extensions=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];const sourceExtension=/\.(?:[cm]?[jt]sx?)$/.test(candidate)?candidate.replace(/\.(?:[cm]?[jt]sx?)$/,""):candidate;const options=[candidate,sourceExtension,...extensions.map(extension=>`${candidate}${extension}`),...extensions.map(extension=>`${candidate}/index${extension}`),...extensions.map(extension=>`${sourceExtension}${extension}`),...extensions.map(extension=>`${sourceExtension}/index${extension}`)];return options.find(option=>knownPaths.has(option))??null}function staticModuleSpecifier(source){if(!isRecord2(source))return void 0;if(typeof source.value==="string")return source.value;if(source.type!=="TemplateLiteral"||!Array.isArray(source.expressions)||source.expressions.length!==0||!Array.isArray(source.quasis))return void 0;const quasi=source.quasis[0];return isRecord2(quasi)&&isRecord2(quasi.value)&&typeof quasi.value.cooked==="string"?quasi.value.cooked:void 0}function sourceLine(node){const location=node.loc;return isRecord2(location)&&isRecord2(location.start)&&typeof location.start.line==="number"?location.start.line:void 0}function dirname2(path){return path.slice(0,Math.max(0,path.lastIndexOf("/")))}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var import_parser2=__toESM(require_lib(),1);function workspaceImportAliases(manifests){const documents=new Map(manifests.map(({path,content})=>[normalizePath2(path),parseDocument3(path,content)]));const packages=[];for(const[path,document]of documents){if(!path.endsWith("package.json")||typeof document.name!=="string")continue;const entries=document.exports;if(isRecord3(entries)&&Object.keys(entries).some(key=>key.startsWith("."))){for(const[subpath,target]of Object.entries(entries)){addTargets(packages,document.name+(subpath==="."?"":subpath.slice(1)),target,directory(path))}}else{addTargets(packages,document.name,entries??document.module??document.main??"./index.ts",directory(path))}}const resolved=new Map;function configOptions(path,chain=[]){const cached2=resolved.get(path);if(cached2)return cached2;if(chain.includes(path))throw new Error(`Cyclic architecture tsconfig inheritance: ${path}`);const document=documents.get(path);if(!document)throw new Error(`Architecture tsconfig is unavailable: ${path}`);let inherited={};const parents=document.extends===void 0?[]:Array.isArray(document.extends)?document.extends:[document.extends];for(const parent of parents){if(typeof parent!=="string"||!parent.startsWith(".")){throw new Error(`Architecture cannot verify external tsconfig inheritance: ${path}`)}const candidate=normalizePath2(`${directory(path)}/${parent}`);inherited={...inherited,...configOptions(documents.has(candidate)||candidate.endsWith(".json")?candidate:`${candidate}.json`,[...chain,path])}}const options=isRecord3(document.compilerOptions)?document.compilerOptions:{};const result2={...inherited};if(options.baseUrl!==void 0){if(typeof options.baseUrl!=="string")throw new Error(`Invalid architecture tsconfig baseUrl: ${path}`);result2.baseUrl=normalizePath2(`${directory(path)}/${options.baseUrl}`)}if(options.paths!==void 0){if(!isRecord3(options.paths))throw new Error(`Invalid architecture tsconfig paths: ${path}`);result2.paths=options.paths;result2.pathsBase=directory(path)}resolved.set(path,result2);return result2}function configAliases(path){const options=configOptions(path);const base=options.baseUrl??options.pathsBase??directory(path);const aliases=[];for(const[prefix,targets]of Object.entries(options.paths??{})){if(!Array.isArray(targets)||targets.length===0||!targets.every(target=>typeof target==="string")){throw new Error(`Invalid architecture tsconfig path targets: ${path}`)}for(const target of targets)addAlias(aliases,prefix,String(target),base)}return aliases}return sourcePath=>{const nearest=[...documents.keys()].filter(path=>path.endsWith("tsconfig.json")&&(directory(path)===""||sourcePath.startsWith(`${directory(path)}/`))).sort((a,b)=>b.length-a.length)[0];return[...nearest?configAliases(nearest):[],...packages]}}function addTargets(aliases,prefix,target,base){if(typeof target==="string")addAlias(aliases,prefix,target,base);else if(Array.isArray(target))for(const entry2 of target)addTargets(aliases,prefix,entry2,base);else if(isRecord3(target))for(const entry2 of Object.values(target))addTargets(aliases,prefix,entry2,base)}function addAlias(aliases,prefix,target,base){const stars=(prefix.match(/\*/g)??[]).length;if(stars>1||stars===1&&(!prefix.endsWith("*")||!target.endsWith("*"))){throw new Error(`Architecture cannot verify non-prefix import mapping: ${prefix}`)}if(/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/|\\)/.test(target)){throw new Error(`Architecture import mapping escapes the workspace: ${prefix}`)}const source=stars?prefix.slice(0,-1):prefix;const destination=stars?target.slice(0,-1):target;const joined=`${base}/${destination}`;let depth=0;for(const segment2 of joined.split("/")){if(segment2==="..")depth-=1;else if(segment2&&segment2!==".")depth+=1;if(depth<0)throw new Error(`Architecture import mapping escapes the workspace: ${prefix}`)}aliases.push({prefix:source,target:normalizePath2(joined)+(destination.endsWith("/")?"/":"")})}function parseDocument3(path,content){const value=literal2((0,import_parser2.parseExpression)(content));if(!isRecord3(value))throw new Error(`Architecture manifest must be an object: ${path}`);return value}function literal2(node){if(!isRecord3(node))throw new Error("Invalid architecture manifest");if(["StringLiteral","NumericLiteral","BooleanLiteral"].includes(String(node.type)))return node.value;if(node.type==="NullLiteral")return null;if(node.type==="ArrayExpression"&&Array.isArray(node.elements))return node.elements.map(literal2);if(node.type==="ObjectExpression"&&Array.isArray(node.properties)){const entries=node.properties.map(property=>{if(!isRecord3(property)||property.type!=="ObjectProperty"||property.computed||!isRecord3(property.key)||property.key.type!=="StringLiteral"){throw new Error("Architecture manifests must contain literal JSON properties")}return[String(property.key.value),literal2(property.value)]});return Object.fromEntries(entries)}if(node.type==="UnaryExpression"&&node.operator==="-"&&isRecord3(node.argument)&&node.argument.type==="NumericLiteral")return-Number(node.argument.value);throw new Error("Architecture manifests must contain only JSON literals")}function directory(path){return path.slice(0,Math.max(0,path.lastIndexOf("/")))}function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var TYPESCRIPT_PROFILE={id:"zaip-aios-stack",extensions:[".ts",".tsx"],frameworkPackages:["hono","react","kysely","drizzle-orm","express","fastify"],queryPatterns:["/queries/",".query.","QueryHandler"],writePortPatterns:["WritePort","CommandRepository","UnitOfWork"],supported:true};var SUPABASE_EDGE_PROFILE={...TYPESCRIPT_PROFILE,id:"supabase-edge-functions",frameworkPackages:[...TYPESCRIPT_PROFILE.frameworkPackages,"@supabase/supabase-js"],supported:true};function validateArchitecture(units,profile=TYPESCRIPT_PROFILE){if(!profile.supported&&!profile.notApplicableReason){throw new Error(`Unsupported profile ${profile.id} requires a notApplicableReason`)}return[...validateAll(units,profile),...supabaseEntrypointFindings(units,profile)].filter(item=>["domain-framework-dependency","application-concrete-adapter","adapter-inward-dependency","frontend-server-dependency","backend-ui-dependency","dashboard-backend-app","inner-layer-app-dependency","site-dashboard-dependency","package-module-dependency","supabase-private-function-import","supabase-function-missing-entrypoint","unresolved-dynamic-import"].includes(item.rule))}function validateCqrs(units,profile=TYPESCRIPT_PROFILE){return validateAll(units,profile).filter(item=>["query-write-port","query-side-effect","route-direct-database","database-row-leak","command-missing-idempotency","query-missing-account-context"].includes(item.rule))}function validateModules(units,profile=TYPESCRIPT_PROFILE){const findings=validateAll(units,profile).filter(item=>item.rule==="cross-module-storage");const modules=new Set(units.map(unit=>moduleName(unit.path)).filter(name=>name!==null));for(const module of modules){if(!units.some(unit=>isCompositionRoot(unit.path,module))){findings.push(finding2("module-missing-composition-root",`modules/${module}`,1,`Module ${module} has no composition-root.ts`))}}return findings}function validateProfileContract(value){if(typeof value!=="object"||value===null)return[{field:"$",message:"Profile must be an object"}];const profile=value;const findings=[];if(typeof profile.id!=="string"||profile.id.length===0)findings.push({field:"id",message:"Profile id is required"});if(profile.status!=="supported"&&profile.status!=="experimental")findings.push({field:"status",message:"Profile status must be supported or experimental"});if(!Array.isArray(profile.extensions)||profile.extensions.length===0)findings.push({field:"extensions",message:"At least one extension is required"});if(!Array.isArray(profile.invariants)||profile.invariants.length===0)findings.push({field:"invariants",message:"Profile invariants are required"});if(profile.status==="supported"){const conventions=profile.conventions;const apps=conventions?.apps;const sourceLimits=conventions?.source_limits;if(!conventions||!apps||apps.frontend!=="apps/frontend"||apps.backend!=="apps/backend"||apps.site!=="apps/site"||conventions.modules!=="modules"||conventions.packages!=="packages"||conventions.e2e!=="tests/e2e"){findings.push({field:"conventions",message:"Supported profiles require canonical apps/frontend, apps/backend, apps/site, modules, packages and tests/e2e paths"})}if(!sourceLimits||!Number.isInteger(sourceLimits.warning_lines)||!Number.isInteger(sourceLimits.error_lines)||Number(sourceLimits.warning_lines)!==400||Number(sourceLimits.error_lines)!==800){findings.push({field:"conventions.source_limits",message:"Supported profiles require source-size limits of 400 warning and 800 error lines"})}const commands=profile.commands;if(!commands||typeof commands.test!=="string"||typeof commands.typecheck!=="string"){findings.push({field:"commands",message:"Supported profiles require test and typecheck commands"})}}return findings}function validateAll(units,profile){const findings=[];const resolveImport=importResolver(units,profile);for(const unit of units){const normalizedPath=unit.path.replace(/\\/g,"/");const layer=detectLayer(normalizedPath);const imports=resolvedImports(unit,resolveImport);if(isDashboardBackendApp(normalizedPath)){findings.push(finding2("dashboard-backend-app",unit.path,1,"The local dashboard is frontend-only; move loopback projection runtime code to .agents/dashboard/packages/local-runtime"))}for(const imported of imports){const resolved=imported.resolvedModule??imported.module;const targetLayer=detectLayer(resolved);if(imported.unverified&&isArchitecturalSource(normalizedPath)){findings.push(finding2("unresolved-dynamic-import",unit.path,imported.line,"Dynamic import cannot be resolved statically; use an explicit import or an approved boundary adapter"))}if(isFrontendRuntimeSource(normalizedPath)&&(isServerOnlyDependency(imported.module)||isBackendApp(resolved))){findings.push(finding2("frontend-server-dependency",unit.path,imported.line,`Frontend imports server-only dependency ${imported.module}`))}if(isBackendApp(normalizedPath)&&isUiRuntimeDependency(imported.module)){findings.push(finding2("backend-ui-dependency",unit.path,imported.line,`Backend imports UI runtime dependency ${imported.module}`))}if(isInnerLibrary(normalizedPath)&&importsApplication(imported.module)){findings.push(finding2("inner-layer-app-dependency",unit.path,imported.line,`Inner module/package imports application ${imported.module}`))}if(isPublicSite(normalizedPath)&&importsDashboardOrAgentState(imported.module)){findings.push(finding2("site-dashboard-dependency",unit.path,imported.line,`Public site imports private dashboard or agent state ${imported.module}`))}if(layer==="domain"&&(isFramework(resolved,profile)||resolved.startsWith("node:")||targetLayer!==null&&targetLayer!=="domain")){findings.push(finding2("domain-framework-dependency",unit.path,imported.line,`Domain imports ${imported.module}`))}if(layer==="application"&&["adapters","infrastructure"].includes(targetLayer??"")){findings.push(finding2("application-concrete-adapter",unit.path,imported.line,`Application imports concrete ${targetLayer}`))}if(["domain","application"].includes(layer??"")&&targetLayer==="adapters"){findings.push(finding2("adapter-inward-dependency",unit.path,imported.line,`Inner layer imports adapter ${imported.module}`))}const sourceModule=moduleName(normalizedPath);const targetModule=moduleName(resolved);if(isPackage(normalizedPath)&&targetModule!==null&&!isDashboardRuntimePublicBoundary(normalizedPath,resolved)){findings.push(finding2("package-module-dependency",unit.path,imported.line,`Package imports module ${targetModule}`))}if(sourceModule&&targetModule&&sourceModule!==targetModule&&isPrivateModuleImplementation(resolved)){findings.push(finding2("cross-module-storage",unit.path,imported.line,`Module ${sourceModule} reaches private storage of ${targetModule}`))}if(isSupabasePrivateFunctionImport(normalizedPath,resolved)){findings.push(finding2("supabase-private-function-import",unit.path,imported.line,`Function imports private source of another function ${imported.module}`))}}if(isPublicSite(normalizedPath)&&/\.agents\/(?:config|data|rules|requirements)/.test(unit.content)){findings.push(finding2("site-dashboard-dependency",unit.path,lineOf(unit.content,".agents/"),"Public site reads private .agents state"))}if(isQuery(normalizedPath,unit.content,profile)){for(const pattern of profile.writePortPatterns){if(unit.content.includes(pattern)){findings.push(finding2("query-write-port",unit.path,lineOf(unit.content,pattern),`Query references write capability ${pattern}`))}}const mutation=unit.content.match(/\.(?:insert|update|delete|save|commit|rollback)\s*\(|\.rpc\s*\(\s*["'`](?:delete|remove|update|insert|create|write)/i);if(mutation?.index!==void 0){findings.push(finding2("query-side-effect",unit.path,lineAt(unit.content,mutation.index),`Query contains mutation ${mutation[0].trim()}`))}if(/\b(?:tenant|account)_?id\b/i.test(unit.content)&&!unit.content.includes("AccountContext")){findings.push(finding2("query-missing-account-context",unit.path,lineOf(unit.content,"account"),"Multi-tenant query does not require AccountContext"))}}if(/\/(?:routes?|http)\//.test(normalizedPath)&&/\b(?:db|kysely|prisma|supabase|client)\s*\.\s*(?:from|selectFrom|insertInto|updateTable|deleteFrom|query)\s*\(/i.test(unit.content)){findings.push(finding2("route-direct-database",unit.path,1,"Inbound adapter accesses database directly"))}if(/\/(?:routes?|http)\//.test(normalizedPath)&&unit.content.includes("DatabaseRow")){findings.push(finding2("database-row-leak",unit.path,lineOf(unit.content,"DatabaseRow"),"DatabaseRow leaks through inbound boundary"))}if(/\/commands\//.test(normalizedPath)&&/critical\s*[:=]\s*true/i.test(unit.content)&&!/Idempotenc|idempotency_key/.test(unit.content)){findings.push(finding2("command-missing-idempotency",unit.path,1,"Critical command has no idempotency policy"))}}return[...deduplicate(findings)]}function isFrontendApp(path){return/(?:^|\/)apps\/frontend\//.test(path)}function isDashboardRuntimePublicBoundary(source,target){return source.startsWith(".agents/dashboard/packages/local-runtime/")&&/^\.agents\/dashboard\/modules\/(?:operations|cost-monitor|traceability)\/(?:composition-root\.ts|src\/(?:contracts\.ts|work-board-model\.ts|server\/index\.ts))$/.test(target)}function isFrontendRuntimeSource(path){return isFrontendApp(path)&&/\/src\/.+\.[cm]?[jt]sx?$/.test(path)&&!/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path)&&!/(?:^|\/)(?:__tests__|test|tests)\//.test(path)}function isBackendApp(path){return/(?:^|\/)apps\/backend\//.test(path)}function isDashboardBackendApp(path){return/(?:^|\/)\.agents\/dashboard\/apps\/backend(?:\/|$)/.test(path)}function isPublicSite(path){return/(?:^|\/)apps\/site\//.test(path)}function isInnerLibrary(path){return/(?:^|\/)(?:modules|packages)\/[^/]+\//.test(path)}function isArchitecturalSource(path){return/(?:^|\/)(?:apps|modules|packages|supabase\/functions)\//.test(path)}function isServerOnlyDependency(module){return module.startsWith("node:")||/^(?:assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|diagnostics_channel|dns|domain|events|fs|http|http2|https|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|sys|timers|tls|trace_events|tty|url|util|v8|vm|wasi|worker_threads|zlib)(?:\/|$)/.test(module)||module==="pg"||module.startsWith("pg/")||module==="hono"||module.startsWith("hono/")||module.startsWith("@hono/")||/^@zaip-ai\/dashboard-(?:operations|cost-monitor|traceability)\/server(?:\/|$)/.test(module)||/^@zaip-ai\/dashboard-local-runtime(?:\/|$)/.test(module)||/^@zaip-ai\/(?:adapters|architecture|cli|context|core|costs|decisions|distribution|eval|specs|tasks|testing)(?:\/|$)/.test(module)}function isUiRuntimeDependency(module){return module==="react"||module.startsWith("react/")||module.startsWith("react-dom")||module==="@zaip-ai/dashboard-ui"||/^@zaip-ai\/dashboard-(?:operations|cost-monitor|traceability)\/react(?:\/|$)/.test(module)}function importsApplication(module){return/(?:^|\/)apps\/(?:frontend|backend|site)(?:\/|$)/.test(module.replace(/\\/g,"/"))||/^@zaip-ai\/dashboard-frontend(?:\/|$)/.test(module)}function importsDashboardOrAgentState(module){const normalized=module.replace(/\\/g,"/");return normalized.includes(".agents/")||/(?:^|\/)\.agents\/dashboard(?:\/|$)/.test(normalized)||/^@zaip-ai\/dashboard-(?:frontend|local-runtime|operations|cost-monitor|traceability)(?:\/|$)/.test(module)}function detectLayer(path){return path.match(/\/(domain|application|adapters|infrastructure)\//)?.[1]??null}function isFramework(module,profile){const packageName=normalizeNpmSpecifier(module);return profile.frameworkPackages.some(name=>packageName===name||packageName.startsWith(`${name}/`))}function normalizeNpmSpecifier(module){const match=module.match(/^npm:((?:@[^/@]+\/)?[^/@]+)(?:@[^/]+)?(\/.*)?$/);return match===null?module:`${match[1]}${match[2]??""}`}function isQuery(path,content,profile){return profile.queryPatterns.some(pattern=>{if(pattern.startsWith("/")||pattern.startsWith("."))return path.includes(pattern);return new RegExp(`\\bclass\\s+[A-Za-z0-9_]*${escapeRegExp(pattern)}\\b`).test(content)})}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function moduleName(path){return path.match(/(?:^|\/)modules\/([^/]+)/)?.[1]??null}function isCompositionRoot(path,module){const normalized=normalizePath2(path);return normalized===`modules/${module}/composition-root.ts`||normalized.endsWith(`/modules/${module}/composition-root.ts`)}function isPackage(path){return/(?:^|\/)packages\/[^/]+\//.test(path)}function isPrivateModuleImplementation(path){return/(?:^|\/)modules\/[^/]+\/(?:adapters|application|domain|infrastructure|persistence|repositories|storage)(?:\/|$)/.test(path)}function lineOf(content,value){return lineAt(content,Math.max(0,content.indexOf(value)))}function lineAt(content,index){return content.slice(0,index).split("\n").length}function finding2(rule,path,line,message2){return{rule,path,line,message:message2}}function deduplicate(findings){const seen=new Set;return findings.filter(item=>{const key=`${item.rule}:${item.path}:${item.line}`;if(seen.has(key))return false;seen.add(key);return true})}init_src3();init_src();init_src4();init_src5();init_src2();init_src3();init_src();var EVAL_VERSION="6.0.0";async function persistEvalReport(filesystem,report,shortName="offline-suite"){const id=createId("EVAL",shortName);const{year,month}=datedIdParts(id);const path=`.agents/evals/results/${year}/${month}/${id}.json`;const persisted={id,version:EVAL_VERSION,generated_at:new Date().toISOString(),report};await filesystem.writeTextAtomic(path,`${JSON.stringify(persisted,null,2)}
3652
+ `);if(digest12(task)!==digest12(nextTask))await composition.tasks.write(nextTask);return{applied:true,task:nextTask,current_release:to,amendment_path:path,reused:digest12(task)===digest12(nextTask)&&digest12(cycle)===digest12(nextCycle)}}var cyclePath5,digest12;var init_task_release_retarget=__esm({"src/task-release-retarget.ts"(){"use strict";init_src7();init_cli_arguments();init_controlled_recovery_authority();init_lifecycle_run_attribution();init_run_client_invocation();init_run_hierarchy();cyclePath5=".agents/config/release-cycle.json";digest12=value=>createHash72("sha256").update(JSON.stringify(value)).digest("hex")}});function selectReadyQueueItem(input){const order2=manualPriority(input.priority);const materialized=new Set(input.executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id)));const completed=new Set(input.tasks.filter(task2=>task2.status==="completed").map(task2=>task2.id));const changes=new Map(input.changes.map(change=>[change.id,change]));const byOrder=(left,right)=>{const leftRank=order2.get(left.id);const rightRank=order2.get(right.id);if(leftRank!==void 0||rightRank!==void 0){if(leftRank===void 0)return 1;if(rightRank===void 0)return-1;if(leftRank!==rightRank)return leftRank-rightRank}return left.created_at.localeCompare(right.created_at)||left.id.localeCompare(right.id)};const prd=input.prds.filter(item=>item.status==="ready").sort(byOrder)[0];if(prd!==void 0)return{kind:"prd",id:prd.id};const spec=input.specs.filter(item=>item.status==="ready"&&item.prd_id===null).sort(byOrder)[0];if(spec!==void 0)return{kind:"spec",id:spec.id};const task=input.tasks.filter(item=>{const change=changes.get(item.change_id);return item.status==="planned"&&item.started_at===null&&(item.attempt_count??0)===0&&!materialized.has(item.id)&&item.prepared_plan===void 0!==(item.plan_ref===void 0)&&item.depends_on.every(id=>completed.has(id))&&change?.source.type==="task"&&change.source.task_id===item.id&&change.task_ids.includes(item.id)}).sort(byOrder)[0];return task===void 0?null:{kind:"task",id:task.id}}function manualPriority(value){if(typeof value!=="object"||value===null||!("schema_version"in value))return new Map;const priority2=value;if(priority2.schema_version!==1||!Array.isArray(priority2.item_ids)||!priority2.item_ids.every(id=>typeof id==="string"&&/^(PRD|SPEC|TASK)-[A-Z0-9-]+$/.test(id))||new Set(priority2.item_ids).size!==priority2.item_ids.length)return new Map;return new Map(priority2.item_ids.map((id,index)=>[id,index]))}var init_ready_queue_selection=__esm({"src/ready-queue-selection.ts"(){"use strict"}});async function readyNextItem(filesystem,composition){const priorityPath=".agents/dashboard/work-priority.json";const priorityText=await filesystem.exists(priorityPath)?await filesystem.readText(priorityPath):"null";const[prds,specs,tasks,changes,executions]=await Promise.all([composition.prds.list(),composition.specs.list(),composition.tasks.list(),composition.changes.list(),composition.executions.list()]);let priority2=null;try{priority2=JSON.parse(priorityText)}catch{}const selected=selectReadyQueueItem({prds,specs,tasks,changes,executions,priority:priority2});if(selected===null)return{selected:null,reason:"no_eligible_work"};if(selected.kind==="task"){const task=tasks.find(item=>item.id===selected.id);if(task===void 0)throw new UsageError(`Ready Task disappeared: ${selected.id}`);const plan=task.prepared_plan??(task.plan_ref===void 0?null:await composition.materializer.readPreparedPlan(task.plan_ref.execution_id));if(plan===null||plan.source.type!=="task"||plan.source.task_id!==task.id||plan.hash!==task.plan_hash)throw new UsageError(`Ready Task has an inconsistent PreparedPlan: ${task.id}`);await assertPreparedPlanReferences(filesystem,plan)}else{const entity=selected.kind==="prd"?prds.find(item=>item.id===selected.id):specs.find(item=>item.id===selected.id);if(entity===void 0)throw new UsageError(`Ready item disappeared: ${selected.id}`);const plan=await preparedPlanForReadyOrExecute(entity,selected.kind==="prd"?"PRD":"SPEC",selected.id,composition.materializer);if(selected.kind==="prd"&&(plan.source.type!=="prd"||plan.source.prd_id!==selected.id)||selected.kind==="spec"&&(plan.source.type!=="spec"||plan.source.spec_id!==selected.id))throw new UsageError(`Ready ${selected.kind.toUpperCase()} has an inconsistent PreparedPlan: ${selected.id}`);await assertPreparedPlanReferences(filesystem,plan)}return{selected}}var init_v2_ready_queue=__esm({"src/commands/v2-ready-queue.ts"(){"use strict";init_cli_arguments();init_prepared_plan_v22();init_ready_queue_selection();init_v2_lifecycle_materialization()}});async function runTaskV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="recover-release")return runControlledRecoveryCommand("recover-task-release",parsed,filesystem,composition);if(action==="recover-post-publication")return preparePostPublicationRecovery(parsed,filesystem,composition);if(action==="resume-post-publication")return resumePostPublicationClosure(parsed,filesystem,composition,lifecycle);if(action==="relay-post-publication")return preparePostPublicationRelay(parsed,filesystem,composition,lifecycle);if(action==="authorize-post-publication")return authorizePostPublicationRelay(parsed,filesystem,composition,lifecycle);if(action==="bind-post-publication")return bindPostPublicationRelay(parsed,filesystem,composition);if(action==="ready-next")return readyNextItem(filesystem,composition);if(action==="amend-scopes")return amendTaskScopes(parsed,filesystem,composition);if(action==="retarget-open-release")return retargetOpenTaskRelease(parsed,filesystem,composition);if(action==="create"){requireOptions(parsed.options,["title","short-name","objective","requirements","acceptance"]);const timeZone=composition.layout.project.timezone;const taskId=parsed.options.id??createId("TASK",parsed.options["short-name"],{timeZone});const changeId=parsed.options.change??createId("CHG",parsed.options["short-name"],{timeZone});const requirementIds=csvOption(parsed.options.requirements);const acceptanceIds=csvOption(parsed.options.acceptance);const risk2=riskOption(parsed.options.risk);const shortName=parsed.options["short-name"];const{task,change}=await createTaskAndChangeAtomically(filesystem,composition,{id:taskId,changeId,title:parsed.options.title,shortName,objective:parsed.options.objective,targetRelease:await releaseTargetForDraft(filesystem,parsed.options["target-release"]),risk:risk2,priority:priorityOption(parsed.options.priority),owner:parsed.options.owner??null,requirementIds,acceptanceIds,dependsOn:csvOption(parsed.options["depends-on"]),writeScopes:csvOption(parsed.options["write-scopes"]),assuranceRiskSignals:taskAssuranceRiskSignalsOption(parsed.options["assurance-risk-signals"])});return{task,change,artifact_path:composition.tasks.path(task.id),change_path:composition.changes.path(change.id)}}if(action==="prepare"){const id2=requiredEntityId(parsed,2,"Task id");const current=await composition.tasks.read(id2);if(current.task.status==="planned"&&current.task.prepared_plan!==void 0){await assertPreparedPlanReferences(filesystem,current.task.prepared_plan);return{task:current.task,artifact_path:composition.tasks.path(id2),plan_hash:current.task.prepared_plan.hash}}if(parsed.options.plan===void 0&&current.task.depends_on.length>0){throw new UsageError("task prepare with dependencies requires --plan containing the complete DAG")}const timeZone=composition.layout.project.timezone;const executionId=await resolveTaskFirstExecutionId(parsed.options.execution,current.task.id,()=>composition.executions.list());const plan=parsed.options.plan===void 0?taskFirstCommandPlan(current.task,parsed,executionId,timeZone):await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const task=await composition.tasks.setPreparedPlan(id2,plan);const change=plan.blueprints.changes.find(candidate=>candidate.id===task.change_id);if(change===void 0)throw new UsageError(`Prepared plan does not contain Change ${task.change_id}`);await ensureTaskDraftChange(composition,task);await composition.changes.promoteDraft(task.change_id,plannedChangeFromBlueprint(change,plan,task.id));return{task,artifact_path:composition.tasks.path(id2),plan_hash:plan.hash}}if(action==="recover-intake"){requireOptions(parsed.options,["execution"]);const taskId=requiredEntityId(parsed,2,"Task id");const{task}=await composition.tasks.read(taskId);if(task.status!=="executing"||task.plan_ref===void 0)throw new UsageError(`Task has no active canonical plan reference: ${taskId}`);const plan=await composition.materializer.readPreparedPlan(task.plan_ref.execution_id);if(plan.hash!==task.plan_ref.hash||plan.source.type!=="task"||plan.source.task_id!==task.id)throw new UsageError(`Task plan reference cannot be resolved canonically: ${taskId}`);const intake2=(await composition.executions.read(parsed.options.execution)).execution;if(intake2.kind!=="delivery"||intake2.origin.type!=="task"||intake2.origin.task_id!==task.id)throw new UsageError(`Delivery intake does not belong to Task: ${intake2.id}`);const current=intake2;const nodes=plan.dag.nodes.map(node=>{const blueprint=plan.blueprints.tasks.find(candidate=>candidate.id===node.task_id);if(blueprint===void 0)throw new UsageError(`Prepared plan DAG lacks Task blueprint: ${node.task_id}`);return{task_id:node.task_id,change_id:blueprint.change_id,depends_on:node.depends_on}});const planned={...current,kind:"delivery",status:"planned",status_reason:null,plan_revision:plan.revision,plan_hash:plan.hash,policy:plan.policy,dag:{nodes,topological_order:plan.dag.topological_order}};const execution=await composition.executions.promoteDeliveryIntake(current.id,planned);return{task,execution,artifact_path:composition.executions.path(execution.id),recovered:true}}if(action==="execute"){const requestedTaskId=parsed.positionals[2];const plan=parsed.options.plan!==void 0?await readPreparedPlan(filesystem,parsed):await preparedTaskPlan(composition.tasks,composition.materializer,requiredEntityId(parsed,2,"Task id"));await assertPreparedPlanReferences(filesystem,plan);if(plan.source.type!=="task"){throw new UsageError("task execute requires a task-first prepared plan")}if(requestedTaskId!==void 0&&requestedTaskId!==plan.source.task_id)throw new UsageError("Requested Task does not match the prepared plan source");const currentTask=await composition.tasks.read(plan.source.task_id);await assertCurrentReleaseForExecution(filesystem,currentTask.task.target_release,"Task");if(composition.layout.projectConfig?.assurance?.require_final_commit===true)await assertGitDeliveryReady(filesystem.root);await assertTaskExecutionIntakeCompatibleBeforeMutation(filesystem,composition,plan.source.task_id,plan.execution_id);const materialized=await existingTaskFirstMaterialization(plan,composition)??await composition.materializer.execute(plan);const taskId=plan.source.task_id;const task=materialized.tasks.find(candidate=>candidate.id===taskId);if(task===void 0){throw new UsageError(`Task-first plan did not materialize its source Task ${taskId}`)}const change=materialized.changes.find(candidate=>candidate.id===task.change_id);if(change===void 0){throw new UsageError(`Task-first plan did not materialize Change ${task.change_id}`)}assertTaskFirstExecutable(task.status,"Task",task.id);assertTaskFirstExecutable(materialized.execution.status,"Execution",materialized.execution.id);assertTaskFirstExecutable(change.status,"Change",change.id);const run=await ensureTaskOrchestratorRun(task,change.id,materialized.execution.id,parsed,filesystem,composition);let execution=(await composition.executions.read(materialized.execution.id)).execution;if(execution.status==="planned"){execution=await composition.executions.transition(execution.id,"running")}let activeChange=(await composition.changes.read(change.id)).change;if(activeChange.status==="planned"){activeChange=await composition.changes.transition(activeChange.id,"executing")}let activeTask=(await composition.tasks.read(task.id)).task;if(activeTask.status==="planned"){activeTask=await lifecycle.startTask(activeTask.id)}return{...materializationOutput(materialized,composition),execution,changes:[activeChange],tasks:[activeTask],run,run_path:composition.runs.path(run.run_id)}}if(action==="list"){const[tasks,changes]=await Promise.all([composition.tasks.list(),parsed.options.prd===void 0&&parsed.options.spec===void 0?Promise.resolve([]):composition.changes.list()]);const relatedChangeIds=new Set(changes.filter(change=>(parsed.options.prd===void 0||change.source.type==="prd"&&change.source.prd_id===parsed.options.prd)&&(parsed.options.spec===void 0||change.source.type==="spec"&&change.source.spec_id===parsed.options.spec||change.source.type==="prd"&&change.source.spec_id===parsed.options.spec)).map(change=>change.id));const filtered=tasks.filter(task=>parsed.options.prd===void 0&&parsed.options.spec===void 0||relatedChangeIds.has(task.change_id));return listLifecyclePage(filtered,parsed).map(task=>({task:compactPreparedEntity(task),artifact_path:composition.tasks.path(task.id)}))}if(action==="next"){const[tasks,executions]=await Promise.all([composition.tasks.list(),composition.executions.list()]);const completed=new Set(tasks.filter(task=>task.status==="completed").map(task=>task.id));const materialized=new Set(executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id)));return tasks.filter(task=>task.status==="planned"&&materialized.has(task.id)&&task.depends_on.every(dependency=>completed.has(dependency))).map(task=>({task,artifact_path:composition.tasks.path(task.id)}))}const id=requiredEntityId(parsed,2,"Task id");if(action==="show"){return{...await composition.tasks.read(id),artifact_path:composition.tasks.path(id)}}if(action==="start"||action==="resume"||action==="rework"){return runTaskStartCommand(id,action,composition,lifecycle)}if(action==="verify"){const task=await lifecycle.verifyTask(id,csvOption(parsed.options.evidence));return{task,artifact_path:composition.tasks.path(id)}}if(["block","complete","fail"].includes(action??"")){throw new UsageError("Task terminal status is applied only by Gui through run finish")}if(action==="cancel"){const cancelled_run_ids=await cancelTaskRunsForHuman(id,composition,parsed);const result2=await lifecycle.cancelTask(id,"Explicit human cancellation",null);return{...result2,cancelled_run_ids,artifact_path:composition.tasks.path(id)}}throw new UsageError(`Unknown V2 Task action: ${action??""}`)}var init_v2_lifecycle_task=__esm({"src/commands/v2-lifecycle-task.ts"(){"use strict";init_src();init_cli_arguments();init_controlled_recovery_command();init_execution_intake_compatibility();init_git_delivery_preflight();init_post_publication_recovery();init_post_publication_relay();init_prepared_plan_v22();init_release_cycle();init_v2_run_cancellation_and_aggregate();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_release_retarget();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();init_v2_ready_queue()}});async function runPrdV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="finalize"){return finalizeMacro("prd",parsed,composition,()=>runLifecycleV2Command("prd","ready",parsed,filesystem,composition,lifecycle))}if(action==="create"){const creationRunId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);return createPrdWithOptionalPlan({parsed,filesystem,composition,creationRunId})}if(action==="rework"){return createPrdRework({parsed,composition,creationRunId:await creationRunIdForCurrentTurn(parsed,filesystem,composition)})}if(action==="list"){return listLifecyclePage(await composition.prds.list(),parsed).map(prd=>({prd:compactPreparedEntity(prd),artifact_path:composition.prds.path(prd.id)}))}const id=requiredEntityId(parsed,2,"PRD id");if(action==="preflight")return inspectDefinitionPreflight("PRD",id,filesystem,composition);if(action==="show"){return{...await composition.prds.read(id),artifact_path:composition.prds.path(id)}}if(action==="prepare"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const prd=await composition.prds.setPreparedPlan(id,plan);const specs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));return{prd,specs,artifact_path:composition.prds.path(id),plan_hash:plan.hash}}if(action==="ready"){assertDefinitionPreflight(await inspectDefinitionPreflight("PRD",id,filesystem,composition));const current=await composition.prds.read(id);await assertCurrentReleaseForExecution(filesystem,current.prd.target_release,"PRD");const plan=await preparedPlanForReadyOrExecute(current.prd,"PRD",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.prd.status)){throw new UsageError(`PRD cannot move to ready from status ${current.prd.status}: ${id}`)}const selectedSpecs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));for(const spec of selectedSpecs){await assertCurrentReleaseForExecution(filesystem,spec.target_release,"SPEC");if(!new Set(["draft","ready"]).has(spec.status)){throw new UsageError(`SPEC cannot move to ready from status ${spec.status}: ${spec.id}`)}await assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout)}const materialized=materializationOutput(await composition.materializer.execute(plan),composition);const prd=current.prd.status==="draft"?await composition.prds.transition(id,"ready"):current.prd;const specs=await Promise.all(selectedSpecs.map(spec=>spec.status==="draft"?composition.specs.transition(spec.id,"ready"):spec));return{...materialized,prd,specs,artifact_path:composition.prds.path(id)}}if(action==="execute"){assertDefinitionPreflight(await inspectDefinitionPreflight("PRD",id,filesystem,composition));const current=await composition.prds.read(id);await assertCurrentReleaseForExecution(filesystem,current.prd.target_release,"PRD");const plan=await preparedPlanForReadyOrExecute(current.prd,"PRD",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.prd.status)){throw new UsageError(`PRD cannot execute from status ${current.prd.status}: ${id}`)}const selectedSpecs=await Promise.all(specIdsForPrdPlanV2(plan,id).map(async specId=>(await composition.specs.read(specId)).spec));for(const spec of selectedSpecs){await assertCurrentReleaseForExecution(filesystem,spec.target_release,"SPEC");if(!new Set(["draft","ready"]).has(spec.status)){throw new UsageError(`SPEC cannot execute from status ${spec.status}: ${spec.id}`)}await assertSpecImplementationMatchesProject(spec.implementation,filesystem,composition.layout)}const output2=executionOutput(await composition.materializer.execute(plan),composition);const specs=await Promise.all(selectedSpecs.map(async selectedSpec=>{let spec=selectedSpec;if(spec.status==="draft")spec=await composition.specs.transition(spec.id,"ready");return spec.status==="ready"?composition.specs.transition(spec.id,"active"):spec}));if(current.prd.status==="draft")await composition.prds.transition(id,"ready");const preparedPrd=(await composition.prds.read(id)).prd;if(preparedPrd.status==="ready")await composition.prds.transition(id,"active");return{...output2,specs}}if(action==="deliver"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="block"||action==="fail"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="cancel"){throw new UsageError("PRD terminal status is applied only by Gui through run finish")}if(action==="activate"){const prd=await composition.prds.transition(id,"active");return{prd,artifact_path:composition.prds.path(id)}}throw new UsageError(`Unknown V2 PRD action: ${action??""}`)}var init_v2_lifecycle_prd=__esm({"src/commands/v2-lifecycle-prd.ts"(){"use strict";init_src();init_src6();init_attribution_v2();init_cli_arguments();init_controlled_recovery_command();init_conversation_intake();init_definition_preflight();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();init_same_turn_spec_handoff();init_v2_run_cancellation_and_aggregate();init_spec_release_retarget();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle();init_v2_lifecycle_materialization();init_v2_lifecycle_support();init_v2_lifecycle_task();init_v2_ready_queue()}});async function runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle){action=lifecycleActionAlias(area,action);if(area==="prd")return runPrdV2Command(action,parsed,filesystem,composition,lifecycle);if(area==="spec")return runSpecV2Command(action,parsed,filesystem,composition,lifecycle);return runTaskV2Command(action,parsed,filesystem,composition,lifecycle)}async function runSpecV2Command(action,parsed,filesystem,composition,lifecycle){if(action==="revise-implementation")return runControlledRecoveryCommand("revise-spec-implementation",parsed,filesystem,composition);if(action==="finalize"){return finalizeMacro("spec",parsed,composition,()=>runLifecycleV2Command("spec","ready",parsed,filesystem,composition,lifecycle))}if(action==="create"){const creationRunId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);return createSpecWithOptionalPlan({parsed,filesystem,composition,creationRunId})}if(action==="list"){const specs=(await composition.specs.list()).filter(spec=>parsed.options.prd===void 0||spec.prd_id===parsed.options.prd);return listLifecyclePage(specs,parsed).map(spec=>({spec:compactPreparedEntity(spec),artifact_path:composition.specs.path(spec.id)}))}const id=requiredEntityId(parsed,2,"SPEC id");if(action==="preflight")return inspectDefinitionPreflight("SPEC",id,filesystem,composition);if(action==="show"){return{...await composition.specs.read(id),artifact_path:composition.specs.path(id)}}if(action==="retarget-release"){requireOptions(parsed.options,["from","to","run"]);return retargetOwnerSpecRelease(filesystem,composition,{specId:id,from:parsed.options.from,to:parsed.options.to,actorRunId:parsed.options.run})}if(action==="prepare"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);const spec=await composition.specs.setPreparedPlan(id,plan);return{spec,artifact_path:composition.specs.path(id),plan_hash:plan.hash}}if(action==="ready"){assertDefinitionPreflight(await inspectDefinitionPreflight("SPEC",id,filesystem,composition));const current=await composition.specs.read(id);await assertCurrentReleaseForExecution(filesystem,current.spec.target_release,"SPEC");const plan=await preparedPlanForReadyOrExecute(current.spec,"SPEC",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(!new Set(["draft","ready"]).has(current.spec.status)){throw new UsageError(`SPEC cannot move to ready from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const materialized=materializationOutput(await composition.materializer.execute(plan),composition);const spec=current.spec.status==="draft"?await composition.specs.transition(id,"ready"):current.spec;return{...materialized,spec,artifact_path:composition.specs.path(id)}}if(action==="execute"){const current=await composition.specs.read(id);const sameTurn=await inspectSameTurnSpecHandoff(current.spec,composition,filesystem);if(sameTurn?.successor===null||sameTurn?.successor===void 0){assertDefinitionPreflight(await inspectDefinitionPreflight("SPEC",id,filesystem,composition))}await assertCurrentReleaseForExecution(filesystem,current.spec.target_release,"SPEC");const plan=await preparedPlanForReadyOrExecute(current.spec,"SPEC",id,composition.materializer);await assertPreparedPlanReferences(filesystem,plan);if(sameTurn?.successor!==null&&sameTurn?.successor!==void 0){const execution=(await composition.executions.read(plan.execution_id)).execution;if(sameTurn.successor.run.execution_id!==execution.id){throw new UsageError("Same-turn handoff replay targets a different Execution")}const claimedRunId=await composition.executions.claimSpecHandoff({clientTurnId:sameTurn.clientTurnId,interactionExecutionId:sameTurn.predecessor.run.execution_id,executionId:execution.id,specId:id,predecessorRunId:sameTurn.predecessor.run.run_id,proposedSuccessorRunId:sameTurn.successor.run.run_id,authorizationSha256:sameTurn.authorizationSha256});if(claimedRunId!==sameTurn.successor.run.run_id){throw new UsageError("Same-turn handoff claim identifies another delivery owner")}return{execution,run:sameTurn.successor.run,run_path:composition.runs.path(sameTurn.successor.run.run_id),artifact_path:composition.executions.path(execution.id),reused:true}}if(sameTurn!==null&&current.spec.status!=="ready"){throw new UsageError("Same-turn SPEC handoff requires ready status")}if(!new Set(["draft","ready"]).has(current.spec.status)){throw new UsageError(`SPEC cannot execute from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const materialized=await composition.materializer.execute(plan);const output2=executionOutput(materialized,composition);let deliveryRun=null;if(sameTurn!==null){let execution=(await composition.executions.read(plan.execution_id)).execution;if(execution.status==="planned"){execution=await composition.executions.transition(execution.id,"running")}const predecessor=sameTurn.predecessor.run;const runId=await composition.executions.claimSpecHandoff({clientTurnId:sameTurn.clientTurnId,interactionExecutionId:predecessor.execution_id,executionId:execution.id,specId:id,predecessorRunId:predecessor.run_id,proposedSuccessorRunId:createId("RUN","spec-delivery",{timeZone:composition.layout.project.timezone}),authorizationSha256:sameTurn.authorizationSha256});const existing=await composition.runs.read(runId).catch(()=>null);if(existing!==null){throw new UsageError("Same-turn successor exists without a matching active owner")}const start={id:runId,shortName:"spec-delivery",phase:"execution",runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:true,executionKind:"delivery",executionEligibility:[],entrypoint:"spec",workType:predecessor.work_type,client:predecessor.client,agent:predecessor.agent,...predecessor.agent_name===void 0?{}:{agentName:predecessor.agent_name},provider:predecessor.provider,model:predecessor.model,...predecessor.reasoning_effort===void 0?{}:{reasoningEffort:predecessor.reasoning_effort},clientThreadId:sameTurn.clientThreadId,clientTurnId:sameTurn.clientTurnId,conversationId:predecessor.conversation_id,executionId:execution.id,specId:id,prdId:current.spec.prd_id,continuationOfRunId:predecessor.run_id,sameTurnHandoff:{predecessor_run_id:predecessor.run_id,target_spec_id:id,authorization_sha256:sameTurn.authorizationSha256},...predecessor.developer_identity===void 0?{}:{developerIdentity:predecessor.developer_identity}};await validateRunV2Attribution(start,composition);deliveryRun=(await composition.runs.start(start)).started}if(current.spec.status==="draft")await composition.specs.transition(id,"ready");const preparedSpec=(await composition.specs.read(id)).spec;if(preparedSpec.status==="ready")await composition.specs.transition(id,"active");return deliveryRun===null?output2:{...output2,execution:(await composition.executions.read(plan.execution_id)).execution,run:deliveryRun,run_path:composition.runs.path(deliveryRun.run_id)}}if(action==="deliver"){throw new UsageError("SPEC terminal status is applied only by Gui through run finish")}if(action==="block"||action==="fail"){throw new UsageError("SPEC terminal status is applied only by Gui through run finish")}if(action==="cancel"){const changes=(await composition.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const executions=(await composition.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id);const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const cancelled_run_ids=(await Promise.all([...taskIds].map(taskId=>cancelTaskRunsForHuman(taskId,composition,parsed)))).flat();const result2=await lifecycle.cancelSpec(id);return{...result2,cancelled_run_ids,artifact_path:composition.specs.path(id)}}if(action==="activate"){const spec=await composition.specs.transition(id,"active");return{spec,artifact_path:composition.specs.path(id)}}throw new UsageError(`Unknown V2 SPEC action: ${action??""}`)}async function creationRunIdForCurrentTurn(parsed,filesystem,composition){if(parsed.options.run!==void 0){return(await composition.runs.read(parsed.options.run)).run.run_id}const invocation2=await resolveRunClientInvocation(filesystem,"codex");const intake2=await findIntakeForExactTurn(composition,"codex",invocation2);return intake2?.run.run_id??null}var init_v2_lifecycle=__esm({"src/commands/v2-lifecycle.ts"(){"use strict";init_src();init_src6();init_attribution_v2();init_cli_arguments();init_controlled_recovery_command();init_conversation_intake();init_definition_preflight();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();init_same_turn_spec_handoff();init_v2_run_cancellation_and_aggregate();init_spec_release_retarget();init_task_assurance_options();init_task_change_creation();init_task_first_command_plan();init_task_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();init_v2_lifecycle_prd();init_v2_lifecycle_support();init_v2_lifecycle_task();init_v2_ready_queue();init_v2_lifecycle_materialization()}});function isHostTerminalOnlyOpenReconciliation(area,action,parsed){return(area==="run"||area==="run-v2")&&action==="reconcile"&&parsed.flags.has("open")&&parsed.flags.has("host-terminal-only")}function isBoundedActiveTelemetryCapture(area,action,parsed){return(area==="run"||area==="run-v2")&&action==="usage"&&(parsed.flags.has("active")||parsed.flags.has("recent"))&&parsed.flags.has("disable-codex-raw")}function isIdempotentLifecycleReplay(area,action,result2){if(!((area==="run"||area==="run-v2"||area==="conversation")&&action==="start")){return false}return typeof result2==="object"&&result2!==null&&"reused"in result2&&result2.reused===true}function isNarrowSubagentTerminalCapture(area,action){return area==="subagent"&&(action==="capture-terminal"||action==="reconcile-stop")}function isNarrowRunFinish(area,action){return(area==="run"||area==="run-v2")&&action==="finish"}var init_v2_router_classification=__esm({"src/commands/v2-router-classification.ts"(){"use strict"}});var V2_COMMAND_AREAS;var init_v2_command_areas=__esm({"src/commands/v2-command-areas.ts"(){"use strict";V2_COMMAND_AREAS=new Set(["plan","prd","spec","change","task","execution","decision","evidence","validation","run","run-v2","conversation","developer","subagent"])}});var v2_router_exports={};__export(v2_router_exports,{V2_COMMAND_AREAS:()=>V2_COMMAND_AREAS,createV2Composition:()=>createV2Composition,runHostTerminalOnlyReconcile:()=>runHostTerminalOnlyReconcile,runV2Command:()=>runV2Command});function createV2Composition(filesystem,layout){const storageMode=layout.projectConfig?.tracking.storage_mode??"tracked_sanitized";return{filesystem,layout,prds:new PrdV2Repository(filesystem,layout),specs:new DeliverySpecV2Repository(filesystem,layout),changes:new ChangeV2Repository(filesystem,layout),tasks:new TaskV2Repository(filesystem,layout),executions:new ExecutionV2Repository(filesystem,layout),materializer:new PreparedPlanV2Materializer(filesystem,layout),decisions:new DecisionV2Repository(filesystem,layout),runs:new RunV2Repository(filesystem,storageMode==="local_only"?{storageMode:"local_only",localBasePath:".local/runs"}:{storageMode:"tracked_sanitized",layout})}}async function runV2Command(area,action,parsed,filesystem,layout){if(area==="conversation"&&action==="resolve"){return preview(parsed,filesystem,layout)}if(area==="change"&&action==="narrative"&&!parsed.flags.has("apply"))return runV2CommandUnlocked(area,action,parsed,filesystem,layout);if((area==="spec"&&action==="revise-implementation"||area==="task"&&["recover-release","recover-post-publication"].includes(action??""))&&!parsed.flags.has("apply"))return runV2CommandUnlocked(area,action,parsed,filesystem,layout);if(isHostTerminalOnlyOpenReconciliation(area,action,parsed)){return runHostTerminalOnlyReconcile(parsed,filesystem,layout)}if(area==="conversation"&&action==="start"){return capture(parsed,filesystem,layout,intake2=>runV2CommandUnlocked(area,action,parsed,filesystem,layout,intake2))}if(area==="task"&&action==="migrate-autonomy"&&parsed.flags.has("confirm"))return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout));if(area==="task"&&action==="assurance"&&(parsed.options["applicability-map"]!==void 0||parsed.options["inherit-applicability-attempt"]!==void 0))return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout));if(!isLifecycleManifestMutation(action)||area==="validation"&&["execute","batch"].includes(action??"")||area==="task"&&["commit","workspace","assurance","recovery-status"].includes(action??"")||isNarrowSubagentTerminalCapture(area,action)||isNarrowRunFinish(area,action)||isBoundedActiveTelemetryCapture(area,action,parsed)){return runV2CommandUnlocked(area,action,parsed,filesystem,layout)}return withLifecycleCanonicalMutationLock(filesystem,()=>runV2CommandUnlocked(area,action,parsed,filesystem,layout),area==="conversation"&&action==="start"?{timeout_ms:15e3}:{})}async function runHostTerminalOnlyReconcile(parsed,filesystem,layout,dependencies={}){const createComposition=dependencies.createComposition??(()=>createV2Composition(filesystem,layout));const preflight=dependencies.preflight??hostTerminalOnlyPreflight;const withLock=dependencies.withLock??(operation=>withLifecycleCanonicalMutationLock(filesystem,operation));const execute4=dependencies.execute??(()=>runV2CommandUnlocked("run","reconcile",parsed,filesystem,layout));const initial=await preflight(createComposition(),filesystem);if(initial.kind==="no-op")return initial.result;return withLock(execute4)}async function runV2CommandUnlocked(area,action,parsed,filesystem,layout,intake2){const composition=createV2Composition(filesystem,layout);if(area==="task"&&action==="recovery-status")return taskRecoveryStatus(parsed.positionals[2]??parsed.options.id??"",composition);if(area==="task"&&action==="assurance")return runTaskAssuranceCommand(parsed,filesystem,composition);if(area==="task"&&action==="workspace")return runTaskWorkspaceAction(parsed,filesystem,composition);if(area==="validation"&&action==="batch")return runValidationBatchCommand(parsed,filesystem,composition);if(action==="list"&&parsed.options.view!=="full"){return manifestList(area==="run-v2"?"run":area,parsed,filesystem)}const lifecycle=new LifecycleV2Gate(filesystem,layout,composition);let result2;let manifestSyncedDuringMutation=false;if(area==="plan")return runPlanV2Command(action,parsed,filesystem,layout);if(area==="developer")return runDeveloperIdentityCommand(action,parsed,filesystem);if(area==="prd")result2=await runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle);else if(area==="spec")result2=await runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle);else if(area==="change")result2=await runChangeV2Command(action,parsed,composition,lifecycle);if(area==="conversation"){result2=await command(action,parsed,composition,filesystem,lifecycle,intake2)}else if(area==="subagent"){result2=await runSubagentV2Command(action,parsed,composition,filesystem,lifecycle,async captured=>{await syncLifecycleManifestResult(captured,"subagent",parsed,composition,filesystem);manifestSyncedDuringMutation=true})}else if(area==="task"){if(action==="migrate-autonomy")return migrateTaskAutonomy(parsed.positionals[2]??parsed.options.id??"",parsed,composition);result2=["repair-verification","settle-repair"].includes(action??"")?await runTaskVerificationRepairCommand(parsed,composition):action==="commit"?await runTaskCommitCommand(parsed,filesystem,composition):await runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}else if(area==="execution")result2=await runExecutionV2Command(action,parsed,composition,lifecycle,async(id,options)=>{const source=(await composition.executions.read(id)).execution.origin.type;const config2=layout.projectConfig;const managed=config2!==null&&!options.flags.has("materialize-only")&&resolveExecutionRuntime(config2,void 0,source).runtime==="autonomous";return runAutonomousExecutionCommand(id,options,composition,managed?createAutonomousProductionDriver(filesystem,config2,source):void 0,await loadAgentCatalog(filesystem))});else if(area==="decision")result2=await runDecisionV2Command(action,parsed,filesystem,composition);else if(area==="evidence")result2=parsed.options.spec!==void 0||parsed.options.execution!==void 0?await runParentEvidenceCommand(action??"",parsed,filesystem,composition):await runEvidenceV2Command(action,parsed,filesystem,composition);else if(area==="validation")result2=parsed.options.spec!==void 0||parsed.options.execution!==void 0?await runParentValidationCommand(action??"",parsed,filesystem,composition):await runValidationV2Command(action,parsed,filesystem,composition);else if(area==="run"||area==="run-v2"){result2=await runRunV2Command(action,parsed,composition,filesystem,lifecycle)}else if(!["prd","spec","change","task","conversation","subagent","evidence","validation"].includes(area)){throw new UsageError(`Unknown V2 command: ${area} ${action??""}`.trim())}if(isLifecycleManifestMutation(action)&&!(area==="change"&&action==="narrative")&&!manifestSyncedDuringMutation&&!isIdempotentLifecycleReplay(area,action,result2)){if(area==="validation"&&action==="execute"){return syncValidationProjection(result2,parsed.options.id,()=>syncLifecycleManifestResult(result2,area,parsed,composition,filesystem))}await syncLifecycleManifestResult(result2,area==="run-v2"?"run":area,parsed,composition,filesystem)}if((area==="run"||area==="run-v2")&&action==="finish")return maybeCloseTerminalTaskWorkspace(filesystem,composition,parsed.positionals[2]??parsed.options.id,result2);return result2}async function runDefinitionLifecycleCommand(area,action,parsed,filesystem,composition,lifecycle){const definitionActions=new Set(["create","rework","prepare"]);if(!definitionActions.has(action??"")){return runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}const runId=await creationRunIdForCurrentTurn(parsed,filesystem,composition);await assertActiveDefinitionRun({area,runId,filesystem,composition,reworkAuthoring:action==="rework"});return runLifecycleV2Command(area,action,parsed,filesystem,composition,lifecycle)}var init_v2_router=__esm({"src/commands/v2-router.ts"(){"use strict";init_src5();init_src6();init_src7();init_autonomous_execution_command();init_autonomous_production_driver();init_candidate_commit_command();init_candidate_validation_batch_command();init_cli_arguments();init_conversation_stop_intake();init_developer_identity_command();init_evidence_commands_v2();init_execution_commands_v2();init_execution_runtime_config();init_governance_commands_v2();init_lifecycle_manifest_commands();init_lifecycle_v2();init_open_work_host_preflight();init_parent_assurance_v1();init_prepared_plan_v22();init_run_agent_identity();init_subagent_command_v2();init_task_assurance_command();init_task_autonomy_migration();init_task_recovery_status();init_task_verification_repair();init_task_workspace_closure();init_task_workspace_routing();init_validation_commands_v2();init_validation_projection();init_definition_run_gate();init_v2_lifecycle();init_v2_router_classification();init_v2_run();init_v2_command_areas()}});init_src2();import{basename as basename9,dirname as dirname21,resolve as resolve31}from"node:path";import{pathToFileURL}from"node:url";var import_parser=__toESM(require_lib(),1);function resolveSupabaseProfile(value){if(!isRecord(value)||value.id!==SUPABASE_EDGE_PROFILE.id){return unsupported2("explicit supabase-edge-functions profile is required")}if(value.workspaces!==void 0||value.scopes!==void 0||value.importMap!==void 0){return unsupported2("unsupported workspace, scope, or importMap configuration")}const map2=parseDenoImportMap(value.deno_json??value.deno_import_map);return map2===null?unsupported2("missing or malformed deno.json or deno_import_map"):{profile:{...SUPABASE_EDGE_PROFILE,denoImportMap:map2},diagnostics:[]}}function supabaseEntrypointFindings(units,profile){if(profile.id!==SUPABASE_EDGE_PROFILE.id)return[];const endpoints=new Set(units.map(unit=>normalizePath(unit.path).match(/^supabase\/functions\/([^/]+)\//)?.[1]).filter(name=>name!==void 0&&name!=="_shared"));return[...endpoints].flatMap(endpoint=>{const entrypoint=profile.functionEntrypoints?.[endpoint]??"index.ts";return units.some(unit=>normalizePath(unit.path)===`supabase/functions/${endpoint}/${entrypoint}`)?[]:[finding("supabase-function-missing-entrypoint",`supabase/functions/${endpoint}`,1,`Function ${endpoint} has no ${entrypoint}`)]})}function isSupabasePrivateFunctionImport(source,target){const sourceFunction=source.match(/^supabase\/functions\/([^/]+)\//)?.[1];const targetFunction=target.match(/^supabase\/functions\/([^/]+)\//)?.[1];if(sourceFunction===void 0||targetFunction===void 0)return false;if(sourceFunction==="_shared"&&targetFunction==="_shared")return false;if(targetFunction==="_shared")return!/^supabase\/functions\/_shared\/index\.(?:[cm]?ts|[cm]?js)$/.test(target);return sourceFunction!==targetFunction}function aliasesForSource(profile,sourcePath){const imports=profile.denoImportMap;if(imports===void 0)return profile.importAliases??[];const functionName=sourcePath.match(/^supabase\/functions\/([^/]+)\//)?.[1];const scoped=functionName===void 0?void 0:imports.functionImports?.[functionName];return[...toImportAliases(scoped??{},`supabase/functions/${functionName??""}`),...toImportAliases(imports.imports,"supabase/functions")]}function unsupported2(reason){return{profile:{...SUPABASE_EDGE_PROFILE,supported:false,notApplicableReason:reason},diagnostics:[`supabase-profile: ${reason}`]}}function toImportAliases(entries,basePath){return Object.entries(entries).map(([prefix,target])=>({prefix,target:normalizeImportTarget(target,basePath)}))}function normalizeImportTarget(target,basePath){const trailingSlash=target.endsWith("/");const normalized=target.startsWith(".")?normalizePath(`${basePath}/${target}`):target;return trailingSlash&&!normalized.endsWith("/")?`${normalized}/`:normalized}function parseDenoImportMap(value){if(!isRecord(value)||!isStringMap(value.imports))return null;if(value.scopes!==void 0||value.workspace!==void 0||value.workspaces!==void 0||value.importMap!==void 0)return null;if(value.function_imports===void 0)return{imports:value.imports};if(!isRecord(value.function_imports))return null;const functionImports={};for(const[functionName,imports]of Object.entries(value.function_imports)){if(!isStringMap(imports))return null;functionImports[functionName]=imports}return{imports:value.imports,functionImports}}function isStringMap(value){return isRecord(value)&&Object.entries(value).every(([prefix,target])=>typeof target==="string"&&prefix.length>0&&target.length>0&&prefix.endsWith("/")===target.endsWith("/"))}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function normalizePath(path){const segments2=[];for(const segment2 of path.replace(/\\/g,"/").split("/")){if(segment2===""||segment2===".")continue;if(segment2==="..")segments2.pop();else segments2.push(segment2)}return segments2.join("/")}function finding(rule,path,line,message2){return{rule,path,line,message:message2}}function resolvedImports(unit,resolveImport){const imports=[];const add=(source,line,unverifiedDynamic=false)=>{const specifier=staticModuleSpecifier(source);if(specifier===void 0){if(unverifiedDynamic)imports.push({module:"<dynamic import>",resolvedModule:null,line:typeof line==="number"?line:1,unverified:true});return}const module=specifier.replace(/\\/g,"/");imports.push({module,resolvedModule:resolveImport(unit.path,module),line:typeof line==="number"?line:1})};const visit=node=>{if(!isRecord2(node))return;const line=sourceLine(node);if(["ImportDeclaration","ExportNamedDeclaration","ExportAllDeclaration","ImportExpression","TSImportType"].includes(String(node.type))){add(node.type==="TSImportType"?node.argument:node.source,line,node.type==="ImportExpression")}else if(node.type==="CallExpression"&&isRecord2(node.callee)&&node.callee.type==="Import"){add(Array.isArray(node.arguments)?node.arguments[0]:void 0,line,true)}else if(node.type==="CallExpression"&&isRecord2(node.callee)&&node.callee.type==="Identifier"&&node.callee.name==="require"){add(Array.isArray(node.arguments)?node.arguments[0]:void 0,line,true)}else if(node.type==="TSImportEqualsDeclaration"&&isRecord2(node.moduleReference)){add(node.moduleReference.expression,line)}for(const value of Object.values(node)){if(Array.isArray(value))for(const child of value)visit(child);else if(value!==node.loc)visit(value)}};visit((0,import_parser.parse)(unit.content,{sourceType:"unambiguous",plugins:unit.path.endsWith(".tsx")||unit.path.endsWith(".jsx")?["typescript","jsx"]:["typescript"]}));return imports}function importResolver(units,profile){const knownPaths=new Set(units.map(unit=>normalizePath2(unit.path)));const sourceAliases=new Map(units.map(unit=>[normalizePath2(unit.path),unit.importAliases??[]]));return(sourcePath,specifier)=>{const candidates=importCandidates(normalizePath2(sourcePath),specifier.replace(/\\/g,"/"),[...sourceAliases.get(normalizePath2(sourcePath))??[],...aliasesForSource(profile,normalizePath2(sourcePath))]);for(const candidate of candidates){const resolved=resolveKnownPath(candidate,knownPaths);if(resolved!==null)return resolved}return candidates[0]??null}}function normalizePath2(path){const segments2=[];for(const segment2 of path.replace(/\\/g,"/").split("/")){if(segment2===""||segment2===".")continue;if(segment2==="..")segments2.pop();else segments2.push(segment2)}return segments2.join("/")}function importCandidates(sourcePath,specifier,aliases){if(specifier.startsWith("."))return[normalizePath2(`${dirname2(sourcePath)}/${specifier}`)];return aliases.filter(alias=>specifier===alias.prefix||alias.prefix.endsWith("/")&&specifier.startsWith(alias.prefix)).sort((left,right)=>right.prefix.length-left.prefix.length).map(alias=>normalizePath2(`${alias.target}${specifier.slice(alias.prefix.length)}`))}function resolveKnownPath(candidate,knownPaths){const extensions=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];const sourceExtension=/\.(?:[cm]?[jt]sx?)$/.test(candidate)?candidate.replace(/\.(?:[cm]?[jt]sx?)$/,""):candidate;const options=[candidate,sourceExtension,...extensions.map(extension=>`${candidate}${extension}`),...extensions.map(extension=>`${candidate}/index${extension}`),...extensions.map(extension=>`${sourceExtension}${extension}`),...extensions.map(extension=>`${sourceExtension}/index${extension}`)];return options.find(option=>knownPaths.has(option))??null}function staticModuleSpecifier(source){if(!isRecord2(source))return void 0;if(typeof source.value==="string")return source.value;if(source.type!=="TemplateLiteral"||!Array.isArray(source.expressions)||source.expressions.length!==0||!Array.isArray(source.quasis))return void 0;const quasi=source.quasis[0];return isRecord2(quasi)&&isRecord2(quasi.value)&&typeof quasi.value.cooked==="string"?quasi.value.cooked:void 0}function sourceLine(node){const location=node.loc;return isRecord2(location)&&isRecord2(location.start)&&typeof location.start.line==="number"?location.start.line:void 0}function dirname2(path){return path.slice(0,Math.max(0,path.lastIndexOf("/")))}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var import_parser2=__toESM(require_lib(),1);function workspaceImportAliases(manifests){const documents=new Map(manifests.map(({path,content})=>[normalizePath2(path),parseDocument3(path,content)]));const packages=[];for(const[path,document]of documents){if(!path.endsWith("package.json")||typeof document.name!=="string")continue;const entries=document.exports;if(isRecord3(entries)&&Object.keys(entries).some(key=>key.startsWith("."))){for(const[subpath,target]of Object.entries(entries)){addTargets(packages,document.name+(subpath==="."?"":subpath.slice(1)),target,directory(path))}}else{addTargets(packages,document.name,entries??document.module??document.main??"./index.ts",directory(path))}}const resolved=new Map;function configOptions(path,chain=[]){const cached2=resolved.get(path);if(cached2)return cached2;if(chain.includes(path))throw new Error(`Cyclic architecture tsconfig inheritance: ${path}`);const document=documents.get(path);if(!document)throw new Error(`Architecture tsconfig is unavailable: ${path}`);let inherited={};const parents=document.extends===void 0?[]:Array.isArray(document.extends)?document.extends:[document.extends];for(const parent of parents){if(typeof parent!=="string"||!parent.startsWith(".")){throw new Error(`Architecture cannot verify external tsconfig inheritance: ${path}`)}const candidate=normalizePath2(`${directory(path)}/${parent}`);inherited={...inherited,...configOptions(documents.has(candidate)||candidate.endsWith(".json")?candidate:`${candidate}.json`,[...chain,path])}}const options=isRecord3(document.compilerOptions)?document.compilerOptions:{};const result2={...inherited};if(options.baseUrl!==void 0){if(typeof options.baseUrl!=="string")throw new Error(`Invalid architecture tsconfig baseUrl: ${path}`);result2.baseUrl=normalizePath2(`${directory(path)}/${options.baseUrl}`)}if(options.paths!==void 0){if(!isRecord3(options.paths))throw new Error(`Invalid architecture tsconfig paths: ${path}`);result2.paths=options.paths;result2.pathsBase=directory(path)}resolved.set(path,result2);return result2}function configAliases(path){const options=configOptions(path);const base=options.baseUrl??options.pathsBase??directory(path);const aliases=[];for(const[prefix,targets]of Object.entries(options.paths??{})){if(!Array.isArray(targets)||targets.length===0||!targets.every(target=>typeof target==="string")){throw new Error(`Invalid architecture tsconfig path targets: ${path}`)}for(const target of targets)addAlias(aliases,prefix,String(target),base)}return aliases}return sourcePath=>{const nearest=[...documents.keys()].filter(path=>path.endsWith("tsconfig.json")&&(directory(path)===""||sourcePath.startsWith(`${directory(path)}/`))).sort((a,b)=>b.length-a.length)[0];return[...nearest?configAliases(nearest):[],...packages]}}function addTargets(aliases,prefix,target,base){if(typeof target==="string")addAlias(aliases,prefix,target,base);else if(Array.isArray(target))for(const entry2 of target)addTargets(aliases,prefix,entry2,base);else if(isRecord3(target))for(const entry2 of Object.values(target))addTargets(aliases,prefix,entry2,base)}function addAlias(aliases,prefix,target,base){const stars=(prefix.match(/\*/g)??[]).length;if(stars>1||stars===1&&(!prefix.endsWith("*")||!target.endsWith("*"))){throw new Error(`Architecture cannot verify non-prefix import mapping: ${prefix}`)}if(/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/|\\)/.test(target)){throw new Error(`Architecture import mapping escapes the workspace: ${prefix}`)}const source=stars?prefix.slice(0,-1):prefix;const destination=stars?target.slice(0,-1):target;const joined=`${base}/${destination}`;let depth=0;for(const segment2 of joined.split("/")){if(segment2==="..")depth-=1;else if(segment2&&segment2!==".")depth+=1;if(depth<0)throw new Error(`Architecture import mapping escapes the workspace: ${prefix}`)}aliases.push({prefix:source,target:normalizePath2(joined)+(destination.endsWith("/")?"/":"")})}function parseDocument3(path,content){const value=literal2((0,import_parser2.parseExpression)(content));if(!isRecord3(value))throw new Error(`Architecture manifest must be an object: ${path}`);return value}function literal2(node){if(!isRecord3(node))throw new Error("Invalid architecture manifest");if(["StringLiteral","NumericLiteral","BooleanLiteral"].includes(String(node.type)))return node.value;if(node.type==="NullLiteral")return null;if(node.type==="ArrayExpression"&&Array.isArray(node.elements))return node.elements.map(literal2);if(node.type==="ObjectExpression"&&Array.isArray(node.properties)){const entries=node.properties.map(property=>{if(!isRecord3(property)||property.type!=="ObjectProperty"||property.computed||!isRecord3(property.key)||property.key.type!=="StringLiteral"){throw new Error("Architecture manifests must contain literal JSON properties")}return[String(property.key.value),literal2(property.value)]});return Object.fromEntries(entries)}if(node.type==="UnaryExpression"&&node.operator==="-"&&isRecord3(node.argument)&&node.argument.type==="NumericLiteral")return-Number(node.argument.value);throw new Error("Architecture manifests must contain only JSON literals")}function directory(path){return path.slice(0,Math.max(0,path.lastIndexOf("/")))}function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var TYPESCRIPT_PROFILE={id:"zaip-aios-stack",extensions:[".ts",".tsx"],frameworkPackages:["hono","react","kysely","drizzle-orm","express","fastify"],queryPatterns:["/queries/",".query.","QueryHandler"],writePortPatterns:["WritePort","CommandRepository","UnitOfWork"],supported:true};var SUPABASE_EDGE_PROFILE={...TYPESCRIPT_PROFILE,id:"supabase-edge-functions",frameworkPackages:[...TYPESCRIPT_PROFILE.frameworkPackages,"@supabase/supabase-js"],supported:true};function validateArchitecture(units,profile=TYPESCRIPT_PROFILE){if(!profile.supported&&!profile.notApplicableReason){throw new Error(`Unsupported profile ${profile.id} requires a notApplicableReason`)}return[...validateAll(units,profile),...supabaseEntrypointFindings(units,profile)].filter(item=>["domain-framework-dependency","application-concrete-adapter","adapter-inward-dependency","frontend-server-dependency","backend-ui-dependency","dashboard-backend-app","inner-layer-app-dependency","site-dashboard-dependency","package-module-dependency","supabase-private-function-import","supabase-function-missing-entrypoint","unresolved-dynamic-import"].includes(item.rule))}function validateCqrs(units,profile=TYPESCRIPT_PROFILE){return validateAll(units,profile).filter(item=>["query-write-port","query-side-effect","route-direct-database","database-row-leak","command-missing-idempotency","query-missing-account-context"].includes(item.rule))}function validateModules(units,profile=TYPESCRIPT_PROFILE){const findings=validateAll(units,profile).filter(item=>item.rule==="cross-module-storage");const modules=new Set(units.map(unit=>moduleName(unit.path)).filter(name=>name!==null));for(const module of modules){if(!units.some(unit=>isCompositionRoot(unit.path,module))){findings.push(finding2("module-missing-composition-root",`modules/${module}`,1,`Module ${module} has no composition-root.ts`))}}return findings}function validateProfileContract(value){if(typeof value!=="object"||value===null)return[{field:"$",message:"Profile must be an object"}];const profile=value;const findings=[];if(typeof profile.id!=="string"||profile.id.length===0)findings.push({field:"id",message:"Profile id is required"});if(profile.status!=="supported"&&profile.status!=="experimental")findings.push({field:"status",message:"Profile status must be supported or experimental"});if(!Array.isArray(profile.extensions)||profile.extensions.length===0)findings.push({field:"extensions",message:"At least one extension is required"});if(!Array.isArray(profile.invariants)||profile.invariants.length===0)findings.push({field:"invariants",message:"Profile invariants are required"});if(profile.status==="supported"){const conventions=profile.conventions;const apps=conventions?.apps;const sourceLimits=conventions?.source_limits;if(!conventions||!apps||apps.frontend!=="apps/frontend"||apps.backend!=="apps/backend"||apps.site!=="apps/site"||conventions.modules!=="modules"||conventions.packages!=="packages"||conventions.e2e!=="tests/e2e"){findings.push({field:"conventions",message:"Supported profiles require canonical apps/frontend, apps/backend, apps/site, modules, packages and tests/e2e paths"})}if(!sourceLimits||!Number.isInteger(sourceLimits.warning_lines)||!Number.isInteger(sourceLimits.error_lines)||Number(sourceLimits.warning_lines)!==400||Number(sourceLimits.error_lines)!==800){findings.push({field:"conventions.source_limits",message:"Supported profiles require source-size limits of 400 warning and 800 error lines"})}const commands=profile.commands;if(!commands||typeof commands.test!=="string"||typeof commands.typecheck!=="string"){findings.push({field:"commands",message:"Supported profiles require test and typecheck commands"})}}return findings}function validateAll(units,profile){const findings=[];const resolveImport=importResolver(units,profile);for(const unit of units){const normalizedPath=unit.path.replace(/\\/g,"/");const layer=detectLayer(normalizedPath);const imports=resolvedImports(unit,resolveImport);if(isDashboardBackendApp(normalizedPath)){findings.push(finding2("dashboard-backend-app",unit.path,1,"The local dashboard is frontend-only; move loopback projection runtime code to .agents/dashboard/packages/local-runtime"))}for(const imported of imports){const resolved=imported.resolvedModule??imported.module;const targetLayer=detectLayer(resolved);if(imported.unverified&&isArchitecturalSource(normalizedPath)){findings.push(finding2("unresolved-dynamic-import",unit.path,imported.line,"Dynamic import cannot be resolved statically; use an explicit import or an approved boundary adapter"))}if(isFrontendRuntimeSource(normalizedPath)&&(isServerOnlyDependency(imported.module)||isBackendApp(resolved))){findings.push(finding2("frontend-server-dependency",unit.path,imported.line,`Frontend imports server-only dependency ${imported.module}`))}if(isBackendApp(normalizedPath)&&isUiRuntimeDependency(imported.module)){findings.push(finding2("backend-ui-dependency",unit.path,imported.line,`Backend imports UI runtime dependency ${imported.module}`))}if(isInnerLibrary(normalizedPath)&&importsApplication(imported.module)){findings.push(finding2("inner-layer-app-dependency",unit.path,imported.line,`Inner module/package imports application ${imported.module}`))}if(isPublicSite(normalizedPath)&&importsDashboardOrAgentState(imported.module)){findings.push(finding2("site-dashboard-dependency",unit.path,imported.line,`Public site imports private dashboard or agent state ${imported.module}`))}if(layer==="domain"&&(isFramework(resolved,profile)||resolved.startsWith("node:")||targetLayer!==null&&targetLayer!=="domain")){findings.push(finding2("domain-framework-dependency",unit.path,imported.line,`Domain imports ${imported.module}`))}if(layer==="application"&&["adapters","infrastructure"].includes(targetLayer??"")){findings.push(finding2("application-concrete-adapter",unit.path,imported.line,`Application imports concrete ${targetLayer}`))}if(["domain","application"].includes(layer??"")&&targetLayer==="adapters"){findings.push(finding2("adapter-inward-dependency",unit.path,imported.line,`Inner layer imports adapter ${imported.module}`))}const sourceModule=moduleName(normalizedPath);const targetModule=moduleName(resolved);if(isPackage(normalizedPath)&&targetModule!==null&&!isDashboardRuntimePublicBoundary(normalizedPath,resolved)){findings.push(finding2("package-module-dependency",unit.path,imported.line,`Package imports module ${targetModule}`))}if(sourceModule&&targetModule&&sourceModule!==targetModule&&isPrivateModuleImplementation(resolved)){findings.push(finding2("cross-module-storage",unit.path,imported.line,`Module ${sourceModule} reaches private storage of ${targetModule}`))}if(isSupabasePrivateFunctionImport(normalizedPath,resolved)){findings.push(finding2("supabase-private-function-import",unit.path,imported.line,`Function imports private source of another function ${imported.module}`))}}if(isPublicSite(normalizedPath)&&/\.agents\/(?:config|data|rules|requirements)/.test(unit.content)){findings.push(finding2("site-dashboard-dependency",unit.path,lineOf(unit.content,".agents/"),"Public site reads private .agents state"))}if(isQuery(normalizedPath,unit.content,profile)){for(const pattern of profile.writePortPatterns){if(unit.content.includes(pattern)){findings.push(finding2("query-write-port",unit.path,lineOf(unit.content,pattern),`Query references write capability ${pattern}`))}}const mutation=unit.content.match(/\.(?:insert|update|delete|save|commit|rollback)\s*\(|\.rpc\s*\(\s*["'`](?:delete|remove|update|insert|create|write)/i);if(mutation?.index!==void 0){findings.push(finding2("query-side-effect",unit.path,lineAt(unit.content,mutation.index),`Query contains mutation ${mutation[0].trim()}`))}if(/\b(?:tenant|account)_?id\b/i.test(unit.content)&&!unit.content.includes("AccountContext")){findings.push(finding2("query-missing-account-context",unit.path,lineOf(unit.content,"account"),"Multi-tenant query does not require AccountContext"))}}if(/\/(?:routes?|http)\//.test(normalizedPath)&&/\b(?:db|kysely|prisma|supabase|client)\s*\.\s*(?:from|selectFrom|insertInto|updateTable|deleteFrom|query)\s*\(/i.test(unit.content)){findings.push(finding2("route-direct-database",unit.path,1,"Inbound adapter accesses database directly"))}if(/\/(?:routes?|http)\//.test(normalizedPath)&&unit.content.includes("DatabaseRow")){findings.push(finding2("database-row-leak",unit.path,lineOf(unit.content,"DatabaseRow"),"DatabaseRow leaks through inbound boundary"))}if(/\/commands\//.test(normalizedPath)&&/critical\s*[:=]\s*true/i.test(unit.content)&&!/Idempotenc|idempotency_key/.test(unit.content)){findings.push(finding2("command-missing-idempotency",unit.path,1,"Critical command has no idempotency policy"))}}return[...deduplicate(findings)]}function isFrontendApp(path){return/(?:^|\/)apps\/frontend\//.test(path)}function isDashboardRuntimePublicBoundary(source,target){return source.startsWith(".agents/dashboard/packages/local-runtime/")&&/^\.agents\/dashboard\/modules\/(?:operations|cost-monitor|traceability)\/(?:composition-root\.ts|src\/(?:contracts\.ts|work-board-model\.ts|server\/index\.ts))$/.test(target)}function isFrontendRuntimeSource(path){return isFrontendApp(path)&&/\/src\/.+\.[cm]?[jt]sx?$/.test(path)&&!/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path)&&!/(?:^|\/)(?:__tests__|test|tests)\//.test(path)}function isBackendApp(path){return/(?:^|\/)apps\/backend\//.test(path)}function isDashboardBackendApp(path){return/(?:^|\/)\.agents\/dashboard\/apps\/backend(?:\/|$)/.test(path)}function isPublicSite(path){return/(?:^|\/)apps\/site\//.test(path)}function isInnerLibrary(path){return/(?:^|\/)(?:modules|packages)\/[^/]+\//.test(path)}function isArchitecturalSource(path){return/(?:^|\/)(?:apps|modules|packages|supabase\/functions)\//.test(path)}function isServerOnlyDependency(module){return module.startsWith("node:")||/^(?:assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|diagnostics_channel|dns|domain|events|fs|http|http2|https|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|sys|timers|tls|trace_events|tty|url|util|v8|vm|wasi|worker_threads|zlib)(?:\/|$)/.test(module)||module==="pg"||module.startsWith("pg/")||module==="hono"||module.startsWith("hono/")||module.startsWith("@hono/")||/^@zaip-ai\/dashboard-(?:operations|cost-monitor|traceability)\/server(?:\/|$)/.test(module)||/^@zaip-ai\/dashboard-local-runtime(?:\/|$)/.test(module)||/^@zaip-ai\/(?:adapters|architecture|cli|context|core|costs|decisions|distribution|eval|specs|tasks|testing)(?:\/|$)/.test(module)}function isUiRuntimeDependency(module){return module==="react"||module.startsWith("react/")||module.startsWith("react-dom")||module==="@zaip-ai/dashboard-ui"||/^@zaip-ai\/dashboard-(?:operations|cost-monitor|traceability)\/react(?:\/|$)/.test(module)}function importsApplication(module){return/(?:^|\/)apps\/(?:frontend|backend|site)(?:\/|$)/.test(module.replace(/\\/g,"/"))||/^@zaip-ai\/dashboard-frontend(?:\/|$)/.test(module)}function importsDashboardOrAgentState(module){const normalized=module.replace(/\\/g,"/");return normalized.includes(".agents/")||/(?:^|\/)\.agents\/dashboard(?:\/|$)/.test(normalized)||/^@zaip-ai\/dashboard-(?:frontend|local-runtime|operations|cost-monitor|traceability)(?:\/|$)/.test(module)}function detectLayer(path){return path.match(/\/(domain|application|adapters|infrastructure)\//)?.[1]??null}function isFramework(module,profile){const packageName=normalizeNpmSpecifier(module);return profile.frameworkPackages.some(name=>packageName===name||packageName.startsWith(`${name}/`))}function normalizeNpmSpecifier(module){const match=module.match(/^npm:((?:@[^/@]+\/)?[^/@]+)(?:@[^/]+)?(\/.*)?$/);return match===null?module:`${match[1]}${match[2]??""}`}function isQuery(path,content,profile){return profile.queryPatterns.some(pattern=>{if(pattern.startsWith("/")||pattern.startsWith("."))return path.includes(pattern);return new RegExp(`\\bclass\\s+[A-Za-z0-9_]*${escapeRegExp(pattern)}\\b`).test(content)})}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function moduleName(path){return path.match(/(?:^|\/)modules\/([^/]+)/)?.[1]??null}function isCompositionRoot(path,module){const normalized=normalizePath2(path);return normalized===`modules/${module}/composition-root.ts`||normalized.endsWith(`/modules/${module}/composition-root.ts`)}function isPackage(path){return/(?:^|\/)packages\/[^/]+\//.test(path)}function isPrivateModuleImplementation(path){return/(?:^|\/)modules\/[^/]+\/(?:adapters|application|domain|infrastructure|persistence|repositories|storage)(?:\/|$)/.test(path)}function lineOf(content,value){return lineAt(content,Math.max(0,content.indexOf(value)))}function lineAt(content,index){return content.slice(0,index).split("\n").length}function finding2(rule,path,line,message2){return{rule,path,line,message:message2}}function deduplicate(findings){const seen=new Set;return findings.filter(item=>{const key=`${item.rule}:${item.path}:${item.line}`;if(seen.has(key))return false;seen.add(key);return true})}init_src3();init_src();init_src4();init_src5();init_src2();init_src3();init_src();var EVAL_VERSION="6.0.1";async function persistEvalReport(filesystem,report,shortName="offline-suite"){const id=createId("EVAL",shortName);const{year,month}=datedIdParts(id);const path=`.agents/evals/results/${year}/${month}/${id}.json`;const persisted={id,version:EVAL_VERSION,generated_at:new Date().toISOString(),report};await filesystem.writeTextAtomic(path,`${JSON.stringify(persisted,null,2)}
3653
3653
  `);return{id,path}}function runEvalSuite(cases,profile){const results=cases.map(testCase=>{const startedAt=performance.now();const findings=testCase.validator==="cqrs"?validateCqrs(testCase.units,profile):validateArchitecture(testCase.units,profile);const actualRules=[...new Set(findings.map(item=>item.rule))].sort();const expectedRules=[...testCase.expectedRules].sort();return{id:testCase.id,passed:JSON.stringify(actualRules)===JSON.stringify(expectedRules),expectedRules,actualRules,durationMs:Math.max(0,performance.now()-startedAt)}});return{passed:results.every(result2=>result2.passed),offline:true,cases:results}}function guardDiff(changedFiles,ledgerFiles){const canonicalChanges=changedFiles.filter(path=>!path.startsWith(".agents/"));return canonicalChanges.filter(path=>!ledgerFiles.includes(path)).map(path=>({rule:"untracked-diff",message:`${path} is not present in the active task ledger`}))}var BUILTIN_EVAL_CASES=[{id:"domain-rejects-framework",units:[{path:"src/modules/a/domain/entity.ts",content:'import { Hono } from "hono";'}],expectedRules:["domain-framework-dependency"]},{id:"query-rejects-write",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: WritePort) => port.save({});"}],expectedRules:["query-side-effect","query-write-port"],validator:"cqrs"},{id:"pure-query-passes",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: ReadPort) => port.find();"}],expectedRules:[],validator:"cqrs"}];function scanInfrastructureSecurity(path,content){const findings=[];if(/\.ya?ml$/.test(path)&&/(?:privileged:\s*true|network_mode:\s*["']?host)/i.test(content)){findings.push({rule:"docker-unsafe-isolation",path})}if(/\.tf$/.test(path)&&/(?:cidr_blocks|source_ranges)\s*=\s*\[[^\]]*["']0\.0\.0\.0\/0/i.test(content)){findings.push({rule:"terraform-public-ingress",path})}if(/\.sql$/.test(path)&&/GRANT\s+ALL(?:\s+PRIVILEGES)?[\s\S]*\sTO\s+(?:PUBLIC|\w+)/i.test(content)){findings.push({rule:"sql-overprivileged-grant",path})}return findings}function runCategoryEval(category){if(category==="architecture"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>item.id.includes("domain")))}if(category==="cqrs"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>!item.id.includes("domain")))}const startedAt=performance.now();let passed=false;let actualRules=[];let expectedRules=[];if(category==="specs"){expectedRules=["untracked-diff"];actualRules=guardDiff(["src/new.ts"],[]).map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="security"){expectedRules=["generic-secret"];actualRules=scanSecrets("fixture.ts",'const token = "definitely-not-a-real-secret"').map(item=>item.kind);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="infrastructure"){expectedRules=["docker-unsafe-isolation","terraform-public-ingress","sql-overprivileged-grant"];actualRules=[...scanInfrastructureSecurity("compose.yaml","services:\n app:\n privileged: true"),...scanInfrastructureSecurity("main.tf",'ingress { cidr_blocks = ["0.0.0.0/0"] }'),...scanInfrastructureSecurity("grant.sql","GRANT ALL PRIVILEGES ON app TO PUBLIC;")].map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="adapters"){const files=adapterFiles(process.cwd());actualRules=files.map(file2=>file2.path);expectedRules=[...actualRules];passed=files.length>0&&new Set(files.map(file2=>file2.path)).size===files.length&&files.every(file2=>file2.content.includes("zaip-managed"))}else if(category==="context"){actualRules=[String(estimateTokens("12345678"))];expectedRules=[...actualRules];passed=Number(actualRules[0])>0}return{passed,offline:true,cases:[{id:`${category}-builtin`,passed,expectedRules,actualRules,durationMs:performance.now()-startedAt}]}}function runAllCategoryEvals(){const categories=["specs","architecture","cqrs","security","infrastructure","adapters","context"];const reports=categories.map(runCategoryEval);return{passed:reports.every(report=>report.passed),offline:true,cases:reports.flatMap(report=>report.cases)}}init_src6();init_src7();init_src();function output(value,json2,error51=false){const text=json2||typeof value!=="string"?`${JSON.stringify(value,null,2)}
3654
3654
  `:`${value}
3655
3655
  `;(error51?process.stderr:process.stdout).write(text)}var ACTIVATION_COMMANDS=new Set(["enable","disable","status"]);var DISABLED_MAINTENANCE_COMMANDS=new Set(["setup","upgrade","doctor","adapters","architecture","cqrs","modules","profile","migrate","version"]);function isActivationCommand(area){return ACTIVATION_COMMANDS.has(area)}async function runActivationCommand(area,filesystem,json2){if(!await filesystem.exists(PROJECT_CONFIG_PATH)){const result2={installed:false,enabled:null,config_path:PROJECT_CONFIG_PATH,message:"ZAIP-AIOS project configuration was not found."};output(result2,json2,area!=="status");return area==="status"?0:6}const repository2=new ProjectConfigRepository(filesystem);const config2=await repository2.read();if(area==="status"){output({installed:true,enabled:isZaipEnabled(config2),configured:config2.zaip?.enabled??null,config_path:PROJECT_CONFIG_PATH},json2);return 0}const enabled=area==="enable";await repository2.write({...config2,zaip:{enabled}});output({installed:true,enabled,config_path:PROJECT_CONFIG_PATH,message:enabled?"ZAIP-AIOS enabled.":"ZAIP-AIOS disabled."},json2);return 0}async function isZaipCliDisabled(filesystem){if(!await filesystem.exists(PROJECT_CONFIG_PATH))return false;return!isZaipEnabled(await new ProjectConfigRepository(filesystem).read())}function isDisabledMaintenanceCommand(area){return DISABLED_MAINTENANCE_COMMANDS.has(area)}async function handleZaipActivation(area,filesystem,json2){if(isActivationCommand(area))return runActivationCommand(area,filesystem,json2);if(isDisabledMaintenanceCommand(area)||!await isZaipCliDisabled(filesystem))return null;output({enabled:false,error:"ZAIP-AIOS is disabled for this project. Run `zaip enable` to reactivate it."},json2,true);return 6}init_cli_arguments();init_src3();async function sourceUnits(filesystem){const frameworkSource=await filesystem.exists("package.json")&&JSON.parse(await filesystem.readText("package.json")).name==="@zaip-ai/aios";const entries=(await inventory(filesystem)).filter(({path})=>frameworkSource||!/^\.agents\/(?:dashboard|design)\//.test(path));const aliasesForSource2=workspaceImportAliases(await Promise.all(entries.filter(({path})=>/(?:^|\/)(?:package|tsconfig(?:\.[^/]+)?)\.json$/.test(path)&&!isGeneratedSourcePath(path)).map(async({path})=>({path,content:await filesystem.readText(path)}))));const files=entries.filter(entry2=>/\.[cm]?[jt]sx?$/.test(entry2.path));const productionFiles=files.filter(entry2=>!/(?:^|\/)(?:tests?|__tests__)(?:\/|$)|\.(?:test|spec)(?:-support)?\.[cm]?[jt]sx?$/.test(entry2.path)&&!/(?:^|\/)scripts\/test-[^/]+\.[cm]?[jt]s$/.test(entry2.path)&&!isGeneratedSourcePath(entry2.path));return Promise.all(productionFiles.map(async({path})=>{const aliases=aliasesForSource2(path);return{path,content:await filesystem.readText(path),...aliases.length>0?{importAliases:aliases}:{}}}))}function configuredArchitectureProfile(projectConfig2){const architecture=projectConfig2?.stack.overrides.architecture;const aliases=isRecord5(architecture)?architecture.import_aliases:void 0;if(aliases!==void 0&&!Array.isArray(aliases))throw new Error("Invalid architecture import_aliases: expected an array");const configured=(aliases??[]).map((value,index)=>parseImportAlias(value,index));for(const[index,{prefix}]of configured.entries()){if(configured.some((alias,other)=>other!==index&&alias.prefix.startsWith(prefix))){throw new Error(`Invalid architecture import_aliases: ambiguous prefix ${prefix}`)}}if(projectConfig2?.stack.id!==SUPABASE_EDGE_PROFILE.id)return{...TYPESCRIPT_PROFILE,importAliases:configured};const resolution=resolveSupabaseProfile({id:SUPABASE_EDGE_PROFILE.id,...isRecord5(architecture)&&architecture.deno_json!==void 0?{deno_json:architecture.deno_json}:isRecord5(architecture)&&architecture.deno_import_map!==void 0?{deno_import_map:architecture.deno_import_map}:{}});if(!resolution.profile.supported){throw new Error(`Invalid Supabase architecture profile: ${resolution.diagnostics.join("; ")}`)}return{...resolution.profile,importAliases:configured}}function parseImportAlias(value,index){if(!isRecord5(value)||typeof value.prefix!=="string"||typeof value.target!=="string"){throw new Error(`Invalid architecture import_aliases[${index}]: expected prefix and target strings`)}if(value.prefix.length===0||value.target.length===0){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not be empty`)}if(!value.prefix.endsWith("/")||!value.target.endsWith("/")){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must end with /`)}if(/\s/.test(value.prefix)||/\s/.test(value.target)){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not contain whitespace`)}if(value.target.startsWith("/")||value.target.startsWith("\\")||/^[A-Za-z]:/.test(value.target)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value.target)||value.target.split(/[\\/]/).includes("..")){throw new Error(`Invalid architecture import_aliases[${index}]: target must be a workspace-relative path`)}return{prefix:value.prefix,target:value.target}}function isGeneratedSourcePath(path){return/(?:^|\/)dist\//.test(path)||path.startsWith(".agents/runtime/bin/")||path.startsWith("public-cli/")||path===".agents/dashboard/packages/local-runtime/server.mjs"}function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function generateBoard(tasks){const states=["planned","executing","verifying","blocked","completed"];return`# Task board
@@ -3710,7 +3710,7 @@ V1 state converted to V2 with source fingerprint \`${fingerprint.sha256}\`.`})),
3710
3710
  `));let archivedCapabilities=0;let promotedSpecs=0;for(const capability of capabilities){const legacyId=requiredString2(capability.metadata.id,`${capability.path}:id`);const promotion=promotions.find(candidate=>candidate.legacy_spec_id===legacyId);if(promotion===void 0){archivedCapabilities+=1;const relative19=capability.path.replace(/^\.agents\/specs\/capabilities\//,"");operations.push(bytesOperation("archive","capability",capability.path,capability.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/capabilities/${relative19}`,capability.bytes));findings.push({severity:"info",code:"capability-archived-not-promoted",path:capability.path,message:`${legacyId} remains legacy evidence; no DeliverySpec was created.`});continue}promotedSpecs+=1;const promotedRequirementIds=requirementIdsFromCapability(capability.body);const promotedStatus=deliverySpecStatus(capability.metadata.status);const promoted={schema_version:2,id:promotion.delivery_spec_id,prd_id:null,revision:1,title:stringOr(capability.metadata.title,legacyId),status:promotedStatus,objective:bodySection(capability.body,"Purpose")||bodySection(capability.body,"Prop\xF3sito")||stringOr(capability.metadata.title,legacyId),included_scope:[],excluded_scope:[],requirement_ids:promotedRequirementIds,acceptance_ids:promotedRequirementIds.map(id=>`AC-${id.replace(/^REQ-/,"")}`),prepared_plan:null,created_at:migrationTimestamp,updated_at:migrationTimestamp};operations.push(textOperation("convert","spec",capability.path,capability.sha256,v2EntityPath2("specs",promotion.delivery_spec_id,`${promotion.delivery_spec_id}.md`),serializeMarkdown({metadata:promoted,body:`${provenanceBody(capability.body,capability.path,capability.sha256)}
3711
3711
  - Promotion authorized by: \`${promotion.authorized_by}\``})))}const project=asRecord2(manifest.project,"manifest.project");const profile=asRecord2(manifest.profile,"manifest.profile");const agents=Array.isArray(manifest.agents)?manifest.agents:[];const managedEmptyPaths=[".agents/requirements/.gitkeep",".agents/skills/.gitkeep",".agents/data/prds/.gitkeep",".agents/data/specs/.gitkeep",".agents/data/changes/.gitkeep",".agents/data/tasks/.gitkeep",".agents/data/executions/.gitkeep",".agents/data/runs/.gitkeep"];const legacyManagedPaths=await readLegacyManagedPaths(filesystem);const v2RuleIds=new Set(DEFAULT_V2_MANAGED_FILES.filter(file2=>file2.path.startsWith(".agents/rules/")).map(file2=>parseRuleDocument(file2.content).metadata.id));for(const source of fingerprint.files.filter(file2=>/^\.agents\/rules\/[^/]+\.md$/.test(file2.path))){if(legacyManagedPaths.has(source.path))continue;const content=await filesystem.readText(source.path);const rule=parseRuleDocument(content);if(v2RuleIds.has(rule.metadata.id)){throw new Error(`Project Rule id collides with a ZAIP Rule during migration: ${rule.metadata.id}`)}v2RuleIds.add(rule.metadata.id)}const existingManagedFiles=await readManagedFiles(filesystem);const managedFiles={...Object.fromEntries(Object.entries(existingManagedFiles).filter(([path])=>!path.startsWith(".agents/rules/"))),...Object.fromEntries(managedEmptyPaths.map(path=>[path,sha2563("")]))};for(const file2 of DEFAULT_V2_MANAGED_FILES){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);try{if(file2.path.startsWith(".agents/rules/"))parseRuleDocument(current);else parseRequirementDocument(current);continue}catch{const source=fingerprint.files.find(candidate=>candidate.path===file2.path);if(source===void 0)throw new Error(`Governance source missing: ${file2.path}`);managedFiles[file2.path]=sha2563(file2.content);operations.push(textOperation("convert","config",file2.path,source.sha256,file2.path,file2.content));continue}}managedFiles[file2.path]=sha2563(file2.content);operations.push(textOperation("convert","config",null,null,file2.path,file2.content))}for(const path of managedEmptyPaths){operations.push(textOperation("convert","config",null,null,path,""))}const cleanupPaths=fingerprint.files.map(file2=>file2.path).filter(path=>!path.startsWith(".agents/rules/")&&!path.startsWith(".agents/rules/project/")&&!path.startsWith(".agents/requirements/")&&!path.startsWith(".agents/skills/")).sort();const cleanupRoots=[".agents/specs",".agents/changes",".agents/tasks",".agents/decisions",".agents/runs",".agents/telemetry",".agents/evidence",".agents/generated",".agents/context",".agents/managed",".agents/project",".agents/evals",".agents/profiles",".agents/files"];const handledPaths=new Set(operations.filter(operation=>operation.source_path!==null).map(operation=>operation.source_path));for(const path of consumedTelemetryPaths)handledPaths.add(path);for(const path of cleanupPaths){if(handledPaths.has(path)||path.startsWith(".agents/generated/")||path.startsWith(".agents/context/")){continue}const source=fingerprint.files.find(file2=>file2.path===path);if(source===void 0)throw new Error(`Source disappeared while planning: ${path}`);const bytes=await readFile4(filesystem.resolve(path));operations.push(bytesOperation("archive","legacy",path,source.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/${sha2563(path).slice(0,24)}.archive`,bytes))}operations.push(textOperation("activate-config","config",".agents/manifest.yaml",manifestFile.sha256,".agents/config/project.yaml",serializeYaml({schema_version:1,zaip:{enabled:true},project:{id:requiredString2(project.id,"manifest.project.id"),name:requiredString2(project.name,"manifest.project.name"),timezone:stringOr(project.timezone,"America/Sao_Paulo")},stack:{id:stringOr(profile.id,"zaip-aios-stack"),overrides:{}},clients:{codex:agents.includes("codex"),claude:agents.includes("claude")},tracking:{enabled:true,currency:"BRL",storage_mode:"tracked_sanitized"}})),textOperation("activate-config","config",".agents/managed/files.json",fingerprint.files.find(file2=>file2.path===".agents/managed/files.json")?.sha256??null,".agents/config/framework.lock.yaml",serializeYaml({lock_version:2,framework:{version:stringOr(asRecord2(manifest.framework,"manifest.framework").version,"0.1.0"),distribution_sha256:null},layout:{version:2},resolved_profile:{id:stringOr(profile.id,"zaip-aios-stack"),sha256:null},managed_files:managedFiles})));const orderedOperations=operations.sort(operationOrder);const duplicateTarget=firstDuplicate(orderedOperations.map(operation=>operation.target_path));if(duplicateTarget!==null){throw new Error(`Migration plan contains duplicate target: ${duplicateTarget}`)}const withoutHash={schema_version:1,migration_id:migrationId,from_layout:1,to_layout:2,source_fingerprint:fingerprint,promotions,operations:orderedOperations,cleanup_paths:cleanupPaths,cleanup_roots:cleanupRoots,counts:{source_files:fingerprint.files.length,operations:orderedOperations.length,converted_changes:convertedChangeCount,converted_tasks:convertedTaskIds.size,converted_decisions:convertedDecisions,relocated_evidence:relocatedEvidence,converted_runs:convertedRuns,usage_records:usageRecords,archived_capabilities:archivedCapabilities,promoted_specs:promotedSpecs},findings};return{...withoutHash,plan_sha256:hashCanonical(withoutHash)}}import{createHash as createHash32}from"node:crypto";import{mkdir as mkdir2,readFile as readFile5,rename as rename2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname3}from"node:path";var MigrationPlanHashError=class extends Error{name="MigrationPlanHashError"};var MigrationSourceDivergenceError=class extends Error{name="MigrationSourceDivergenceError"};var MigrationCollisionError=class extends Error{name="MigrationCollisionError"};async function applyV1ToV2Migration(filesystem,plan,expectedHash){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath2=`${stateRoot}/journal.json`;const inspected=await inspectTargets(filesystem,plan.operations);const journal=await readJournal(filesystem,journalPath2);if(inspected.missing.length===0&&journal?.state==="completed"&&!await anyPathExists(filesystem,[...plan.cleanup_paths,...plan.cleanup_roots])){await persistMigrationPlan(filesystem,stateRoot,plan);return{migration_id:plan.migration_id,status:"noop",created:[],reused:inspected.identical,journal_path:journalPath2}}if(journal?.state==="cleanup"||journal?.state==="completed"){await assertBackups(filesystem,stateRoot,plan.source_fingerprint);if(inspected.missing.length>0){throw new MigrationCollisionError(`Migration ${plan.migration_id} reached cleanup with missing V2 targets`)}for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath2,plan,"completed",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"applied",created:[],reused:inspected.identical,journal_path:journalPath2}}else{await assertSourceFingerprint(filesystem,plan.source_fingerprint)}const ownedCreated=journal===null?inspected.missing:[...journal.created];const ownedReused=journal===null?inspected.identical:[...journal.reused];await persistMigrationPlan(filesystem,stateRoot,plan);await writeJournal(filesystem,journalPath2,plan,"backing_up",ownedCreated,ownedReused);for(const source of plan.source_fingerprint.files){const sourceBytes=await readFile5(filesystem.resolve(source.path));const backupPath=`${stateRoot}/backup/${source.path}`;if(await filesystem.exists(backupPath)){const backupBytes=await readFile5(filesystem.resolve(backupPath));if(sha2566(backupBytes)!==source.sha256){throw new MigrationCollisionError(`Divergent migration backup: ${backupPath}`)}}else{await writeBytesAtomic(filesystem,backupPath,sourceBytes)}}await writeJournal(filesystem,journalPath2,plan,"staging",ownedCreated,ownedReused);for(const operation of plan.operations){const stagePath=`${stateRoot}/staging/${operation.target_path}`;const bytes=Buffer.from(operation.content_base64,"base64");if(sha2566(bytes)!==operation.target_sha256){throw new MigrationPlanHashError(`Operation content hash does not match: ${operation.target_path}`)}if(await filesystem.exists(stagePath)){const staged=await readFile5(filesystem.resolve(stagePath));if(sha2566(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}}else{await writeBytesAtomic(filesystem,stagePath,bytes)}}await writeJournal(filesystem,journalPath2,plan,"staged",ownedCreated,ownedReused);const created=[];const reused=new Set(inspected.identical);const ordinary=plan.operations.filter(operation=>operation.kind!=="activate-config");for(const operation of ordinary){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath2,plan,"commit_started",ownedCreated,ownedReused);const configs=plan.operations.filter(operation=>operation.kind==="activate-config").sort((left,right)=>configOrder2(left.target_path)-configOrder2(right.target_path));if(configs.map(operation=>operation.target_path).join("|")!==".agents/config/project.yaml|.agents/config/framework.lock.yaml"){throw new MigrationPlanHashError("Migration activation must contain exactly both V2 config files")}for(const operation of configs){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath2,plan,"cleanup",ownedCreated,ownedReused);for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath2,plan,"completed",ownedCreated,ownedReused);return{migration_id:plan.migration_id,status:created.length===0?"noop":"applied",created:created.sort(),reused:[...reused].sort(),journal_path:journalPath2}}async function readPersistedMigrationPlan(filesystem,migrationId){if(!/^MIG-[A-Z0-9]+$/.test(migrationId))throw new Error(`Invalid migration id: ${migrationId}`);const path=`.local/migrations/${migrationId}/plan.json`;if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));if(parsed.migration_id!==migrationId){throw new MigrationPlanHashError(`Persisted migration id does not match ${migrationId}`)}assertPlanHash(parsed,parsed.plan_sha256);return parsed}async function inspectV1ToV2Migration(filesystem,plan){assertPlanHash(plan,plan.plan_sha256);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath2=`${stateRoot}/journal.json`;const[journal,targets]=await Promise.all([readJournal(filesystem,journalPath2),inspectTargets(filesystem,plan.operations,true)]);let presentBackups=0;for(const source of plan.source_fingerprint.files){if(await filesystem.exists(`${stateRoot}/backup/${source.path}`))presentBackups+=1}let cleanupRemaining=0;for(const path of[...plan.cleanup_paths,...plan.cleanup_roots]){if(await filesystem.exists(path))cleanupRemaining+=1}return{migration_id:plan.migration_id,state:journal?.state??"not_started",journal_path:journalPath2,targets:{identical:targets.identical.length,missing:targets.missing.length},backups:{present:presentBackups,expected:plan.source_fingerprint.files.length},cleanup_remaining:cleanupRemaining}}async function rollbackV1ToV2Migration(filesystem,plan,expectedHash=plan.plan_sha256){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath2=`${stateRoot}/journal.json`;const journal=await readJournal(filesystem,journalPath2);if(journal===null)throw new Error(`Migration journal not found: ${journalPath2}`);const targetInspection=await inspectTargets(filesystem,plan.operations,true);const backups=new Map;for(const source of plan.source_fingerprint.files){const backupPath=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(backupPath))throw new Error(`Migration backup is missing: ${backupPath}`);const backup=await readFile5(filesystem.resolve(backupPath));if(sha2566(backup)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${backupPath}`)}if(plan.cleanup_paths.includes(source.path)&&await filesystem.exists(source.path)){const current=await readFile5(filesystem.resolve(source.path));if(sha2566(current)!==source.sha256){throw new MigrationSourceDivergenceError(`V1 source changed after migration: ${source.path}`)}}backups.set(source.path,backup)}if(targetInspection.identical.length===0&&journal.state==="rolled_back"){return{migration_id:plan.migration_id,status:"noop",removed:[],restored:[],journal_path:journalPath2}}await writeJournal(filesystem,journalPath2,plan,"rolling_back",journal.created,journal.reused);const removed=[];const createdTargets=new Set(journal.created);for(const operation of[...plan.operations].sort((left,right)=>{const leftConfig=left.kind==="activate-config"?0:1;const rightConfig=right.kind==="activate-config"?0:1;return leftConfig-rightConfig||right.target_path.localeCompare(left.target_path)})){if(createdTargets.has(operation.target_path)&&await filesystem.exists(operation.target_path)){await rm2(filesystem.resolve(operation.target_path),{force:true});removed.push(operation.target_path)}}const restored=[];for(const[path,backup]of backups){if(plan.cleanup_paths.includes(path)&&!await filesystem.exists(path)){await writeBytesAtomic(filesystem,path,backup);restored.push(path)}}await writeJournal(filesystem,journalPath2,plan,"rolled_back",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"rolled-back",removed:removed.sort(),restored:restored.sort(),journal_path:journalPath2}}async function fingerprintV1Source2(filesystem){const paths2=(await filesystem.listFiles(".agents")).filter(path=>!path.startsWith(".agents/config/")&&!path.startsWith(".agents/data/")).sort();const files=[];for(const path of paths2){const bytes=await readFile5(filesystem.resolve(path));files.push({path,sha256:sha2566(bytes),size:bytes.byteLength})}return{sha256:hashCanonical3(files),files}}async function assertSourceFingerprint(filesystem,expected){const actual=await fingerprintV1Source2(filesystem);if(actual.sha256!==expected.sha256||JSON.stringify(actual.files)!==JSON.stringify(expected.files)){throw new MigrationSourceDivergenceError(`V1 source fingerprint changed: expected ${expected.sha256}, received ${actual.sha256}`)}}async function persistMigrationPlan(filesystem,stateRoot,plan){const path=`${stateRoot}/plan.json`;const existing=await readPersistedMigrationPlan(filesystem,plan.migration_id);if(existing!==null){if(existing.plan_sha256!==plan.plan_sha256||JSON.stringify(canonicalize4(existing))!==JSON.stringify(canonicalize4(plan))){throw new MigrationPlanHashError(`Persisted migration plan diverges: ${path}`)}return}await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(plan,null,2)}
3712
3712
  `,"utf8"))}function assertPlanHash(plan,expectedHash){const{plan_sha256:actualHash,...withoutHash}=plan;const calculated=hashCanonical3(withoutHash);if(actualHash!==calculated||actualHash!==expectedHash){throw new MigrationPlanHashError(`Migration plan hash mismatch: expected ${expectedHash}, calculated ${calculated}`)}}async function inspectTargets(filesystem,operations,allowMissing=false){const identical=[];const missing=[];for(const operation of operations){if(!await filesystem.exists(operation.target_path)){missing.push(operation.target_path);continue}const target=await readFile5(filesystem.resolve(operation.target_path));const targetHash=sha2566(target);if(targetHash!==operation.target_sha256&&operation.source_path===operation.target_path&&targetHash===operation.source_sha256){missing.push(operation.target_path);continue}if(targetHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}identical.push(operation.target_path)}if(!allowMissing&&identical.length+missing.length!==operations.length){throw new MigrationCollisionError("Unable to inspect every migration target")}return{identical:identical.sort(),missing:missing.sort()}}async function commitOperation(filesystem,stateRoot,operation){const stagePath=`${stateRoot}/staging/${operation.target_path}`;if(await filesystem.exists(operation.target_path)){const existing=await readFile5(filesystem.resolve(operation.target_path));const existingHash=sha2566(existing);if(existingHash===operation.target_sha256){await rm2(filesystem.resolve(stagePath),{force:true});return"reused"}if(operation.source_path===operation.target_path&&existingHash===operation.source_sha256){const staged2=await readFile5(filesystem.resolve(stagePath));if(sha2566(staged2)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}await rm2(filesystem.resolve(operation.target_path),{force:true});await rename2(filesystem.resolve(stagePath),filesystem.resolve(operation.target_path));return"created"}if(existingHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}}const staged=await readFile5(filesystem.resolve(stagePath));if(sha2566(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}const target=filesystem.resolve(operation.target_path);await mkdir2(dirname3(target),{recursive:true});if(await filesystem.exists(operation.target_path)){throw new MigrationCollisionError(`Migration target appeared during commit: ${operation.target_path}`)}await rename2(filesystem.resolve(stagePath),target);return"created"}async function readJournal(filesystem,path){if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));return{...parsed,created:parsed.created??[],reused:parsed.reused??[]}}async function writeJournal(filesystem,path,plan,state,created=[],reused=[]){const journal={schema_version:1,migration_id:plan.migration_id,plan_sha256:plan.plan_sha256,source_sha256:plan.source_fingerprint.sha256,state,created:[...created].sort(),reused:[...reused].sort()};await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(journal,null,2)}
3713
- `,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2566(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths2){for(const path of paths2)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname3(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2566(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2566(value){return createHash32("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2566(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="6.0.0";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines2=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines2){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash33("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve7(workspaceRoot);const source=resolve7(root,sourcePath);const target=resolve7(root,".agents/runtime");const backup=resolve7(root,".local/rollback/runtime");const fromRoot=relative6(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute6(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve7(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve7(workspaceRoot);const target=resolve7(root,".agents/runtime");const backup=resolve7(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash34}from"node:crypto";import{cp as cp2,lstat as lstat6,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname4,relative as relative7,resolve as resolve8,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve8(distributionRoot,asset);const destination=resolve8(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve8(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname4(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve8(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve8(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve8(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve8(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative7(root,resolve8(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve8(root,portable);if(!destination.startsWith(`${resolve8(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash34("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat6(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname5,resolve as resolve9}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve9(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths2=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths2.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_src2();init_src();init_v2_router();init_previous_stop_recovery();import{createHash as createHash73}from"node:crypto";import{lstat as lstat17,readFile as readFile15}from"node:fs/promises";import{resolve as resolve23}from"node:path";var hash5=value=>createHash73("sha256").update(value).digest("hex");async function boundedFile(path){const info=await lstat17(path);if(!info.isFile()||info.isSymbolicLink()||info.size>2097152)throw new Error("Unsafe hook readiness file");return readFile15(path)}async function hookReadiness(root,session=process.env.CODEX_THREAD_ID){let fingerprint;try{const files=await Promise.all(HOOK_ACTIVATION_FILES.map(async file2=>[file2,hash5(await boundedFile(resolve23(root,file2)))]));fingerprint=hash5(JSON.stringify(files))}catch{return{state:"installation_incomplete",full_integration:false,trust:"unknown",events:[]}}const events=await Promise.all(HOOK_ACTIVATION_EVENTS.map(async event=>{try{const receipt=JSON.parse((await boundedFile(resolve23(root,`.local/hooks/activation/${event}.json`))).toString("utf8"));const current=receipt.schema_version===1&&receipt.event===event&&receipt.fingerprint===fingerprint&&typeof receipt.session_id==="string"&&receipt.session_id.length>0&&typeof receipt.turn_id==="string"&&receipt.turn_id.length>0&&(!session||receipt.session_id===session)&&Number.isFinite(Date.parse(receipt.observed_at));let closure=null;if(current&&event==="Stop"){const key=hash5(JSON.stringify([receipt.session_id,receipt.turn_id]));closure="pending";try{const stop=JSON.parse((await boundedFile(resolve23(root,`.local/hooks/stop-${key}.json`))).toString("utf8"));if(stop.session_id===receipt.session_id&&stop.turn_id===receipt.turn_id&&stop.state==="persisted"&&typeof stop.run_id==="string"){const filesystem=new WorkspaceFileSystem(root);await verifyStopPersistence(filesystem,createV2Composition(filesystem,await loadWorkspaceLayout(filesystem)),receipt.session_id,receipt.turn_id,stop.run_id);closure="confirmed"}}catch{}}return{event,state:current?"observed":"unverified",outcome:current?receipt.outcome:null,observed_at:current?receipt.observed_at:null,session_id:current?receipt.session_id:null,closure}}catch{return{event,state:"unverified",outcome:null,observed_at:null}}}));const sessions=new Set(events.filter(event=>event.state==="observed").map(event=>event.session_id));const full=events.every(event=>event.state==="observed")&&sessions.size===1;const closed=events.some(event=>event.event==="Stop"&&event.closure==="confirmed");const partial2=events.some(event=>event.state==="observed");return{state:full&&closed?"validated":full?"closure_pending":partial2?"activation_partial":"activation_unverified",full_integration:full&&closed,trust:"not_read_from_host",fingerprint,events,limitations:["Local event receipts prove invocation, not permission persistence or successful canonical closure.","Stop is observed only after the preceding answer ends; verify its closure separately in the next interaction."],instructions:full?null:partial2?'H\xE1 execu\xE7\xE3o observada. Valide os eventos reais ainda n\xE3o observados em um fluxo nativo pequeno; confirme Stop na intera\xE7\xE3o seguinte. Quando houver o aviso "precisam de revis\xE3o", abra a revis\xE3o dos hooks ZAIP pelo \xEDcone de hooks (\xE2ncora) na \xE1rea de digita\xE7\xE3o do chat do Codex e clique em Permitir tudo. Se houver terceiros, selecione somente ZAIP. Interruptor ligado n\xE3o comprova revis\xE3o nem aprova\xE7\xE3o. Aus\xEAncia de evid\xEAncia n\xE3o prova recusa. N\xE3o repita a aprova\xE7\xE3o se a integra\xE7\xE3o atual j\xE1 estiver validada.':'Abra o \xEDcone de hooks (\xE2ncora) na \xE1rea de digita\xE7\xE3o do chat do Codex. Quando houver o aviso "precisam de revis\xE3o", abra a revis\xE3o dos hooks ZAIP e clique em Permitir tudo. Se houver terceiros, selecione somente ZAIP. Interruptor ligado n\xE3o comprova revis\xE3o nem aprova\xE7\xE3o. Aus\xEAncia de evid\xEAncia n\xE3o prova recusa. N\xE3o repita a aprova\xE7\xE3o se a integra\xE7\xE3o atual j\xE1 estiver validada. Avise para validar eventos reais; confirme Stop na intera\xE7\xE3o seguinte. N\xE3o basta executar os scripts diretamente.'}}init_lifecycle_manifest_commands();init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}init_v2_router();var EXIT={success:0,error:1,conformity:3,security:5,prerequisite:6};async function runDistributionCommand(context2){const{area,action,parsed,filesystem,root,json:json2}=context2;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve24(dirname14(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve24(executableRoot,"..");if(basename6(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename6(executableRoot)===".agents"?distributionRoot:executableRoot);const verification=await verifyDistribution(runtimeFilesystem);if(!verification.valid){output(verification,json2,true);return EXIT.security}const frameworkSource=await isFrameworkSourceWorkspace(filesystem,root,distributionRoot);templateFiles=frameworkSource?await frameworkSourceTemplateFiles(filesystem):await frameworkSourceTemplateFiles(distributionFilesystem);if(!frameworkSource)assetPlans=await planManagedAssetInstalls(distributionRoot,root)}}const hasLegacyManifest=await filesystem.exists(".agents/manifest.yaml");const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");if(hasLegacyManifest&&!hasV2Config){throw new UsageError("V1 workspace is read-only: review `migrate plan`, then run `migrate apply`")}const options={projectName:parsed.options.name??basename6(root),bootstrapTask:parsed.flags.has("bootstrap-task"),templateFiles:templateFiles.filter(file2=>/^(?:\.agents\/config\/agents\/catalog\.yaml|\.agents\/(?:rules|requirements|skills)\/)/.test(file2.path))};const dryRun=parsed.flags.has("dry-run");if(assetPlans!==null){const preflight=await setupProjectV2(filesystem,{...options,dryRun:true});const conflicts=[...preflight.conflicts,...Object.values(assetPlans).flatMap(plan=>plan.conflicts)].sort();if(dryRun||conflicts.length>0){const result3={...preflight,conflicts,...assetPlans};output(result3,json2);return conflicts.length>0?EXIT.conformity:EXIT.success}}const setup=await setupProjectV2(filesystem,{...options,dryRun});const installedAssets=assetPlans!==null&&setup.applied?await applyManagedAssetInstalls(assetPlans):assetPlans;const result2=installedAssets===null?setup:{...setup,...installedAssets};if(!dryRun&&setup.applied&&setup.conflicts.length===0&&!await filesystem.exists(".agents/records/lifecycle/manifest.json")){const composition=createV2Composition(filesystem,await loadWorkspaceLayout(filesystem));await runLifecycleManifestMaintenance("rebuild",{...parsed,flags:new Set([...parsed.flags,"confirm-full-scan"])},filesystem,composition)}output(result2,json2);return setup.conflicts.length>0||!setup.dryRun&&!setup.applied?EXIT.conformity:EXIT.success}if(area==="doctor"){const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");const findings=hasV2Config?await doctorProjectV2(filesystem):await doctorProject(filesystem);const assetFindings=await managedAssetDoctorFindings(process.argv[1],root,filesystem);const combinedFindings=[...findings,...assetFindings];output({valid:combinedFindings.every(item=>item.severity!=="error"),findings:combinedFindings,hooks:await hookReadiness(root)},json2);return combinedFindings.some(item=>item.severity==="error")?EXIT.prerequisite:EXIT.success}if(area==="migrate"){if(action==="legacy-manifest"){if(await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml")){throw new UsageError("legacy-manifest is disabled after V2 activation")}output(await migrateProject(filesystem,parsed.flags.has("dry-run")),json2);return EXIT.success}const migrationOptions=await readMigrationOptions(filesystem,parsed);if(action==="plan"||action===void 0&&parsed.flags.has("dry-run")){const plan=await planV1ToV2Migration(filesystem,migrationOptions);output(migrationPlanOutput(plan,parsed.flags.has("verbose")),json2);return EXIT.success}if(action==="apply"){requireOptions(parsed.options,["plan-hash"]);const plan=parsed.options.migration===void 0?await planV1ToV2Migration(filesystem,migrationOptions):await readPersistedMigrationPlan(filesystem,parsed.options.migration);if(plan===null){throw new UsageError(`Migration plan not found: ${parsed.options.migration}`)}output(await applyV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]),json2);return EXIT.success}if(action==="status"||action==="rollback"){requireOptions(parsed.options,["migration"]);const migrationId=parsed.options.migration;const plan=await readPersistedMigrationPlan(filesystem,migrationId);if(plan===null)throw new UsageError(`Migration plan not found: ${migrationId}`);if(action==="rollback"){output(await rollbackV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]??plan.plan_sha256),json2)}else{output({migration_id:migrationId,plan_hash:plan.plan_sha256,status:await inspectV1ToV2Migration(filesystem,plan),plan:migrationPlanOutput(plan,parsed.flags.has("verbose"))},json2)}return EXIT.success}throw new UsageError("migrate requires plan, apply --plan-hash HASH, status --migration ID, or rollback --migration ID")}if(area==="upgrade"){if(parsed.flags.has("rollback")){await rollbackDistribution(root);output({rolledBack:true},json2);return EXIT.success}const source=parsed.options.from;if(source===void 0)throw new UsageError("upgrade requires --from PATH or --rollback");output(await upgradeDistribution(root,source,parsed.flags.has("dry-run")),json2);return EXIT.success}return null}init_src();init_cli_arguments();import{dirname as dirname15}from"node:path";async function persistEvalReportV2(filesystem,layout,report,shortName,parsed){const scope=decisionV2ScopeOption(parsed);if(scope===void 0){throw new UsageError("V2 eval persistence requires --change or --execution (or use --no-write)")}const ownerPath=layout.activePath(scope.type,scope.id);if(!await filesystem.exists(ownerPath)){throw new UsageError(`${scope.type} not found for eval evidence: ${scope.id}`)}const id=createId("EVAL",shortName,{timeZone:layout.project.timezone});const path=`${dirname15(ownerPath)}/artifacts/evals/${id}.json`;await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:2,id,generated_at:new Date().toISOString(),report},null,2)}
3713
+ `,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2566(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths2){for(const path of paths2)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname3(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2566(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2566(value){return createHash32("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2566(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="6.0.1";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines2=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines2){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash33("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve7(workspaceRoot);const source=resolve7(root,sourcePath);const target=resolve7(root,".agents/runtime");const backup=resolve7(root,".local/rollback/runtime");const fromRoot=relative6(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute6(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve7(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve7(workspaceRoot);const target=resolve7(root,".agents/runtime");const backup=resolve7(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash34}from"node:crypto";import{cp as cp2,lstat as lstat6,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname4,relative as relative7,resolve as resolve8,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve8(distributionRoot,asset);const destination=resolve8(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve8(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname4(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve8(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve8(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve8(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve8(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative7(root,resolve8(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve8(root,portable);if(!destination.startsWith(`${resolve8(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash34("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat6(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname5,resolve as resolve9}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve9(dirname5(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve9(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve9(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths2=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths2.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_src2();init_src();init_v2_router();init_previous_stop_recovery();import{createHash as createHash73}from"node:crypto";import{lstat as lstat17,readFile as readFile15}from"node:fs/promises";import{resolve as resolve23}from"node:path";var hash5=value=>createHash73("sha256").update(value).digest("hex");async function boundedFile(path){const info=await lstat17(path);if(!info.isFile()||info.isSymbolicLink()||info.size>2097152)throw new Error("Unsafe hook readiness file");return readFile15(path)}async function hookReadiness(root,session=process.env.CODEX_THREAD_ID){let fingerprint;try{const files=await Promise.all(HOOK_ACTIVATION_FILES.map(async file2=>[file2,hash5(await boundedFile(resolve23(root,file2)))]));fingerprint=hash5(JSON.stringify(files))}catch{return{state:"installation_incomplete",full_integration:false,trust:"unknown",events:[]}}const events=await Promise.all(HOOK_ACTIVATION_EVENTS.map(async event=>{try{const receipt=JSON.parse((await boundedFile(resolve23(root,`.local/hooks/activation/${event}.json`))).toString("utf8"));const current=receipt.schema_version===1&&receipt.event===event&&receipt.fingerprint===fingerprint&&typeof receipt.session_id==="string"&&receipt.session_id.length>0&&typeof receipt.turn_id==="string"&&receipt.turn_id.length>0&&(!session||receipt.session_id===session)&&Number.isFinite(Date.parse(receipt.observed_at));let closure=null;if(current&&event==="Stop"){const key=hash5(JSON.stringify([receipt.session_id,receipt.turn_id]));closure="pending";try{const stop=JSON.parse((await boundedFile(resolve23(root,`.local/hooks/stop-${key}.json`))).toString("utf8"));if(stop.session_id===receipt.session_id&&stop.turn_id===receipt.turn_id&&stop.state==="persisted"&&typeof stop.run_id==="string"){const filesystem=new WorkspaceFileSystem(root);await verifyStopPersistence(filesystem,createV2Composition(filesystem,await loadWorkspaceLayout(filesystem)),receipt.session_id,receipt.turn_id,stop.run_id);closure="confirmed"}}catch{}}return{event,state:current?"observed":"unverified",outcome:current?receipt.outcome:null,observed_at:current?receipt.observed_at:null,session_id:current?receipt.session_id:null,closure}}catch{return{event,state:"unverified",outcome:null,observed_at:null}}}));const sessions=new Set(events.filter(event=>event.state==="observed").map(event=>event.session_id));const full=events.every(event=>event.state==="observed")&&sessions.size===1;const closed=events.some(event=>event.event==="Stop"&&event.closure==="confirmed");const partial2=events.some(event=>event.state==="observed");return{state:full&&closed?"validated":full?"closure_pending":partial2?"activation_partial":"activation_unverified",full_integration:full&&closed,trust:"not_read_from_host",fingerprint,events,limitations:["Local event receipts prove invocation, not permission persistence or successful canonical closure.","Stop is observed only after the preceding answer ends; verify its closure separately in the next interaction."],instructions:full?null:partial2?'H\xE1 execu\xE7\xE3o observada. Valide os eventos reais ainda n\xE3o observados em um fluxo nativo pequeno; confirme Stop na intera\xE7\xE3o seguinte. Quando houver o aviso "precisam de revis\xE3o", abra a revis\xE3o dos hooks ZAIP pelo \xEDcone de hooks (\xE2ncora) na \xE1rea de digita\xE7\xE3o do chat do Codex e clique em Permitir tudo. Se houver terceiros, selecione somente ZAIP. Interruptor ligado n\xE3o comprova revis\xE3o nem aprova\xE7\xE3o. Aus\xEAncia de evid\xEAncia n\xE3o prova recusa. N\xE3o repita a aprova\xE7\xE3o se a integra\xE7\xE3o atual j\xE1 estiver validada.':'Abra o \xEDcone de hooks (\xE2ncora) na \xE1rea de digita\xE7\xE3o do chat do Codex. Quando houver o aviso "precisam de revis\xE3o", abra a revis\xE3o dos hooks ZAIP e clique em Permitir tudo. Se houver terceiros, selecione somente ZAIP. Interruptor ligado n\xE3o comprova revis\xE3o nem aprova\xE7\xE3o. Aus\xEAncia de evid\xEAncia n\xE3o prova recusa. N\xE3o repita a aprova\xE7\xE3o se a integra\xE7\xE3o atual j\xE1 estiver validada. Avise para validar eventos reais; confirme Stop na intera\xE7\xE3o seguinte. N\xE3o basta executar os scripts diretamente.'}}init_lifecycle_manifest_commands();init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}init_v2_router();var EXIT={success:0,error:1,conformity:3,security:5,prerequisite:6};async function runDistributionCommand(context2){const{area,action,parsed,filesystem,root,json:json2}=context2;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve24(dirname14(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve24(executableRoot,"..");if(basename6(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename6(executableRoot)===".agents"?distributionRoot:executableRoot);const verification=await verifyDistribution(runtimeFilesystem);if(!verification.valid){output(verification,json2,true);return EXIT.security}const frameworkSource=await isFrameworkSourceWorkspace(filesystem,root,distributionRoot);templateFiles=frameworkSource?await frameworkSourceTemplateFiles(filesystem):await frameworkSourceTemplateFiles(distributionFilesystem);if(!frameworkSource)assetPlans=await planManagedAssetInstalls(distributionRoot,root)}}const hasLegacyManifest=await filesystem.exists(".agents/manifest.yaml");const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");if(hasLegacyManifest&&!hasV2Config){throw new UsageError("V1 workspace is read-only: review `migrate plan`, then run `migrate apply`")}const options={projectName:parsed.options.name??basename6(root),bootstrapTask:parsed.flags.has("bootstrap-task"),templateFiles:templateFiles.filter(file2=>/^(?:\.agents\/config\/agents\/catalog\.yaml|\.agents\/(?:rules|requirements|skills)\/)/.test(file2.path))};const dryRun=parsed.flags.has("dry-run");if(assetPlans!==null){const preflight=await setupProjectV2(filesystem,{...options,dryRun:true});const conflicts=[...preflight.conflicts,...Object.values(assetPlans).flatMap(plan=>plan.conflicts)].sort();if(dryRun||conflicts.length>0){const result3={...preflight,conflicts,...assetPlans};output(result3,json2);return conflicts.length>0?EXIT.conformity:EXIT.success}}const setup=await setupProjectV2(filesystem,{...options,dryRun});const installedAssets=assetPlans!==null&&setup.applied?await applyManagedAssetInstalls(assetPlans):assetPlans;const result2=installedAssets===null?setup:{...setup,...installedAssets};if(!dryRun&&setup.applied&&setup.conflicts.length===0&&!await filesystem.exists(".agents/records/lifecycle/manifest.json")){const composition=createV2Composition(filesystem,await loadWorkspaceLayout(filesystem));await runLifecycleManifestMaintenance("rebuild",{...parsed,flags:new Set([...parsed.flags,"confirm-full-scan"])},filesystem,composition)}output(result2,json2);return setup.conflicts.length>0||!setup.dryRun&&!setup.applied?EXIT.conformity:EXIT.success}if(area==="doctor"){const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");const findings=hasV2Config?await doctorProjectV2(filesystem):await doctorProject(filesystem);const assetFindings=await managedAssetDoctorFindings(process.argv[1],root,filesystem);const combinedFindings=[...findings,...assetFindings];output({valid:combinedFindings.every(item=>item.severity!=="error"),findings:combinedFindings,hooks:await hookReadiness(root)},json2);return combinedFindings.some(item=>item.severity==="error")?EXIT.prerequisite:EXIT.success}if(area==="migrate"){if(action==="legacy-manifest"){if(await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml")){throw new UsageError("legacy-manifest is disabled after V2 activation")}output(await migrateProject(filesystem,parsed.flags.has("dry-run")),json2);return EXIT.success}const migrationOptions=await readMigrationOptions(filesystem,parsed);if(action==="plan"||action===void 0&&parsed.flags.has("dry-run")){const plan=await planV1ToV2Migration(filesystem,migrationOptions);output(migrationPlanOutput(plan,parsed.flags.has("verbose")),json2);return EXIT.success}if(action==="apply"){requireOptions(parsed.options,["plan-hash"]);const plan=parsed.options.migration===void 0?await planV1ToV2Migration(filesystem,migrationOptions):await readPersistedMigrationPlan(filesystem,parsed.options.migration);if(plan===null){throw new UsageError(`Migration plan not found: ${parsed.options.migration}`)}output(await applyV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]),json2);return EXIT.success}if(action==="status"||action==="rollback"){requireOptions(parsed.options,["migration"]);const migrationId=parsed.options.migration;const plan=await readPersistedMigrationPlan(filesystem,migrationId);if(plan===null)throw new UsageError(`Migration plan not found: ${migrationId}`);if(action==="rollback"){output(await rollbackV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]??plan.plan_sha256),json2)}else{output({migration_id:migrationId,plan_hash:plan.plan_sha256,status:await inspectV1ToV2Migration(filesystem,plan),plan:migrationPlanOutput(plan,parsed.flags.has("verbose"))},json2)}return EXIT.success}throw new UsageError("migrate requires plan, apply --plan-hash HASH, status --migration ID, or rollback --migration ID")}if(area==="upgrade"){if(parsed.flags.has("rollback")){await rollbackDistribution(root);output({rolledBack:true},json2);return EXIT.success}const source=parsed.options.from;if(source===void 0)throw new UsageError("upgrade requires --from PATH or --rollback");output(await upgradeDistribution(root,source,parsed.flags.has("dry-run")),json2);return EXIT.success}return null}init_src();init_cli_arguments();import{dirname as dirname15}from"node:path";async function persistEvalReportV2(filesystem,layout,report,shortName,parsed){const scope=decisionV2ScopeOption(parsed);if(scope===void 0){throw new UsageError("V2 eval persistence requires --change or --execution (or use --no-write)")}const ownerPath=layout.activePath(scope.type,scope.id);if(!await filesystem.exists(ownerPath)){throw new UsageError(`${scope.type} not found for eval evidence: ${scope.id}`)}const id=createId("EVAL",shortName,{timeZone:layout.project.timezone});const path=`${dirname15(ownerPath)}/artifacts/evals/${id}.json`;await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:2,id,generated_at:new Date().toISOString(),report},null,2)}
3714
3714
  `);return{id,path}}init_v2_router();init_src();init_src4();init_src6();init_cli_arguments();async function hasVerifiedEvidenceRecord(filesystem,evidenceId2,taskId){if(typeof evidenceId2!=="string"||evidenceId2.trim().length===0)return false;const expectedId=evidenceId2.trim();const expectedSuffix=`/artifacts/evidence/${expectedId}.md`;const paths2=await filesystem.listFiles(".agents/records/changes",".md");let matches=0;for(const candidate of paths2){if(!candidate.endsWith(expectedSuffix))continue;try{const evidence=parseMarkdown(await filesystem.readText(candidate),evidenceArtifactV2Schema).metadata;if(evidence.id===expectedId&&evidence.task_id===taskId&&evidence.status==="passed"){matches+=1}}catch{}}return matches===1}async function readCostCohortInput(filesystem,path){let decoded;try{decoded=JSON.parse(await filesystem.readText(path))}catch(error51){throw new UsageError(`Unable to read cost cohort input: ${error51 instanceof Error?error51.message:String(error51)}`)}try{const input=parseCompletedTaskCostCohortCollectionInputV2(decoded);const tasks=await Promise.all(input.tasks.map(async task=>({...task,equivalence_evidence_verified:await hasVerifiedEvidenceRecord(filesystem,task.equivalence_evidence_id,task.task_id),baseline_equivalence_evidence_verified:await hasVerifiedEvidenceRecord(filesystem,task.baseline_equivalence_evidence_id,task.baseline_task_id??"")})));return collectCompletedTaskCostCohortV2({...input,tasks})}catch(error51){throw new UsageError(`Invalid cost cohort input: ${error51 instanceof Error?error51.message:String(error51)}`)}}import{execFile as execFile28}from"node:child_process";import{createHash as createHash77}from"node:crypto";import{promisify as promisify28}from"node:util";init_cli_arguments();init_commit_policy();import{chmod,mkdir as mkdir8,readFile as readFile16,writeFile as writeFile6}from"node:fs/promises";import{dirname as dirname16,resolve as resolve25}from"node:path";var taskCommitHook=`#!/bin/sh
3715
3715
  # zaip-managed task-commit-policy v1
3716
3716
  # Git passes its proposed index, including commit --only's alternate index.
@@ -3775,4 +3775,4 @@ Direct delivery: conversation start or run start --direct-authorization HUMAN-RE
3775
3775
  Explicit migration: task migrate-autonomy TASK --execution EXEC --expected-revision N --legacy-attempts N --legacy-replans N|unknown [--future-replans N|unlimited] --reason TEXT [--confirm]; unknown requires an explicit future grant; preview by default, preserves history and quota`}init_cli_arguments();init_src();init_src5();init_v2_router();import{createHash as createHash76}from"node:crypto";import{lstat as lstat20,readdir as readdir5,readFile as readFile17,realpath as realpath18,writeFile as writeFile9}from"node:fs/promises";import{resolve as resolve28}from"node:path";import{randomUUID as randomUUID11}from"node:crypto";import{lstat as lstat19,open as open9,realpath as realpath17,rename as rename7,writeFile as writeFile8}from"node:fs/promises";import{dirname as dirname18,relative as relative15,resolve as resolve27}from"node:path";function validateReceipt(path,root,value){const directory2=resolve27(root,".local/hooks/observations");if(dirname18(resolve27(path)).toLowerCase()!==directory2.toLowerCase()||!/^[a-f0-9]{64}\.json$/.test(relative15(directory2,path)))throw new Error("observation_receipt_path_invalid");const receipt=value;if(receipt?.schema_version!==1||!["pending","persisted"].includes(receipt.state)||!["PreToolUse","SubagentStart","SubagentStop","Stop"].includes(receipt.event_name)||typeof receipt.session_id!=="string"||!receipt.session_id||typeof receipt.turn_id!=="string"||!receipt.turn_id||typeof receipt.governance!=="boolean"||!/^HOBS-[a-f0-9]{64}$/.test(receipt.event_id))throw new Error("observation_receipt_invalid");return receipt}async function save(path,receipt){const temporary=`${path}.tmp-${randomUUID11()}`;await writeFile8(temporary,`${JSON.stringify(receipt)}
3776
3776
  `,{flag:"wx",mode:384});await rename7(temporary,path)}async function terminalStatus3(receipt){if(receipt.status!==null)return receipt.status;if(receipt.event_name!=="Stop"||!receipt.transcript_path)return null;const path=receipt.transcript_path;const metadata3=await lstat19(path);if(!metadata3.isFile()||metadata3.isSymbolicLink()||(await realpath17(path)).toLowerCase()!==resolve27(path).toLowerCase())throw new Error("observation_transcript_unsafe");const handle=await open9(path,"r");try{const header=Buffer.alloc(Math.min(1024*1024,metadata3.size));await handle.read(header,0,header.length,0);const end=header.indexOf(10);if(end<0)throw new Error("observation_transcript_header_pending");const first=JSON.parse(header.subarray(0,end).toString("utf8"));if(first?.type!=="session_meta"||first.payload?.id!==receipt.session_id)throw new Error("observation_transcript_session_mismatch");const size=Math.min(16*1024*1024,metadata3.size);const offset=metadata3.size-size;const tail=Buffer.alloc(size);await handle.read(tail,0,size,offset);const start=offset===0?0:tail.indexOf(10)+1;if(start===0&&offset>0)throw new Error("observation_transcript_tail_pending");for(const line of tail.subarray(start).toString("utf8").split(/\r?\n/).filter(Boolean).reverse()){let row;try{row=JSON.parse(line)}catch{continue}const payload=row.payload;if(payload?.type==="task_complete"&&payload.turn_id===receipt.turn_id)return payload.status==="cancelled"?"cancelled":payload.status==="failed"||payload.error!=null?"failed":"completed"}return null}finally{await handle.close()}}init_hook_tracking_policy();init_lifecycle_manifest_commands();init_record_codex_telemetry();var digest13=value=>createHash76("sha256").update(value).digest("hex");async function observeHookReceipt(filesystem,path){const metadata3=await lstat20(path);if(!metadata3.isFile()||metadata3.isSymbolicLink()||metadata3.size>16384||(await realpath18(path)).toLowerCase()!==resolve28(path).toLowerCase())throw new Error("observation_receipt_unsafe");const receipt=validateReceipt(path,filesystem.root,JSON.parse(await readFile17(path,"utf8")));if(receipt.state==="persisted")return{state:"persisted",event_id:receipt.event_id,run_id:receipt.run_id??null};if(!await hookTrackingEnabled(filesystem))return{state:"pending",event_id:receipt.event_id,run_id:receipt.run_id??null,error:"tracking_disabled"};try{const layout=await loadWorkspaceLayout(filesystem);const composition=createV2Composition(filesystem,layout);const subagent=receipt.event_name.startsWith("Subagent");const client=subagent?"codex-subagent":"codex";const agentPath=subagent?receipt.agent_path:null;if(subagent&&receipt.agent_id===null&&agentPath===null)throw new Error("native_child_identity_missing");const runId=await composition.runs.withUsageAttributionLock(async()=>{let correlation=await readCodexTelemetryCorrelationForTurn(filesystem,client,subagent?null:receipt.session_id,receipt.turn_id,agentPath,subagent?receipt.agent_id:null);let runId2=correlation?.run_id??null;if(correlation===null&&receipt.governance){const observed=await readCodexTelemetryCorrelationForTurn(filesystem,client,subagent?null:receipt.session_id,receipt.turn_id,agentPath,subagent?receipt.agent_id:null,true);const prior=observed===null?null:await composition.runs.read(observed.run_id);if(!observed||!prior||prior.run.entrypoint!=="observation"||prior.run.run_purpose!=="observation"||prior.run.task_id!==null||prior.run.execution_id!==null||prior.run.change_id!==null||prior.run.client!==client||prior.run.client_thread_id!==(subagent?agentPath??receipt.agent_id:receipt.session_id)||prior.run.client_turn_id!==receipt.turn_id)throw new Error("governed_run_correlation_pending");correlation=observed;runId2=observed.run_id}if(correlation===null){correlation=await readCodexTelemetryCorrelationForTurn(filesystem,client,subagent?null:receipt.session_id,receipt.turn_id,agentPath,subagent?receipt.agent_id:null,true);runId2=correlation?.run_id??null}if(correlation===null){const occurred=new Date(receipt.observed_at);if(!Number.isFinite(occurred.getTime()))throw new Error("observation_time_invalid");const date5=occurred.toISOString().slice(0,16).replace("T","-").replaceAll(":","-");const identity2=digest13(JSON.stringify([receipt.session_id,receipt.turn_id,receipt.agent_id,agentPath])).slice(0,12).toUpperCase();runId2=`RUN-${date5}-OBSERVATION-${identity2}`;const prior=await composition.runs.read(runId2).catch(()=>null);if(prior===null){const parentCandidate=subagent?await readCodexTelemetryCorrelationForTurn(filesystem,"codex",receipt.session_id,receipt.turn_id,null)??await readCodexTelemetryCorrelationForTurn(filesystem,"codex",receipt.session_id,receipt.turn_id,null,null,true):null;const parentRun=parentCandidate===null?null:await composition.runs.read(parentCandidate.run_id);const parent=receipt.parent_agent_id!==null&&parentRun!==null&&[parentRun.run.client_thread_id,parentRun.run.observed_agent_id,parentRun.run.observed_agent_path].includes(receipt.parent_agent_id)?parentCandidate:null;await composition.runs.start({id:runId2,shortName:`OBSERVATION-${identity2}`,phase:"conversation",runPurpose:"observation",runRole:parent?"subagent":"intake",requiresFinalizer:false,entrypoint:"observation",workType:"new",client,agent:receipt.agent_type??"agent-observer",provider:null,model:receipt.model??"unavailable",reasoningEffort:runV2ReasoningEffortSchema.safeParse(receipt.reasoning_effort).data??null,clock:{now:()=>occurred},clientThreadId:subagent?agentPath??receipt.agent_id:receipt.session_id,clientTurnId:receipt.turn_id,observedAgentId:receipt.agent_id,observedAgentPath:agentPath,observedParentAgentId:receipt.parent_agent_id,conversationId:null,executionId:null,taskId:null,specId:null,prdId:null,changeId:null,parentRunId:parent?.run_id??null})}correlation=await readCodexTelemetryCorrelationForTurn(filesystem,client,subagent?null:receipt.session_id,receipt.turn_id,agentPath,subagent?receipt.agent_id:null,true);if(correlation?.run_id!==runId2)throw new Error("observation_correlation_unavailable")}if(runId2===null)throw new Error("observation_run_unavailable");return runId2});if(receipt.event_name==="Stop"||receipt.event_name==="SubagentStop"){const observation=await readCodexTelemetryCorrelationForTurn(filesystem,client,subagent?null:receipt.session_id,receipt.turn_id,agentPath,subagent?receipt.agent_id:null,true);if(observation!==null&&observation.run_id!==runId){const status=await terminalStatus3(receipt);if(status===null)throw new Error("observation_terminal_pending");await composition.runs.withUsageAttributionLock(async()=>{const previous=await composition.runs.read(observation.run_id);if(previous.finished!==null)return;const sequence=previous.records.length+1;await composition.runs.appendRecord({schema_version:2,event_id:`EVT-${observation.run_id}-${sequence}`,run_id:observation.run_id,sequence,occurred_at:receipt.observed_at,type:"run.finished",phase:"conversation",status,duration_ms:null,duration_provenance:null})});await syncObservedRunManifest(observation.run_id,composition,filesystem)}const current=await composition.runs.read(runId);if(current.finished===null){if((!receipt.governance||current.run.entrypoint==="observation")&&receipt.event_name==="Stop"){receipt.status=await terminalStatus3(receipt);if(receipt.status===null)throw new Error("observation_terminal_pending")}if((!receipt.governance||current.run.entrypoint==="observation")&&receipt.event_name==="SubagentStop"&&receipt.status===null)throw new Error("observation_terminal_pending");const priorTranscript=process.env.CODEX_TRANSCRIPT_PATH;try{if(receipt.transcript_path)process.env.CODEX_TRANSCRIPT_PATH=receipt.transcript_path;await recordCodexTelemetryIfAvailable(current,composition,filesystem)}finally{if(priorTranscript===void 0)delete process.env.CODEX_TRANSCRIPT_PATH;else process.env.CODEX_TRANSCRIPT_PATH=priorTranscript}if(current.run.entrypoint==="observation"){await composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(runId);if(fresh.finished===null&&receipt.status!==null){const sequence=fresh.records.length+1;await composition.runs.appendRecord({schema_version:2,event_id:`EVT-${runId}-${sequence}`,run_id:runId,sequence,occurred_at:receipt.observed_at,type:"run.finished",phase:"conversation",status:receipt.status,duration_ms:null,duration_provenance:null})}})}}}await syncObservedRunManifest(runId,composition,filesystem);receipt.state="persisted";receipt.run_id=runId;delete receipt.last_error;await save(path,receipt);return{state:"persisted",event_id:receipt.event_id,run_id:runId}}catch(error51){const code=error51 instanceof Error?error51.message:"";receipt.last_error=/^(observation_|native_child_|governed_run_)[a-z_]+$/.test(code)?code:"observation_persistence_pending";await save(path,receipt);return{state:"pending",event_id:receipt.event_id,run_id:receipt.run_id??null,error:receipt.last_error}}}async function replayHookObservations(filesystem){if(!await hookTrackingEnabled(filesystem))return{attempted:0,pending:0,errors:0,scanned:0};const directory2=resolve28(filesystem.root,".local/hooks/observations");const names=(await readdir5(directory2).catch(()=>[])).filter(name=>/^[a-f0-9]{64}\.json$/.test(name)).sort();const cursorPath=resolve28(directory2,"replay-cursor.txt");const cursor=await readFile17(cursorPath,"utf8").catch(()=>"");const ordered=[...names.filter(name=>name>cursor),...names.filter(name=>name<=cursor)];let attempted=0,pending=0,errors=0,scanned=0;let last=cursor;for(const name of ordered.slice(0,256)){last=name;scanned++;try{const path=resolve28(directory2,name);const info=await lstat20(path);if(!info.isFile()||info.isSymbolicLink()||info.size>16384)throw new Error("unsafe_receipt");const candidate=validateReceipt(path,filesystem.root,JSON.parse(await readFile17(path,"utf8")));if(candidate.state!=="pending")continue;attempted++;if((await observeHookReceipt(filesystem,path)).state==="pending")pending++}catch{errors++}if(attempted>=3)break}if(scanned>0)await writeFile9(cursorPath,last,{mode:384});return{attempted,pending,errors,scanned}}init_stop_receipt();async function hookCommand(filesystem,parsed){if(parsed.positionals[1]==="observe"){requireOptions(parsed.options,["receipt"]);const result3=await observeHookReceipt(filesystem,parsed.options.receipt);return{result:result3,success:result3.state==="persisted"}}if(parsed.positionals[1]==="replay-observations")return{result:await replayHookObservations(filesystem),success:true};if(parsed.positionals[1]==="status")return{result:await hookReadiness(filesystem.root,parsed.options.session),success:true};if(parsed.positionals[1]!=="recover-stop")throw new Error("Unknown hook action");requireOptions(parsed.options,["session","turn"]);const result2=await replayStopReceipt(filesystem,parsed.options.session,parsed.options.turn);return{result:result2,success:result2.state==="persisted"&&result2.error===null}}init_lifecycle_v2();import{spawn as spawn2}from"node:child_process";import{dirname as dirname20}from"node:path";async function taskLedger(repository2){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.change));const tasks=allTasks.filter(task=>activeChangeIds.has(task.change)&&task.status!=="planned");const paths2=new Set;for(const task of tasks){const{body}=await repository2.read(task.id);const section=body.match(/## Arquivos alterados\s+([\s\S]*?)(?=\n## |$)/)?.[1]??"";for(const match of section.matchAll(/^\s*-\s+`?([^`\n]+?)`?\s*$/gm)){if(match[1])paths2.add(match[1].replace(/\\/g,"/"))}}return[...paths2].sort()}async function taskLedgerV2(repository2,changed){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).map(task=>task.change_id));const changeTasks=allTasks.filter(task=>activeChangeIds.has(task.change_id)&&!["draft","planned","cancelled"].includes(task.status));const completedTasks=allTasks.filter(task=>task.result!==null);const paths2=new Set([...changeTasks,...completedTasks].flatMap(task=>task.result?.changed_files??[]));const authorizedScopes=[...changeTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).flatMap(task=>task.write_scopes),...completedTasks.flatMap(task=>task.result?.changed_files??[])];for(const path of changed){if(authorizedScopes.some(scope=>workspaceScopeMatches(scope,path)))paths2.add(path)}return[...paths2].sort()}function runUiServer(serverPath,workspace){const child=spawn2(process.execPath,[serverPath],{cwd:dirname20(serverPath),env:{...process.env,ZAIP_WORKSPACE:workspace},stdio:"inherit",windowsHide:true});return new Promise((resolveExit,reject)=>{child.once("error",reject);child.once("exit",code=>resolveExit(code??1))})}init_lifecycle_manifest_commands();init_run_conversation_v2();init_cli_arguments();import{execFile as execFile27}from"node:child_process";import{lstat as lstat21,realpath as realpath19}from"node:fs/promises";import{basename as basename8,isAbsolute as isAbsolute15,relative as relative17,resolve as resolve29,sep as sep7}from"node:path";import{promisify as promisify27}from"node:util";var execFileAsync12=promisify27(execFile27);var shaPattern2=/^[a-f0-9]{40}$/i;var canonicalMigrationPath=/^supabase\/migrations\/[A-Za-z0-9][A-Za-z0-9_.-]*\.sql$/;async function runSupabaseMigrationCommand(input){if(input.action!=="plan"&&input.action!=="validate"){throw new UsageError("supabase migration requires plan or validate")}const target=input.config?.supabase_migrations;if(target===void 0){throw new UsageError("supabase migration requires supabase_migrations in .agents/config/project.yaml")}const findings=await validateTarget(target.repository);const plan={repository_id:target.repository.id,configured_path:target.repository.path,required_branch:target.repository.branch,required_origin:target.repository.origin,hosted_applicator:target.hosted_applicator,applies_hosted_schema:false,required_evidence:["migration catalog entry","candidate SHA on beta","passed candidate checks","Supabase migration-history observation showing the same migration applied"]};if(input.action==="plan")return{valid:findings.length===0,mode:"plan",target:plan,findings};const evidencePath=input.parsed.options.evidence;if(evidencePath===void 0)throw new UsageError("supabase migration validate requires --evidence PATH");let evidence=null;try{evidence=parseEvidence(JSON.parse(await input.filesystem.readText(evidencePath)))}catch(error51){findings.push({code:"evidence-invalid",message:error51 instanceof Error?error51.message:"Migration evidence is invalid"})}if(evidence!==null&&findings.length===0){findings.push(...await validateEvidence(target.repository.path,evidence))}return{valid:findings.length===0,mode:"validate",target:plan,findings}}async function validateTarget(repository2){const findings=[];if(!isAbsolute15(repository2.path)||repository2.path.includes("\0")){return[{code:"target-path-invalid",message:"Migration target path must be absolute"}]}let target;try{target=await realpath19(repository2.path)}catch{return[{code:"target-path-unavailable",message:"Configured migration target is unavailable"}]}if(target.split(/[\\/]/).at(-1)!==repository2.id){findings.push({code:"target-identity-mismatch",message:"Target path basename does not match the configured repository id"})}const[branch,origin]=await Promise.all([git7(target,["branch","--show-current"]),git7(target,["remote","get-url","origin"])]);if(branch!==repository2.branch){findings.push({code:"target-branch-mismatch",message:"Migration target must be on branch beta"})}if(origin!==repository2.origin){findings.push({code:"target-origin-mismatch",message:"Migration target origin does not match configuration"})}return findings}async function validateEvidence(targetPath,evidence){const findings=[];if(!canonicalMigrationPath.test(evidence.migration.path)){return[{code:"migration-path-invalid",message:"Migration path must be a canonical supabase/migrations/*.sql path"}]}if(!basename8(evidence.migration.path).startsWith(evidence.migration.id)){findings.push({code:"migration-id-filename-mismatch",message:"Migration id must be the filename prefix"})}if(!shaPattern2.test(evidence.candidate.sha)){findings.push({code:"candidate-sha-invalid",message:"Candidate SHA must be a full Git commit SHA"})}if(evidence.candidate.checks.length===0||evidence.candidate.checks.some(check3=>check3.status!=="passed")){findings.push({code:"candidate-checks-missing",message:"Candidate evidence requires one or more passed checks"})}if(evidence.applied.migration_id!==evidence.migration.id){findings.push({code:"applied-migration-mismatch",message:"Applied migration evidence must name the catalogued migration id"})}if(!Number.isFinite(Date.parse(evidence.applied.observed_at))){findings.push({code:"applied-observation-invalid",message:"Applied migration observation requires an ISO timestamp"})}if(findings.length>0)return findings;const target=await realpath19(targetPath);const migrationFile=resolve29(target,evidence.migration.path);if(!within(target,migrationFile)){return[{code:"migration-path-escape",message:"Migration path escapes the configured target"}]}try{const physicalMigrationFile=await realpath19(migrationFile);const status=await lstat21(migrationFile);if(status.isSymbolicLink()||!status.isFile()||!within(target,physicalMigrationFile)){findings.push({code:"migration-file-unsafe",message:"Migration file must be a regular non-symlink file inside the target"})}await git7(target,["ls-files","--error-unmatch","--",evidence.migration.path])}catch{findings.push({code:"migration-not-catalogued",message:"Migration file is absent from the target catalog"})}const head=await git7(target,["rev-parse","HEAD"]);if(head!==evidence.candidate.sha){findings.push({code:"candidate-sha-mismatch",message:"Candidate SHA must equal the current beta HEAD"})}try{const observedOriginBeta=await git7(target,["rev-parse","refs/remotes/origin/beta"]);if(observedOriginBeta!==evidence.candidate.sha){findings.push({code:"origin-beta-sha-mismatch",message:"Observed refs/remotes/origin/beta does not match the candidate SHA"})}else{findings.push({code:"origin-beta-unverified",message:"Observed origin/beta is local ref evidence only; fetch freshness and remote publication remain unverified"})}}catch{findings.push({code:"origin-beta-ref-unavailable",message:"refs/remotes/origin/beta is unavailable; remote publication is pending"})}try{const type=await git7(target,["cat-file","-t",`${evidence.candidate.sha}:${evidence.migration.path}`]);if(type!=="blob")throw new Error("candidate object is not a blob");await git7(target,["diff","--quiet","--",evidence.migration.path]);await git7(target,["diff","--cached","--quiet","--",evidence.migration.path])}catch{findings.push({code:"candidate-migration-unverified",message:"Candidate migration must be a tracked clean blob at the candidate SHA"})}return findings}function parseEvidence(value){if(typeof value!=="object"||value===null)throw new Error("Migration evidence must be an object");const record3=value;const migration=record3.migration;const candidate=record3.candidate;const applied=record3.applied;if(record3.schema_version!==1||migration===void 0||candidate===void 0||applied===void 0){throw new Error("Migration evidence must use schema_version 1 with migration, candidate and applied sections")}if(typeof migration.id!=="string"||typeof migration.path!=="string"||typeof candidate.sha!=="string"||!Array.isArray(candidate.checks)||typeof applied.migration_id!=="string"||applied.status!=="applied"||applied.source!=="supabase-migration-history"||applied.trust!=="unverified"||typeof applied.observed_at!=="string"){throw new Error("Migration evidence fields are incomplete or invalid; local observations are unverified")}if(!candidate.checks.every(check3=>typeof check3==="object"&&check3!==null&&typeof check3.id==="string"&&["passed","failed"].includes(String(check3.status)))){throw new Error("Candidate checks must each have id and passed or failed status")}return value}async function git7(cwd,args){const result2=await execFileAsync12("git",[...args],{cwd,windowsHide:true,encoding:"utf8"});return result2.stdout.trim()}function within(root,candidate){const path=relative17(root,candidate);return path===""||!path.startsWith(`..${sep7}`)&&path!==".."&&!isAbsolute15(path)}init_task_execution_resolution_v2();init_cli_arguments();import{lstat as lstat22,realpath as realpath20}from"node:fs/promises";import{isAbsolute as isAbsolute16,relative as relative18,resolve as resolve30,sep as sep8}from"node:path";async function assertToolWriteScope(root,scopes,requestedPath){if(!isCanonicalRelativePath(requestedPath)){throw new UsageError("Tool write path must be canonical and workspace-relative")}if(scopes.length===0||!scopes.some(scope=>scopeMatches2(scope,requestedPath))){throw new UsageError(`Tool write path is outside declared write scopes: ${requestedPath}`)}const physicalRoot=await realpath20(root);const target=resolve30(root,requestedPath);if(!within2(physicalRoot,target))throw new UsageError("Tool write path escapes workspace root");let ancestor=target;while(true){try{const status=await lstat22(ancestor);const physicalAncestor=await realpath20(ancestor);if(status.isSymbolicLink()||!within2(physicalRoot,physicalAncestor)){throw new UsageError("Tool write path escapes workspace through a symlink")}return}catch(error51){if(error51 instanceof UsageError)throw error51;if(!(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT"))throw error51;const parent=resolve30(ancestor,"..");if(parent===ancestor||!within2(resolve30(root),parent)){throw new UsageError("Tool write path has no contained existing ancestor")}ancestor=parent}}}async function copyWithinToolWriteScope(input){await assertToolWriteScope(input.root,input.scopes,input.to);await input.filesystem.writeTextAtomic(input.to,await input.filesystem.readText(input.from))}function isCanonicalRelativePath(value){return value.length>0&&!value.includes("\\")&&!value.includes(":")&&!value.includes("\0")&&!isAbsolute16(value)&&!value.startsWith("./")&&value.split("/").every(part=>part!==""&&part!=="."&&part!==".."&&!/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(part))}function scopeMatches2(scope,path){if(!isCanonicalRelativePath(scope.replace(/\*+$/g,"placeholder")))return false;const normalized=scope.replace(/\/+$/,"");if(!normalized.includes("*"))return path===normalized||path.startsWith(`${normalized}/`);const expression=normalized.split("**").map(part=>part.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")).join(".*");return new RegExp(`^${expression}$`).test(path)}function within2(root,candidate){const fromRoot=relative18(root,candidate);return fromRoot===""||!fromRoot.startsWith(`..${sep8}`)&&fromRoot!==".."&&!isAbsolute16(fromRoot)}init_src();import{spawn as spawn3}from"node:child_process";async function runScopedVerification(filesystem,risk2){const changed=await new ShellGit(filesystem.root).status();const packageRoots=new Set;for(const entry2 of changed){const path=entry2.path.replace(/\\/g,"/");const match=path.match(/^(packages\/[^/]+|\.agents\/dashboard\/(?:apps|modules|packages|tests)\/[^/]+)/);if(match?.[1]!==void 0)packageRoots.add(`./${match[1]}`)}const commands=[];if(risk2==="critical")commands.push({name:"full-verify",command:"pnpm",args:["verify"]});else if(risk2==="standard"){commands.push({name:"encoding",command:"node",args:["scripts/validate-text-encoding.mjs"]},{name:"source-size",command:"node",args:["scripts/validate-source-size.mjs"]});for(const root of[...packageRoots].sort()){commands.push({name:`${root}:typecheck`,command:"pnpm",args:["--filter",root,"typecheck"]});commands.push({name:`${root}:test`,command:"pnpm",args:["--filter",root,"test"]})}}const lines2=[];const checks=risk2==="lite"?[{name:"diff-only",passed:true,exit_code:0}]:[];const expectedChecks=checks.length+commands.length;for(const check3 of commands){const outcome=await runProcess2(check3.command,check3.args,filesystem.root);lines2.push(`$ ${check3.command} ${check3.args.join(" ")}
3777
3777
  ${outcome.output}`);checks.push({name:check3.name,passed:outcome.code===0,exit_code:outcome.code});if(outcome.code!==0)break}const logPath=`.local/verify/${new Date().toISOString().replace(/[:.]/g,"-")}.log`;await filesystem.writeTextAtomic(logPath,`${lines2.join("\n\n")}
3778
- `);return{passed:checks.length===expectedChecks&&checks.every(check3=>check3.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command2,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command2==="pnpm"?"pnpm.cmd":command2;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="6.0.0";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync13=promisify28(execFile28);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve31(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"){const{result:result2,success:success2}=await hookCommand(filesystem,parsed);output(result2,json2);return success2?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="git-lock"&&action==="recover"){requireOptions(parsed.options,["task","run","decision"]);const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("Git lock recovery requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const fold=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());const decision=await composition.decisions.read("change",task.change_id,parsed.options.decision);if(!["executing","verifying"].includes(task.status)||fold.status!=="running"||fold.run.task_id!==task.id||fold.run.change_id!==task.change_id||fold.run.execution_id!==executionId||decision.origin!=="human"||decision.confirmed_at===null||!/index[.]lock/i.test(`${decision.decision} ${decision.reason}`))throw new UsageError("Git lock recovery requires an active Task Run and confirmed human Decision for index.lock");output({task_id:task.id,run_id:fold.run.run_id,decision_id:decision.id,...await recoverResidualGitIndexLock(root)},json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash77("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync13("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync13("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync13("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash77("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}const contextExit=await runContextCli(area,action,parsed,filesystem,json2,EXIT2);if(contextExit!==null)return contextExit;if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message2=>({field:"clients",message:message2})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve31(dirname21(executable),"..");const distributionRoot=basename9(executableRoot)===".agents"?executableRoot:resolve31(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename9(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve31(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);output({error:message2},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve31(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};
3778
+ `);return{passed:checks.length===expectedChecks&&checks.every(check3=>check3.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command2,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command2==="pnpm"?"pnpm.cmd":command2;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="6.0.1";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync13=promisify28(execFile28);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve31(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"){const{result:result2,success:success2}=await hookCommand(filesystem,parsed);output(result2,json2);return success2?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="git-lock"&&action==="recover"){requireOptions(parsed.options,["task","run","decision"]);const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("Git lock recovery requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const fold=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());const decision=await composition.decisions.read("change",task.change_id,parsed.options.decision);if(!["executing","verifying"].includes(task.status)||fold.status!=="running"||fold.run.task_id!==task.id||fold.run.change_id!==task.change_id||fold.run.execution_id!==executionId||decision.origin!=="human"||decision.confirmed_at===null||!/index[.]lock/i.test(`${decision.decision} ${decision.reason}`))throw new UsageError("Git lock recovery requires an active Task Run and confirmed human Decision for index.lock");output({task_id:task.id,run_id:fold.run.run_id,decision_id:decision.id,...await recoverResidualGitIndexLock(root)},json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash77("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync13("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync13("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync13("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash77("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}const contextExit=await runContextCli(area,action,parsed,filesystem,json2,EXIT2);if(contextExit!==null)return contextExit;if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message2=>({field:"clients",message:message2})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve31(dirname21(executable),"..");const distributionRoot=basename9(executableRoot)===".agents"?executableRoot:resolve31(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename9(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve31(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message2=error51 instanceof Error?error51.message:String(error51);output({error:message2},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve31(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};