@zaip-ai/cli 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/services/adapters.d.ts +1 -1
  2. package/dist/services/adapters.js +1 -1
  3. package/dist/services/codex-hook-activation.d.ts.map +1 -1
  4. package/dist/services/codex-hook-activation.js +12 -0
  5. package/dist/services/codex-hook-activation.js.map +1 -1
  6. package/dist/services/codex-pre-tool-hook-template.js +1 -1
  7. package/dist/services/codex-pre-tool-hook-template.test.js +36 -0
  8. package/dist/services/codex-pre-tool-hook-template.test.js.map +1 -1
  9. package/dist/services/global-codex-config-migration-rollback.test.d.ts +2 -0
  10. package/dist/services/global-codex-config-migration-rollback.test.d.ts.map +1 -0
  11. package/dist/services/global-codex-config-migration-rollback.test.js +88 -0
  12. package/dist/services/global-codex-config-migration-rollback.test.js.map +1 -0
  13. package/dist/services/global-codex-config-migration.test.js +69 -82
  14. package/dist/services/global-codex-config-migration.test.js.map +1 -1
  15. package/dist/services/global-codex-config-transaction.test.js +5 -1
  16. package/dist/services/global-codex-config-transaction.test.js.map +1 -1
  17. package/dist/services/global-codex-config.d.ts.map +1 -1
  18. package/dist/services/global-codex-config.js +32 -53
  19. package/dist/services/global-codex-config.js.map +1 -1
  20. package/dist/services/global-codex-toml.d.ts +9 -0
  21. package/dist/services/global-codex-toml.d.ts.map +1 -0
  22. package/dist/services/global-codex-toml.js +53 -0
  23. package/dist/services/global-codex-toml.js.map +1 -0
  24. package/dist/services/logger.js +1 -1
  25. package/dist/services/logger.js.map +1 -1
  26. package/dist/services/logger.test.js +2 -2
  27. package/dist/services/logger.test.js.map +1 -1
  28. package/package.json +1 -1
  29. package/templates/.agents/config/agents/discovery.json +1 -1
  30. package/templates/.agents/dashboard/.zaip-managed.json +38 -38
  31. package/templates/.agents/dashboard/apps/frontend/dist/assets/{CostCalculationGuidePage-OUjdwEcM.js → CostCalculationGuidePage-BW7Vy1cp.js} +1 -1
  32. package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-Cei1ChjE.js → DashboardHelpDialog-BN8KQPrr.js} +2 -2
  33. package/templates/.agents/dashboard/apps/frontend/dist/assets/{PricingSettingsDialog-_woNCrTT.js → PricingSettingsDialog-Prcs-ydy.js} +1 -1
  34. package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-B2_7MVOP.js → ProjectSettingsPage-HqGUImIG.js} +1 -1
  35. package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-C_jCsSZe.js → TraceabilityWorkspace-CNpmQMO4.js} +1 -1
  36. package/templates/.agents/dashboard/apps/frontend/dist/assets/{cost-monitor-C8zQDBT7.js → cost-monitor-Co2Jiuzh.js} +1 -1
  37. package/templates/.agents/dashboard/apps/frontend/dist/assets/{icons-vendor-iMPXot7Y.js → icons-vendor-DOhy6D2-.js} +1 -1
  38. package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-DiCwz0sr.js → index-DX65Ufuu.js} +2 -2
  39. package/templates/.agents/dashboard/apps/frontend/dist/assets/{react-vendor-721Re3Ss.js → react-vendor-CkPC-yMz.js} +1 -1
  40. package/templates/.agents/dashboard/apps/frontend/dist/assets/{traceability-BjdTkWS0.js → traceability-BEdGoIDm.js} +1 -1
  41. package/templates/.agents/dashboard/apps/frontend/dist/index.html +5 -5
  42. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  43. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  44. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  45. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.macro-metrics.test.ts +2 -1
  46. package/templates/.agents/dashboard/modules/operations/src/react/overview-duration-hint.ts +1 -3
  47. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  48. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  49. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  50. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  51. package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
  52. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  53. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  54. package/templates/.agents/design/.zaip-managed.json +3 -3
  55. package/templates/.agents/design/apps/catalog/package.json +1 -1
  56. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  57. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  58. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  59. package/templates/.agents/requirements/comparative-audit.md +1 -1
  60. package/templates/.agents/requirements/context-engine.md +1 -1
  61. package/templates/.agents/requirements/cost-observability.md +1 -1
  62. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  63. package/templates/.agents/requirements/data-export.md +1 -1
  64. package/templates/.agents/requirements/design-system.md +1 -1
  65. package/templates/.agents/requirements/execution-engine.md +1 -1
  66. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  67. package/templates/.agents/requirements/model-orchestration.md +1 -1
  68. package/templates/.agents/requirements/public-distribution.md +11 -9
  69. package/templates/.agents/requirements/software-architecture.md +1 -1
  70. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  71. package/templates/.agents/requirements/work-lifecycle.md +1 -1
  72. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  73. package/templates/.agents/runtime/VERSION +1 -1
  74. package/templates/.agents/runtime/bin/zaip.mjs +18 -6
  75. package/templates/.agents/runtime/checksums.sha256 +5 -5
  76. package/templates/.agents/runtime/manifest.json +1 -1
  77. package/templates/.agents/runtime/provenance.json +4 -4
  78. package/templates/.agents/runtime/sbom.cdx.json +1 -1
  79. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.mjs +11 -2
  80. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.test.mjs +26 -0
  81. package/templates/.agents/zaip-aios/VERSION +1 -1
  82. package/templates/.agents/zaip-aios/guides/14-troubleshooting.md +1 -1
  83. package/templates/template-manifest.json +70 -70
@@ -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((metadata2,context)=>{if(metadata2.load==="file_match"&&metadata2.globs.length===0){context.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((metadata2,context)=>{if(metadata2.source_change===null&&metadata2.source_release===void 0){context.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata2.source_change!==null&&metadata2.source_release!==void 0){context.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,context)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context.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,digest7){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest7}.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="4.7.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((metadata2,context)=>{if(metadata2.load==="file_match"&&metadata2.globs.length===0){context.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((metadata2,context)=>{if(metadata2.source_change===null&&metadata2.source_release===void 0){context.addIssue({code:"custom",path:["source_release"],message:"released Requirements require source_release when source_change is null"})}if(metadata2.source_change!==null&&metadata2.source_release!==void 0){context.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,context)=>{const bindings=Object.keys(mode.capability_bindings).sort();const surfaces=[...mode.native_surfaces].sort();if(JSON.stringify(bindings)!==JSON.stringify(surfaces)){context.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,digest7){return`${LIFECYCLE_CLAIMS_ROOT}/${kind}/${digest7}.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="4.8.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)}
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 paths=new Set;const bySubject=new Map;for(const file2 of files){if(paths.has(file2.path))drifted.push(`${file2.path}:duplicate-path`);paths.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 inventory2=await agentGuidanceInventory(filesystem,new Set(files.map(file2=>file2.path)));for(const path of inventory2.staleManaged){drifted.push(path);findings.push({classification:"stale-managed",path})}for(const path of inventory2.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)}
@@ -428,6 +428,18 @@ export function recordActivation(root, event, outcome = "observed") {
428
428
  renameSync(temporary, path);
429
429
  } catch { /* Diagnostics must not break a tool or turn. Missing evidence stays unknown. */ }
430
430
  }
431
+ export async function isZaipDisabled(repositoryRoot, boundedCanonicalText) {
432
+ try {
433
+ const source = (await boundedCanonicalText(resolve(repositoryRoot, ".agents/config/project.yaml"), 65536))
434
+ .replace(/\r\n/g, "\n");
435
+ const enabled = /^zaip:\n enabled: (true|false)(?:\n|$)/m.exec(source)?.[1];
436
+ const zaipKeys = [...source.matchAll(/^(?:zaip|"zaip"|'zaip')\s*:/gm)];
437
+ const enabledKeys = [...source.matchAll(/^ enabled\s*:/gm)];
438
+ return enabled === "false" && zaipKeys.length === 1 && enabledKeys.length === 1;
439
+ } catch {
440
+ return false;
441
+ }
442
+ }
431
443
  `}});import{createHash as createHash3}from"node:crypto";function lines(text){const result2=[];let multiline=null;let start=0;for(const raw of text.match(/[^\n]*(?:\n|$)/g)??[]){if(!raw)continue;result2.push({text:raw.trim(),start,end:start+raw.length,outside:multiline===null});for(let i=0;i<raw.length;i++){if(multiline!==null){if(multiline==='"""'&&raw[i]==="\\"){i++;continue}if(raw.startsWith(multiline,i)){i+=2;multiline=null}}else if(raw[i]==="#")break;else if(raw[i]==='"'||raw[i]==="'"){const quote=raw[i];if(raw.startsWith(quote.repeat(3),i)){multiline=quote.repeat(3);i+=2}else for(i++;i<raw.length;i++){if(quote==='"'&&raw[i]==="\\")i++;else if(raw[i]===quote)break}}}start+=raw.length}return result2}function sections(text){const headers=lines(text).filter(line=>line.outside&&/^\[.+\]\s*(?:#.*)?$/.test(line.text));return headers.map((line,index)=>{const end=headers[index+1]?.start??text.length;return{header:line.text.replace(/\s+#.*$/,""),start:line.start,end,text:text.slice(line.start,end)}})}function registrationRange(text){const source=lines(text).filter(line=>line.outside);const starts=source.filter(line=>line.text===BEGIN);const ends=source.filter(line=>line.text===END);if(!starts.length&&!ends.length)return null;if(starts.length!==1||ends.length!==1||(starts[0]?.start??0)>=(ends[0]?.start??0)){throw new Error("Ambiguous managed Codex agent registration block")}return{start:starts[0]?.start??0,end:ends[0]?.end??text.length}}function managedHook(section){return lines(section.text).some(line=>line.outside&&/^command\s*=/.test(line.text)&&/[\\/]zaip-(?:pre-tool-use|conversation-lifecycle|subagent-lifecycle)\.mjs/.test(line.text))}function refreshHooks(current,generated){const expected=sections(generated);const replacements=new Map;for(let i=0;i<expected.length;i++){const section=expected[i];if(section&&/^\[\[hooks\.[\w]+\]\]$/.test(section.header)&&expected[i+1]&&managedHook(expected[i+1])){replacements.set(section.header,section.text+expected[i+1]?.text)}}const source=sections(current);const changes=[];const seen=new Set;for(let i=0;i<source.length;i++){const parent=source[i];if(!parent||!replacements.has(parent.header))continue;const childHeader=`${parent.header.slice(0,-2)}.hooks]]`;const children=[];while(source[i+1]?.header===childHeader)children.push(source[++i]);const owned=children.filter(managedHook);if(!owned.length)continue;const thirdParty=children.filter(child=>!managedHook(child));const replacement=seen.has(parent.header)?"":replacements.get(parent.header)??"";seen.add(parent.header);changes.push({start:parent.start,end:children.at(-1)?.end??parent.end,text:(thirdParty.length?parent.text+thirdParty.map(child=>child.text).join(""):"")+replacement})}for(const change of changes.reverse())current=current.slice(0,change.start)+change.text+current.slice(change.end);const missing=[...replacements].filter(([header])=>!seen.has(header)).map(([,text])=>text);if(missing.length)current=`${current.trimEnd()}
432
444
 
433
445
  ${missing.join("")}`;return current}function enableHooks(current){const section=sections(current).find(section2=>section2.header==="[features]");if(!section)return`${current.trimEnd()}
@@ -1406,7 +1418,7 @@ if (typeof commandFromCmd === "string" && typeof commandFromCommand === "string"
1406
1418
  const command = typeof commandFromCmd === "string" ? commandFromCmd : commandFromCommand;
1407
1419
  if (typeof command !== "string") deny("A matched tool call without a command was rejected.");
1408
1420
 
1409
- if (await requiresOrchestratorRun(event, command)) {
1421
+ if (await requiresOrchestratorRun(event, command) && !(await activation?.isZaipDisabled?.(repositoryRoot, boundedCanonicalText))) {
1410
1422
  const directRun = await nativeAuthority?.hasCurrentTaskOrchestratorRun(event, installedRoot, boundedCanonicalText);
1411
1423
  const primaryRead = (path, maximumBytes) => boundedCanonicalText(path, maximumBytes, installedRoot);
1412
1424
  const delegated = directRun ? false : await nativeAuthority?.hasNativeDelegatedPatch(event, repositoryRoot, primaryRead, installedRoot);
@@ -2346,7 +2358,7 @@ Read \`.agents/config/project.yaml\` first. Apply ZAIP only for literal boolean
2346
2358
  - Use native \`spawn_agent\` only for Sub-Runs; the orchestrator records observed spawn and terminal events idempotently. Independent chats require an explicit user request.
2347
2359
 
2348
2360
  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.
2349
- `}});import{createHash as createHash7}from"node:crypto";import{resolve as resolve3}from"node:path";function windowsHookCommand(hookFile,workspaceRoot){const search=workspaceRoot===void 0?"(Get-Location)":`'${resolve3(workspaceRoot).replaceAll("'","''")}'`;const script=`$ProgressPreference = 'SilentlyContinue'; $search = ${search}; $git = $null; while ($search) { $candidate = Join-Path $search '.local/git/cmd/git.exe'; if (Test-Path -LiteralPath $candidate -PathType Leaf) { $git = $candidate; break }; $parent = Split-Path -Path $search -Parent; if (!$parent -or $parent -eq $search) { break }; $search = $parent }; if (!$git) { $git = (Get-Command git -ErrorAction SilentlyContinue).Source }; if (!$git) { exit 0 }; $root = & $git rev-parse --show-toplevel 2>$null; if ($LASTEXITCODE -ne 0 -or !$root) { exit 0 }; $hook = Join-Path $root '.codex/hooks/${hookFile}'; if (!(Test-Path -LiteralPath $hook -PathType Leaf)) { exit 0 }; & node $hook; exit $LASTEXITCODE`;return`powershell -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function adapterFiles(workspaceRoot,catalog,windowsWorkspaceRoot){const codexConfig=CODEX_CONFIG.replaceAll(CODEX_WORKSPACE_ROOT_PLACEHOLDER,JSON.stringify(resolve3(workspaceRoot))).replaceAll("__ZAIP_WINDOWS_PRE_TOOL_HOOK__",windowsHookCommand("zaip-pre-tool-use.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_CONVERSATION_HOOK__",windowsHookCommand("zaip-conversation-lifecycle.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_SUBAGENT_HOOK__",windowsHookCommand("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"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-hook-activation.mjs",CODEX_HOOK_ACTIVATION,"codex-hook-activation"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-pre-tool-use.mjs",CODEX_PRE_TOOL_HOOK,"codex-safety-hook"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-pre-tool-support.mjs",CODEX_PRE_TOOL_SUPPORT_HOOK,"codex-safety-support"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-native-tool-authority.mjs",CODEX_NATIVE_TOOL_AUTHORITY_HOOK,"codex-native-tool-authority"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-conversation-lifecycle.mjs",CODEX_CONVERSATION_LIFECYCLE_HOOK,"codex-conversation-lifecycle-hook"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-subagent-lifecycle.mjs",CODEX_SUBAGENT_LIFECYCLE_HOOK,"codex-subagent-lifecycle-hook"),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_conversation_lifecycle_hook();init_codex_hook_activation();init_codex_hook_activation();init_codex_config_overlay();init_codex_native_tool_authority_template();init_codex_pre_tool_hook_template();init_codex_pre_tool_support_template();init_codex_rules();init_codex_subagent_lifecycle_hook();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="4.7.0";USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);RETIRED_MANAGED_ADAPTERS=["CLAUDE.md"];CLAUDE_SETTINGS=`{
2361
+ `}});import{createHash as createHash7}from"node:crypto";import{resolve as resolve3}from"node:path";function windowsHookCommand(hookFile,workspaceRoot){const search=workspaceRoot===void 0?"(Get-Location)":`'${resolve3(workspaceRoot).replaceAll("'","''")}'`;const script=`$ProgressPreference = 'SilentlyContinue'; $search = ${search}; $git = $null; while ($search) { $candidate = Join-Path $search '.local/git/cmd/git.exe'; if (Test-Path -LiteralPath $candidate -PathType Leaf) { $git = $candidate; break }; $parent = Split-Path -Path $search -Parent; if (!$parent -or $parent -eq $search) { break }; $search = $parent }; if (!$git) { $git = (Get-Command git -ErrorAction SilentlyContinue).Source }; if (!$git) { exit 0 }; $root = & $git rev-parse --show-toplevel 2>$null; if ($LASTEXITCODE -ne 0 -or !$root) { exit 0 }; $hook = Join-Path $root '.codex/hooks/${hookFile}'; if (!(Test-Path -LiteralPath $hook -PathType Leaf)) { exit 0 }; & node $hook; exit $LASTEXITCODE`;return`powershell -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function adapterFiles(workspaceRoot,catalog,windowsWorkspaceRoot){const codexConfig=CODEX_CONFIG.replaceAll(CODEX_WORKSPACE_ROOT_PLACEHOLDER,JSON.stringify(resolve3(workspaceRoot))).replaceAll("__ZAIP_WINDOWS_PRE_TOOL_HOOK__",windowsHookCommand("zaip-pre-tool-use.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_CONVERSATION_HOOK__",windowsHookCommand("zaip-conversation-lifecycle.mjs",windowsWorkspaceRoot)).replaceAll("__ZAIP_WINDOWS_SUBAGENT_HOOK__",windowsHookCommand("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"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-hook-activation.mjs",CODEX_HOOK_ACTIVATION,"codex-hook-activation"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-pre-tool-use.mjs",CODEX_PRE_TOOL_HOOK,"codex-safety-hook"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-pre-tool-support.mjs",CODEX_PRE_TOOL_SUPPORT_HOOK,"codex-safety-support"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-native-tool-authority.mjs",CODEX_NATIVE_TOOL_AUTHORITY_HOOK,"codex-native-tool-authority"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-conversation-lifecycle.mjs",CODEX_CONVERSATION_LIFECYCLE_HOOK,"codex-conversation-lifecycle-hook"),managedAdapterFile(ADAPTERS_VERSION,".codex/hooks/zaip-subagent-lifecycle.mjs",CODEX_SUBAGENT_LIFECYCLE_HOOK,"codex-subagent-lifecycle-hook"),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_conversation_lifecycle_hook();init_codex_hook_activation();init_codex_hook_activation();init_codex_config_overlay();init_codex_native_tool_authority_template();init_codex_pre_tool_hook_template();init_codex_pre_tool_support_template();init_codex_rules();init_codex_subagent_lifecycle_hook();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="4.8.0";USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);RETIRED_MANAGED_ADAPTERS=["CLAUDE.md"];CLAUDE_SETTINGS=`{
2350
2362
  "permissions": {
2351
2363
  "allow": [],
2352
2364
  "deny": []
@@ -2821,7 +2833,7 @@ ${attempt.run.run_id}`).digest("hex")}});for(const delegation of delegations){co
2821
2833
  `);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 execFile19}from"node:child_process";import{createHash as createHash53}from"node:crypto";import{constants as constants2}from"node:fs";import{copyFile,lstat as lstat12,mkdir as mkdir8,mkdtemp as mkdtemp3,readFile as readFile10,realpath as realpath13,rm as rm8}from"node:fs/promises";import{dirname as dirname13,isAbsolute as isAbsolute12,join as join7,relative as relative13,resolve as resolve18,sep as sep6}from"node:path";import{promisify as promisify19}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=resolve18(filesystem.root);const primary=resolve18(await git4(root,["rev-parse","--show-toplevel"]));const common=resolve18(await git4(root,["rev-parse","--path-format=absolute","--git-common-dir"]));if(root!==primary||common!==resolve18(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(resolve18(claim.path)!==resolve18(expected.path)||claim.branch!==expected.branch)throw new UsageError("Isolated workspace claim differs from the registered Task front");const branchTip=await git4(root,["rev-parse",claim.branch]);const worktreeTip=await git4(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 git4(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 git4(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=resolve18(root,branchRelative);const backup=resolve18(root,worktreeRelative);assertChild(resolve18(root,".local/backup-branchs"),bundle);assertChild(resolve18(root,".local/backup-worktrees"),backup);const receiptPath=`${worktreeRelative}/manifest.json`;if(await filesystem.exists(receiptPath))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 mkdir8(dirname13(bundle),{recursive:true});await mkdir8(join7(backup,"files"),{recursive:true});for(const directory2 of[dirname13(bundle),backup,join7(backup,"files")]){const info=await lstat12(directory2);if(!info.isDirectory()||info.isSymbolicLink()||resolve18(await realpath13(directory2))!==directory2)throw new UsageError("Task backup directory is not a verified physical directory")}await git4(root,["bundle","create",bundle,claim.branch]);await git4(root,["bundle","verify",bundle]);const bundleSha=digest6(await readFile10(bundle));const entries=(await git4(claim.path,["ls-files","-c","-o","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const files=[];for(const path of entries){const source=resolve18(claim.path,path);const target=resolve18(backup,"files",path);assertChild(claim.path,source);assertChild(resolve18(backup,"files"),target);const info=await lstat12(source);if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1)throw new UsageError(`Workspace snapshot contains an unsafe file: ${path}`);await mkdir8(dirname13(target),{recursive:true});if(resolve18(await realpath13(dirname13(target)))!==dirname13(target))throw new UsageError("Task backup destination traverses a link");await copyFile(source,target,constants2.COPYFILE_EXCL);const sha2566=digest6(await readFile10(source));if(digest6(await readFile10(target))!==sha2566)throw new UsageError(`Workspace snapshot verification failed: ${path}`);files.push({path:path.replaceAll("\\","/"),sha256:sha2566})}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 git4(claim.path,["status","--porcelain","-z"]),discarded_ignored:ignored.map(path=>path.replaceAll("\\","/")),files};const probeParent=resolve18(root,".local/backup-worktrees");const probe=await mkdtemp3(join7(probeParent,"restore-probe-"));assertChild(probeParent,probe);try{await git4(root,["clone","--quiet","--no-checkout",branchRelative,relative13(root,probe)]);await git4(probe,["cat-file","-e",`${branchTip}^{commit}`]);for(const entry2 of files){if(digest6(await readFile10(resolve18(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(receiptPath,`${JSON.stringify(receipt,null,2)}
2822
2834
  `);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 git4(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 ")&&resolve18(line.slice(9))===resolve18(claimedPath))&&lines2.includes(`branch refs/heads/${claim.branch}`)&&lines2.includes(`HEAD ${branchTip}`)})||await git4(claim.path,["branch","--show-current"])!==claim.branch||await git4(claim.path,["rev-parse","HEAD"])!==branchTip||await git4(root,["rev-parse",claim.branch])!==branchTip||digest6(await readFile10(bundle))!==bundleSha)throw new UsageError("Task branch, worktree or bundle changed after backup");const currentEntries=(await git4(claim.path,["ls-files","-c","-o","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const currentIgnored=(await git4(claim.path,["ls-files","-o","-i","--exclude-standard","-z"])).split("\0").filter(Boolean).sort();const currentStatus=await git4(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=resolve18(claim.path,entry2.path);const info=await lstat12(source);if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||digest6(await readFile10(source))!==entry2.sha256||digest6(await readFile10(resolve18(backup,"files",entry2.path)))!==entry2.sha256)throw new UsageError(`Task snapshot changed after backup: ${entry2.path}`)}await git4(root,["worktree","remove",...currentStatus||ignored.length?["--force"]:[],claim.path]);await git4(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})}
2823
2835
  `);await filesystem.removeFileIfContentMatches(`.local/task-workspaces/claims/${taskId}.json`,`${JSON.stringify(claim,null,2)}
2824
- `);return{status:"closed",backup_branch:branchRelative,backup_worktree:worktreeRelative}})}function discardableIgnored(path){const parts=path.replaceAll("\\","/").split("/");if(parts.some(part=>part===".."||part===""))return false;return parts.some(part=>["node_modules",".turbo",".cache","coverage","dist","build",".vite",".next"].includes(part))||parts.at(-1)?.endsWith(".tsbuildinfo")===true}function assertChild(root,path){const scoped=relative13(root,path);if(!scoped||scoped===".."||scoped.startsWith(`..${sep6}`)||isAbsolute12(scoped))throw new UsageError("Backup path escapes its dedicated local directory")}function digest6(content){return createHash53("sha256").update(content).digest("hex")}async function git4(cwd,args){return(await exec7("git",args,{cwd,shell:false,windowsHide:true,encoding:"utf8",maxBuffer:64*1024*1024,timeout:3e5,env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/^(GIT_|NODE_OPTIONS$)/i.test(key)))})).stdout.trim()}var exec7;var init_task_workspace_closure=__esm({"src/task-workspace-closure.ts"(){"use strict";init_cli_arguments();init_git_autonomous_worktree();init_lifecycle_manifest_commands();init_run_hierarchy();init_task_workspace_command();exec7=promisify19(execFile19)}});function runTaskWorkspaceAction(parsed,filesystem,composition){if(!parsed.flags.has("close"))return runTaskWorkspaceCommand(parsed,filesystem,composition);return closeTaskWorkspace(filesystem,composition,parsed.positionals[2]??parsed.options.task??"",parsed.options.run??"")}var init_task_workspace_routing=__esm({"src/task-workspace-routing.ts"(){"use strict";init_task_workspace_closure();init_task_workspace_command()}});async function assertActiveDefinitionRun(input){const{area,runId,filesystem,composition}=input;const catalog=await loadAgentCatalog(filesystem);const expected=selectAgent(catalog,{role:area==="prd"?"analyst":"builder",capability:area==="prd"?"prd-creation":"spec-creation"}).agent;if(runId===null){throw new UsageError(`${area.toUpperCase()} definition requires an observed --run or exact-turn Run`)}const observed=await composition.runs.read(runId);const parent=observed.run.parent_run_id===null?null:await composition.runs.read(observed.run.parent_run_id);const invocation2=await resolveRunClientInvocation(filesystem,"codex");const isStandaloneAuthoring=parent===null;const reworkAuthoring=input.reworkAuthoring===true||input.reworkSuccessorPrdId!==void 0;const authorizationRun=parent?.run??observed.run;const definitionAuthorized=authorizationRun.intake?.reason_codes.includes(`definition-${area}-authorized`)??false;if(!reworkAuthoring&&!definitionAuthorized){throw new UsageError(`${area.toUpperCase()} definition requires root intake authorization --definition ${area}`)}if(!reworkAuthoring&&authorizationRun.execution_kind!=="interaction"){throw new UsageError(`${area.toUpperCase()} definition requires a root interaction, not a delivery execution`)}if(!reworkAuthoring&&(authorizationRun.intake?.intent!=="conversation"||authorizationRun.intake.classification_source!=="explicit")){throw new UsageError(`${area.toUpperCase()} definition requires an explicit conversation root intake`)}const expectedAgent=reworkAuthoring&&area==="prd"?[expected.id,"agent-builder"]:[expected.id];const currentInvocationMatches=invocation2.clientThreadId!==null&&invocation2.clientTurnId!==null&&[observed.run,...parent===null?[]:[parent.run]].some(run=>run.client_thread_id===invocation2.clientThreadId&&run.client_turn_id===invocation2.clientTurnId);if(!expectedAgent.includes(observed.run.agent)||observed.run.agent===expected.id&&observed.run.agent_name!==expected.codex_name||observed.run.agent==="agent-builder"&&observed.run.agent_name!=="zaip-agent-builder"||observed.status!=="running"||observed.run.client!=="codex-subagent"||reworkAuthoring&&observed.run.work_type!=="rework"||input.reworkSuccessorPrdId!==void 0&&observed.run.prd_id!==input.reworkSuccessorPrdId||!isStandaloneAuthoring&&(observed.run.invocation_kind!=="delegated"||observed.run.run_purpose!=="execution")||!isStandaloneAuthoring&&(parent.status!=="running"||parent.run.parent_run_id!==null||parent.run.invocation_kind!=="orchestrator"||parent.run.agent!=="agent-orchestrator"||parent.run.agent_name!=="zaip-agent-orchestrator"||parent.run.execution_id!==observed.run.execution_id||parent.run.conversation_id!==observed.run.conversation_id||!currentInvocationMatches)){throw new UsageError(`${area.toUpperCase()} definition requires an active delegated ${expected.codex_name} Run linked to the root orchestration`)}return observed.run.run_id}var init_definition_run_gate=__esm({"src/commands/definition-run-gate.ts"(){"use strict";init_src();init_cli_arguments();init_run_agent_identity();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 createHash54,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 digest7=createHash54("sha256").update(`${path}\0${randomBytes2(16).toString("hex")}`).digest("hex").slice(0,24);const recoveryPath=`.local/recovery/composite-create/${digest7}.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"}});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()}});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==="ready-next")return readyNextItem(filesystem,composition);if(action==="amend-scopes")return amendTaskScopes(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_execution_intake_compatibility();init_git_delivery_preflight();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_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();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 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==="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"){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"){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??""}`)}async function runSpecV2Command(action,parsed,filesystem,composition,lifecycle){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==="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"){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);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 execute from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const output2=executionOutput(await composition.materializer.execute(plan),composition);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 output2}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_cli_arguments();init_conversation_intake();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();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_support();init_v2_lifecycle_task();init_v2_ready_queue();init_v2_lifecycle_materialization()}});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"])}});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(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(!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 execute2=dependencies.execute??(()=>runV2CommandUnlocked("run","reconcile",parsed,filesystem,layout));const initial=await preflight(createComposition(),filesystem);if(initial.kind==="no-op")return initial.result;return withLock(execute2)}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")}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=await runEvidenceV2Command(action,parsed,filesystem,composition);else if(area==="validation")result2=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)&&!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}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"}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_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_run();init_v2_command_areas()}});init_src2();import{basename as basename7,dirname as dirname18,resolve as resolve24}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,message){return{rule,path,line,message}}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,message){return{rule,path,line,message}}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="4.7.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)}
2836
+ `);return{status:"closed",backup_branch:branchRelative,backup_worktree:worktreeRelative}})}function discardableIgnored(path){const parts=path.replaceAll("\\","/").split("/");if(parts.some(part=>part===".."||part===""))return false;return parts.some(part=>["node_modules",".turbo",".cache","coverage","dist","build",".vite",".next"].includes(part))||parts.at(-1)?.endsWith(".tsbuildinfo")===true}function assertChild(root,path){const scoped=relative13(root,path);if(!scoped||scoped===".."||scoped.startsWith(`..${sep6}`)||isAbsolute12(scoped))throw new UsageError("Backup path escapes its dedicated local directory")}function digest6(content){return createHash53("sha256").update(content).digest("hex")}async function git4(cwd,args){return(await exec7("git",args,{cwd,shell:false,windowsHide:true,encoding:"utf8",maxBuffer:64*1024*1024,timeout:3e5,env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/^(GIT_|NODE_OPTIONS$)/i.test(key)))})).stdout.trim()}var exec7;var init_task_workspace_closure=__esm({"src/task-workspace-closure.ts"(){"use strict";init_cli_arguments();init_git_autonomous_worktree();init_lifecycle_manifest_commands();init_run_hierarchy();init_task_workspace_command();exec7=promisify19(execFile19)}});function runTaskWorkspaceAction(parsed,filesystem,composition){if(!parsed.flags.has("close"))return runTaskWorkspaceCommand(parsed,filesystem,composition);return closeTaskWorkspace(filesystem,composition,parsed.positionals[2]??parsed.options.task??"",parsed.options.run??"")}var init_task_workspace_routing=__esm({"src/task-workspace-routing.ts"(){"use strict";init_task_workspace_closure();init_task_workspace_command()}});async function assertActiveDefinitionRun(input){const{area,runId,filesystem,composition}=input;const catalog=await loadAgentCatalog(filesystem);const expected=selectAgent(catalog,{role:area==="prd"?"analyst":"builder",capability:area==="prd"?"prd-creation":"spec-creation"}).agent;if(runId===null){throw new UsageError(`${area.toUpperCase()} definition requires an observed --run or exact-turn Run`)}const observed=await composition.runs.read(runId);const parent=observed.run.parent_run_id===null?null:await composition.runs.read(observed.run.parent_run_id);const invocation2=await resolveRunClientInvocation(filesystem,"codex");const isStandaloneAuthoring=parent===null;const reworkAuthoring=input.reworkAuthoring===true||input.reworkSuccessorPrdId!==void 0;const authorizationRun=parent?.run??observed.run;const definitionAuthorized=authorizationRun.intake?.reason_codes.includes(`definition-${area}-authorized`)??false;if(!reworkAuthoring&&!definitionAuthorized){throw new UsageError(`${area.toUpperCase()} definition requires root intake authorization --definition ${area}`)}if(!reworkAuthoring&&authorizationRun.execution_kind!=="interaction"){throw new UsageError(`${area.toUpperCase()} definition requires a root interaction, not a delivery execution`)}if(!reworkAuthoring&&(authorizationRun.intake?.intent!=="conversation"||authorizationRun.intake.classification_source!=="explicit")){throw new UsageError(`${area.toUpperCase()} definition requires an explicit conversation root intake`)}const expectedAgent=reworkAuthoring&&area==="prd"?[expected.id,"agent-builder"]:[expected.id];const currentInvocationMatches=invocation2.clientThreadId!==null&&invocation2.clientTurnId!==null&&[observed.run,...parent===null?[]:[parent.run]].some(run=>run.client_thread_id===invocation2.clientThreadId&&run.client_turn_id===invocation2.clientTurnId);if(!expectedAgent.includes(observed.run.agent)||observed.run.agent===expected.id&&observed.run.agent_name!==expected.codex_name||observed.run.agent==="agent-builder"&&observed.run.agent_name!=="zaip-agent-builder"||observed.status!=="running"||observed.run.client!=="codex-subagent"||reworkAuthoring&&observed.run.work_type!=="rework"||input.reworkSuccessorPrdId!==void 0&&observed.run.prd_id!==input.reworkSuccessorPrdId||!isStandaloneAuthoring&&(observed.run.invocation_kind!=="delegated"||observed.run.run_purpose!=="execution")||!isStandaloneAuthoring&&(parent.status!=="running"||parent.run.parent_run_id!==null||parent.run.invocation_kind!=="orchestrator"||parent.run.agent!=="agent-orchestrator"||parent.run.agent_name!=="zaip-agent-orchestrator"||parent.run.execution_id!==observed.run.execution_id||parent.run.conversation_id!==observed.run.conversation_id||!currentInvocationMatches)){throw new UsageError(`${area.toUpperCase()} definition requires an active delegated ${expected.codex_name} Run linked to the root orchestration`)}return observed.run.run_id}var init_definition_run_gate=__esm({"src/commands/definition-run-gate.ts"(){"use strict";init_src();init_cli_arguments();init_run_agent_identity();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 createHash54,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 digest7=createHash54("sha256").update(`${path}\0${randomBytes2(16).toString("hex")}`).digest("hex").slice(0,24);const recoveryPath=`.local/recovery/composite-create/${digest7}.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"}});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()}});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==="ready-next")return readyNextItem(filesystem,composition);if(action==="amend-scopes")return amendTaskScopes(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_execution_intake_compatibility();init_git_delivery_preflight();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_scope_amendment();init_task_start_command();init_v2_lifecycle_materialization();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 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==="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"){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"){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??""}`)}async function runSpecV2Command(action,parsed,filesystem,composition,lifecycle){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==="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"){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);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 execute from status ${current.spec.status}: ${id}`)}await assertSpecImplementationMatchesProject(current.spec.implementation,filesystem,composition.layout);const output2=executionOutput(await composition.materializer.execute(plan),composition);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 output2}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_cli_arguments();init_conversation_intake();init_execution_intake_compatibility();init_git_delivery_preflight();init_prepared_plan_v22();init_release_cycle();init_run_budget();init_run_client_invocation();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_support();init_v2_lifecycle_task();init_v2_ready_queue();init_v2_lifecycle_materialization()}});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"])}});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(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(!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 execute2=dependencies.execute??(()=>runV2CommandUnlocked("run","reconcile",parsed,filesystem,layout));const initial=await preflight(createComposition(),filesystem);if(initial.kind==="no-op")return initial.result;return withLock(execute2)}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")}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=await runEvidenceV2Command(action,parsed,filesystem,composition);else if(area==="validation")result2=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)&&!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}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"}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_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_run();init_v2_command_areas()}});init_src2();import{basename as basename7,dirname as dirname18,resolve as resolve24}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,message){return{rule,path,line,message}}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,message){return{rule,path,line,message}}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="4.8.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)}
2825
2837
  `);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)}
2826
2838
  `:`${value}
2827
2839
  `;(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
@@ -2882,7 +2894,7 @@ V1 state converted to V2 with source fingerprint \`${fingerprint.sha256}\`.`})),
2882
2894
  `));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 relative16=capability.path.replace(/^\.agents\/specs\/capabilities\//,"");operations.push(bytesOperation("archive","capability",capability.path,capability.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/capabilities/${relative16}`,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)}
2883
2895
  - 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,sha2562("")]))};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]=sha2562(file2.content);operations.push(textOperation("convert","config",file2.path,source.sha256,file2.path,file2.content));continue}}managedFiles[file2.path]=sha2562(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/${sha2562(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 createHash31}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 dirname4}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 journalPath=`${stateRoot}/journal.json`;const inspected=await inspectTargets(filesystem,plan.operations);const journal=await readJournal(filesystem,journalPath);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:journalPath}}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,journalPath,plan,"completed",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"applied",created:[],reused:inspected.identical,journal_path:journalPath}}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,journalPath,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(sha2565(backupBytes)!==source.sha256){throw new MigrationCollisionError(`Divergent migration backup: ${backupPath}`)}}else{await writeBytesAtomic(filesystem,backupPath,sourceBytes)}}await writeJournal(filesystem,journalPath,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(sha2565(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(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}}else{await writeBytesAtomic(filesystem,stagePath,bytes)}}await writeJournal(filesystem,journalPath,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,journalPath,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,journalPath,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,journalPath,plan,"completed",ownedCreated,ownedReused);return{migration_id:plan.migration_id,status:created.length===0?"noop":"applied",created:created.sort(),reused:[...reused].sort(),journal_path:journalPath}}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 journalPath=`${stateRoot}/journal.json`;const[journal,targets]=await Promise.all([readJournal(filesystem,journalPath),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:journalPath,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 journalPath=`${stateRoot}/journal.json`;const journal=await readJournal(filesystem,journalPath);if(journal===null)throw new Error(`Migration journal not found: ${journalPath}`);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(sha2565(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(sha2565(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:journalPath}}await writeJournal(filesystem,journalPath,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,journalPath,plan,"rolled_back",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"rolled-back",removed:removed.sort(),restored:restored.sort(),journal_path:journalPath}}async function fingerprintV1Source2(filesystem){const paths=(await filesystem.listFiles(".agents")).filter(path=>!path.startsWith(".agents/config/")&&!path.startsWith(".agents/data/")).sort();const files=[];for(const path of paths){const bytes=await readFile5(filesystem.resolve(path));files.push({path,sha256:sha2565(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)}
2884
2896
  `,"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=sha2565(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=sha2565(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(sha2565(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(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}const target=filesystem.resolve(operation.target_path);await mkdir2(dirname4(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)}
2885
- `,"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(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(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 sha2565(value){return createHash31("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(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="4.7.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=createHash32("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=resolve6(workspaceRoot);const source=resolve6(root,sourcePath);const target=resolve6(root,".agents/runtime");const backup=resolve6(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(resolve6(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=resolve6(workspaceRoot);const target=resolve6(root,".agents/runtime");const backup=resolve6(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 createHash33}from"node:crypto";import{cp as cp2,lstat as lstat5,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative7,resolve as resolve7,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=resolve7(distributionRoot,asset);const destination=resolve7(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=resolve7(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=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve7(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve7(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=resolve7(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(resolve7(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,resolve7(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=resolve7(root,portable);if(!destination.startsWith(`${resolve7(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash33("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat5(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 dirname6,resolve as resolve8}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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(resolve8(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 paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.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 createHash55}from"node:crypto";import{lstat as lstat13,readFile as readFile11}from"node:fs/promises";import{resolve as resolve19}from"node:path";var hash5=value=>createHash55("sha256").update(value).digest("hex");async function boundedFile(path){const info=await lstat13(path);if(!info.isFile()||info.isSymbolicLink()||info.size>2097152)throw new Error("Unsafe hook readiness file");return readFile11(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(resolve19(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(resolve19(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(resolve19(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(context){const{area,action,parsed,filesystem,root,json:json2}=context;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve20(dirname14(executable),"..");const distributionRoot=basename5(executableRoot)===".agents"?executableRoot:resolve20(executableRoot,"..");if(basename5(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename5(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??basename5(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)}
2897
+ `,"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(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(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 sha2565(value){return createHash31("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(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="4.8.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=createHash32("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=resolve6(workspaceRoot);const source=resolve6(root,sourcePath);const target=resolve6(root,".agents/runtime");const backup=resolve6(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(resolve6(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=resolve6(workspaceRoot);const target=resolve6(root,".agents/runtime");const backup=resolve6(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 createHash33}from"node:crypto";import{cp as cp2,lstat as lstat5,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative7,resolve as resolve7,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=resolve7(distributionRoot,asset);const destination=resolve7(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=resolve7(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=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve7(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve7(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=resolve7(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(resolve7(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,resolve7(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=resolve7(root,portable);if(!destination.startsWith(`${resolve7(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash33("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat5(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 dirname6,resolve as resolve8}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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=resolve8(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve8(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(resolve8(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 paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.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 createHash55}from"node:crypto";import{lstat as lstat13,readFile as readFile11}from"node:fs/promises";import{resolve as resolve19}from"node:path";var hash5=value=>createHash55("sha256").update(value).digest("hex");async function boundedFile(path){const info=await lstat13(path);if(!info.isFile()||info.isSymbolicLink()||info.size>2097152)throw new Error("Unsafe hook readiness file");return readFile11(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(resolve19(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(resolve19(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(resolve19(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(context){const{area,action,parsed,filesystem,root,json:json2}=context;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve20(dirname14(executable),"..");const distributionRoot=basename5(executableRoot)===".agents"?executableRoot:resolve20(executableRoot,"..");if(basename5(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename5(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??basename5(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)}
2886
2898
  `);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 paths=await filesystem.listFiles(".agents/records/changes",".md");let matches=0;for(const candidate of paths){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 execFile23}from"node:child_process";import{createHash as createHash57}from"node:crypto";import{promisify as promisify23}from"node:util";init_cli_arguments();init_commit_policy();import{chmod,mkdir as mkdir9,readFile as readFile12,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname16,resolve as resolve21}from"node:path";var taskCommitHook=`#!/bin/sh
2887
2899
  # zaip-managed task-commit-policy v1
2888
2900
  # Git passes its proposed index, including commit --only's alternate index.
@@ -2945,4 +2957,4 @@ Autonomous execution: execution run ID [--materialize-only] [--continue-independ
2945
2957
  Direct delivery: conversation start or run start --direct-authorization HUMAN-REFERENCE; only an observed Task-scoped root, no fake executor; Gui and Evidence still required
2946
2958
  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_stop_receipt();async function hookCommand(filesystem,parsed){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"}}init_lifecycle_v2();import{spawn as spawn2}from"node:child_process";import{dirname as dirname17}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 paths=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])paths.add(match[1].replace(/\\/g,"/"))}}return[...paths].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 paths=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)))paths.add(path)}return[...paths].sort()}function runUiServer(serverPath,workspace){const child=spawn2(process.execPath,[serverPath],{cwd:dirname17(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 execFile22}from"node:child_process";import{lstat as lstat14,realpath as realpath14}from"node:fs/promises";import{basename as basename6,isAbsolute as isAbsolute13,relative as relative14,resolve as resolve22,sep as sep7}from"node:path";import{promisify as promisify22}from"node:util";var execFileAsync11=promisify22(execFile22);var shaPattern=/^[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(!isAbsolute13(repository2.path)||repository2.path.includes("\0")){return[{code:"target-path-invalid",message:"Migration target path must be absolute"}]}let target;try{target=await realpath14(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([git5(target,["branch","--show-current"]),git5(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(!basename6(evidence.migration.path).startsWith(evidence.migration.id)){findings.push({code:"migration-id-filename-mismatch",message:"Migration id must be the filename prefix"})}if(!shaPattern.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(check2=>check2.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 realpath14(targetPath);const migrationFile=resolve22(target,evidence.migration.path);if(!within(target,migrationFile)){return[{code:"migration-path-escape",message:"Migration path escapes the configured target"}]}try{const physicalMigrationFile=await realpath14(migrationFile);const status=await lstat14(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 git5(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 git5(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 git5(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 git5(target,["cat-file","-t",`${evidence.candidate.sha}:${evidence.migration.path}`]);if(type!=="blob")throw new Error("candidate object is not a blob");await git5(target,["diff","--quiet","--",evidence.migration.path]);await git5(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(check2=>typeof check2==="object"&&check2!==null&&typeof check2.id==="string"&&["passed","failed"].includes(String(check2.status)))){throw new Error("Candidate checks must each have id and passed or failed status")}return value}async function git5(cwd,args){const result2=await execFileAsync11("git",[...args],{cwd,windowsHide:true,encoding:"utf8"});return result2.stdout.trim()}function within(root,candidate){const path=relative14(root,candidate);return path===""||!path.startsWith(`..${sep7}`)&&path!==".."&&!isAbsolute13(path)}init_task_execution_resolution_v2();init_cli_arguments();import{lstat as lstat15,realpath as realpath15}from"node:fs/promises";import{isAbsolute as isAbsolute14,relative as relative15,resolve as resolve23,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 realpath15(root);const target=resolve23(root,requestedPath);if(!within2(physicalRoot,target))throw new UsageError("Tool write path escapes workspace root");let ancestor=target;while(true){try{const status=await lstat15(ancestor);const physicalAncestor=await realpath15(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=resolve23(ancestor,"..");if(parent===ancestor||!within2(resolve23(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")&&!isAbsolute14(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=relative15(root,candidate);return fromRoot===""||!fromRoot.startsWith(`..${sep8}`)&&fromRoot!==".."&&!isAbsolute14(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 check2 of commands){const outcome=await runProcess2(check2.command,check2.args,filesystem.root);lines2.push(`$ ${check2.command} ${check2.args.join(" ")}
2947
2959
  ${outcome.output}`);checks.push({name:check2.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")}
2948
- `);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.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="4.7.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 execFileAsync12=promisify23(execFile23);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve24(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==="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=createHash57("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([execFileAsync12("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync12("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 execFileAsync12("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(createHash57("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}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}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(message=>({field:"clients",message})));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=resolve24(dirname18(executable),"..");const distributionRoot=basename7(executableRoot)===".agents"?executableRoot:resolve24(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename7(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(resolve24(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 message=error51 instanceof Error?error51.message:String(error51);output({error:message},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(resolve24(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};
2960
+ `);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.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="4.8.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 execFileAsync12=promisify23(execFile23);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve24(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==="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=createHash57("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([execFileAsync12("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync12("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 execFileAsync12("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(createHash57("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}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}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(message=>({field:"clients",message})));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=resolve24(dirname18(executable),"..");const distributionRoot=basename7(executableRoot)===".agents"?executableRoot:resolve24(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename7(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(resolve24(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 message=error51 instanceof Error?error51.message:String(error51);output({error:message},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(resolve24(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};