@ornexus/neocortex 4.60.65 → 4.60.66

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 (42) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +23 -23
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +9 -2
  6. package/packages/client/dist/commands/architecture-root-binding.js +1 -1
  7. package/packages/client/dist/commands/invoke.d.ts +1 -1
  8. package/packages/client/dist/commands/invoke.js +79 -78
  9. package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
  10. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  11. package/packages/client/dist/git/direct-yolo-c01-retry.d.ts +21 -0
  12. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -0
  13. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +1 -5
  14. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  15. package/packages/client/dist/git/git-lifecycle-store.d.ts +0 -2
  16. package/packages/client/dist/git/git-lifecycle-store.js +8 -9
  17. package/packages/client/dist/private-execution/clean-baseline.d.ts +2 -3
  18. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  19. package/packages/client/dist/private-execution/isolated-admission.d.ts +2 -0
  20. package/packages/client/dist/private-execution/isolated-admission.js +16 -11
  21. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +16 -0
  22. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -0
  23. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +7 -0
  24. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  25. package/packages/shared/dist/architecture-non-ui-scope.js +22 -0
  26. package/packages/shared/dist/architecture-public-topology.js +11 -0
  27. package/packages/shared/dist/invocation/index.js +4 -2
  28. package/packages/shared/dist/private-qa-structural-admission.js +14 -0
  29. package/packages/shared/dist/private-yolo-predecessor-decision.js +32 -0
  30. package/packages/shared/dist/project-validation-commands.js +74 -0
  31. package/packages/shared/dist/yolo/spec-envelope.js +2 -0
  32. package/targets-stubs/antigravity/gemini.md +1 -1
  33. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  34. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  35. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  36. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  37. package/targets-stubs/claude-code/neocortex.md +2 -2
  38. package/targets-stubs/codex/AGENTS.md +1 -1
  39. package/targets-stubs/cursor/agent.md +2 -2
  40. package/targets-stubs/gemini-cli/agent.md +2 -2
  41. package/targets-stubs/opencode/neocortex-root.md +1 -1
  42. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,59 +1,60 @@
1
- import{classifyNonUiArchitectureTransition as ya,architectureMemoryPredecessorCount as Xn}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Zn}from"./shared-architecture-non-ui.js";import{createHash as Ge,randomUUID as en}from"node:crypto";import{loadPactAnswerReceipt as er,loadPactPrivateAnswers as Ea}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Bt,deriveArchitectureTerminalMemoryReceipt as _n}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as $t,explicitArchitectureEpicTarget as Ia}from"./architecture-root-binding.js";import{derivePactWriteSet as Sa}from"../private-execution/pact-write-set.js";import{execFileSync as je}from"node:child_process";import{existsSync as Ot,readFileSync as Ve,renameSync as tr,unlinkSync as Rn,writeFileSync as tn,mkdirSync as Wt,statSync as va,openSync as Gt,closeSync as Ht,fsyncSync as nn,realpathSync as Ca,lstatSync as Nt}from"node:fs";import{isDeepStrictEqual as E}from"node:util";import{join as X,isAbsolute as wa,resolve as nr}from"node:path";import{homedir as Ft}from"node:os";import{isPrivateExecutionPublicEnvelope as _a,isPrivatePlanningRootPublicEnvelope as Ra,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Aa}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as rr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as ar}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as ir}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as ba}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as xa}from"../../../shared/dist/planning/diagnosis-state.js";import{LicenseClient as Ta}from"../license/license-client.js";import{EncryptedCache as An}from"../cache/encrypted-cache.js";import{NoOpCache as or}from"../types/index.js";import{resolveClientPreFlightTrigger as bn,TierAwareClient as Pa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as Ct,COMMAND_REGISTRY_VERSION as wt,GENERATED_CLIENT_COMMANDS as ka}from"../generated/command-registry.generated.js";import{loadSecureConfig as cr}from"../config/secure-config.js";import{neocortexProfileDirectory as Oa}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as Na}from"../constants.js";import{detectFirstRunLocale as Da,renderFirstRunMessage as La}from"../i18n/first-run.js";import{humanizeError as sr,formatHumanizedError as dr,detectErrorLocale as pr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Ma,projectStateSnapshotForInvoke as ur,projectStateSnapshotResultV2ForInvoke as ja}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Va,maybeRepairStateJsonBeforeInvoke as Ua,StateRepairHardStopError as Ba}from"../state/state-json-repair.js";import{StructuralDagError as lr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as $a,StateMigrationApplyError as Wa}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Ga,classifyRunnerBootstrapPolicyFromArgs as Ha}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Fa,ensureRunnerSchedulerBootstrap as qa,observeRunnerOperationalStatus as za}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as hr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as gr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as fr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as mr,openContinuityClientStateStore as Ja}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Ya,runLocalJobsConsoleCommand as Ka}from"../runner/local-console.js";import{detectNativeHostAttestation as Qa,detectPlatform as Xa}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Za}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as Dt}from"../version.js";import{createCapabilityCache as yr,executeInvokeQueryTransport as Er,executeSecondaryNetworkMutation as ei}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as ti,STRICT_READ_ONLY_CLIENT_PROJECTION as Ir,STRICT_READ_ONLY_SERVER_PROJECTION as ni,StrictReadOnlyError as Lt,canonicalizeInvokeEffects as ri,createInvokeEffectContext as ai,verifyStrictReadOnlyReceipt as ii}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as oi,assertInvokeInputEnvelopeV2 as ci,assertProjectIdentityMigrationReceiptV1 as si,buildProjectIdentityPublicDiagnostic as Mt,createInvocationAdmissionReceipt as di,projectInvokeInputEvidenceV1 as Sr,verifyStrictDiagnoseReceiptV1 as pi}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as rn,InvokeInputDecodeError as ui}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as li,finalizeProjectIdentityMigration as hi,prepareProjectIdentityMigration as gi,ProjectIdentityMigrationError as xn,readProjectIdentityMigrationPhase as fi}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as mi}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as yi}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as an}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as vr,classifyGitLifecycleStoryCheckpointProjectionSync as Ei,ensureGitLifecycleRuntimeInitialized as Ii,executeP205TransientAuthorities as Si,persistGitLifecycleGraphAuthority as vi,P205_COMPLETE_COMMAND as Ci,gitLifecycleStoryWriteSet as Cr,readGitLifecycleRuntimeSync as on,verifyLegacyCheckpointMigrationCandidateSync as wi}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as _i}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Ri}from"../private-execution/shared-root-memory-types.js";const cn=Oa(),Tn=X(cn,"cache"),wr=X(Tn,"menu-cache.json"),_r=1440*60*1e3,Rr=3e4,Ar=256*1024,br=Ar,xr=.8,ut="[REDACTED]",Ai=1e5,_t=2e3,bi=200,xi=200,Ti=12,Pi=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ki=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Oi=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Pn=Math.floor(Ar*xr),Tr=X(cn,".first-run-shown"),Ni="pending-epic-claims.json",Pr=64;function kr(e){return X(e,".neocortex",Ni)}function jt(e){const t=kr(e);if(!Ot(t))return{schemaVersion:1,operations:{}};const a=JSON.parse(Ve(t,"utf8"));if(!a||typeof a!="object"||Array.isArray(a))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=a;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Pr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(i)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return a}function kn(e,t){const a=kr(e);Wt(X(e,".neocortex"),{recursive:!0,mode:448});const r=`${a}.${process.pid}.${en()}.tmp`;tn(r,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),tr(r,a)}function Di(e,t){return Ge("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Li(e,t,a="create-epic"){const r=Di(t,a),i=jt(e),n=i.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(i.operations).length>=Pr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=en(),s={...i.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return kn(e,{schemaVersion:1,operations:s}),{key:o,fingerprint:r}}function Mi(e,t){const a=jt(e);if(!a.operations[t])return;const r={...a.operations};delete r[t],kn(e,{schemaVersion:1,operations:r})}function Or(e,t,a,r,i){if(!/^[0-9a-f-]{36}$/.test(a)||!/^P[1-9][0-9]*$/.test(r)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=jt(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==a||o.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");kn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:a,epicId:r,...i?{planningProtocol:i}:{}}}})}function ji(){try{if(Ot(Tr))return;const e=Da(),t=La(e);process.stderr.write(t);try{Wt(cn,{recursive:!0}),tn(Tr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function On(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Vi(e){return oi(e,{registryVersion:wt,registryChecksum:Ct})}const Ui=new Set(["completed","aborted","cancelled"]),Bi=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Ie=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),Ae=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),F=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),Nr=240,$i=/(https?:\/\/\S+|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH))/i;function Wi(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,ut).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,ut).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,ut).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,ut).replace(ki,ut).replace(Oi,ut)}function He(e,t){const a=Wi(e);return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function Nn(e,t=0,a=new WeakSet){if(t>Ti)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return He(e,_t);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(a.has(e))return"[CIRCULAR]";a.add(e);try{if(Array.isArray(e))return e.slice(0,bi).map(i=>Nn(i,t+1,a));const r={};for(const[i,n]of Object.entries(e).slice(0,xi)){if(Pi.test(i)){r[i]=ut;continue}const o=Nn(n,t+1,a);o!==void 0&&(r[i]=o)}return r}finally{a.delete(e)}}}function sn(e,t){return{instructions:He(e??"",Ai),metadata:t?Nn(t):void 0}}class dn extends Error{reason;source;byteLength;code;constructor(t,a,r,i,n){super(a),this.reason=r,this.source=i,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function Gi(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Hi(e,"--project-evidence")}function Hi(e,t){let a=null,r=-1,i=!1,n=!1;for(let o=0;o<=e.length;o+=1){const s=e[o];if(o===e.length||!a&&/\s/.test(s??"")){if(r>=0&&!i&&e.slice(r,o)===t)return!0;r=-1,i=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(s==="\\"){n=!0;continue}(s==='"'||s==="'")&&(i=!0,a=a===s?null:a??s)}return!1}const Fi=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function qi(e,t){if(e.targetId!=="codex")return null;const a=t.CODEX_VERSION?.trim();if(a&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(a))return a;try{return je("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Fi)?.[1]??null}catch{return null}}class Dn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Ln extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Mn=!1;function zi(e){const t=[];if(!e||typeof e!="object")return t;const a=e,r=a.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(a.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),a.epics&&typeof a.epics=="object"&&!Array.isArray(a.epics))for(const[n,o]of Object.entries(a.epics)){const s=o;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=a.epics&&typeof a.epics=="object"&&Object.keys(a.epics).length>0||a.stories&&typeof a.stories=="object"&&!Array.isArray(a.stories)&&Object.keys(a.stories).length>0||Array.isArray(a.stories)||r&&r.current!==void 0;return a.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):a.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(a.schema_version)} (expected: 1)`}),t}function Ji(e){if(!(Mn||e.length===0)){Mn=!0;try{const t=e.map(a=>` - ${a.message}`).join(`
1
+ import{classifyNonUiArchitectureTransition as Ca,architectureMemoryPredecessorCount as nr}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as rr}from"./shared-architecture-non-ui.js";import{createHash as Ye,randomUUID as en}from"node:crypto";import{loadPactAnswerReceipt as ar,loadPactPrivateAnswers as wa}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as $t,deriveArchitectureTerminalMemoryReceipt as An}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Gt,explicitArchitectureEpicTarget as _a}from"./architecture-root-binding.js";import{derivePactWriteSet as Ra}from"../private-execution/pact-write-set.js";import{execFileSync as Ve}from"node:child_process";import{existsSync as Nt,readFileSync as Ue,renameSync as ir,unlinkSync as bn,writeFileSync as tn,mkdirSync as Wt,statSync as Aa,openSync as Ht,closeSync as qt,fsyncSync as nn,realpathSync as ba,lstatSync as Lt}from"node:fs";import{isDeepStrictEqual as E}from"node:util";import{join as J,isAbsolute as xa,resolve as or}from"node:path";import{homedir as Ft}from"node:os";import{isPrivateExecutionPublicEnvelope as Ta,isPrivatePlanningRootPublicEnvelope as Pa,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ka}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as cr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as sr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as dr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Oa}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as Na}from"../../../shared/dist/planning/diagnosis-state.js";import{LicenseClient as La}from"../license/license-client.js";import{EncryptedCache as xn}from"../cache/encrypted-cache.js";import{NoOpCache as pr}from"../types/index.js";import{resolveClientPreFlightTrigger as rn,TierAwareClient as Da}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as At,COMMAND_REGISTRY_VERSION as bt,GENERATED_CLIENT_COMMANDS as Ma}from"../generated/command-registry.generated.js";import{loadSecureConfig as Tn}from"../config/secure-config.js";import{neocortexProfileDirectory as ja}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as Va}from"../constants.js";import{detectFirstRunLocale as Ua,renderFirstRunMessage as Ba}from"../i18n/first-run.js";import{humanizeError as ur,formatHumanizedError as lr,detectErrorLocale as hr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as $a,projectStateSnapshotForInvoke as fr,projectStateSnapshotResultV2ForInvoke as Ga}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as gr,maybeRepairStateJsonBeforeInvoke as Wa,StateRepairHardStopError as Ha}from"../state/state-json-repair.js";import{StructuralDagError as mr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as qa,StateMigrationApplyError as Fa}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Ya,classifyRunnerBootstrapPolicyFromArgs as za}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ja,ensureRunnerSchedulerBootstrap as Ka,observeRunnerOperationalStatus as Qa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as yr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Er,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Ir,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Sr,openContinuityClientStateStore as Xa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Za,runLocalJobsConsoleCommand as ei}from"../runner/local-console.js";import{detectNativeHostAttestation as ti,detectPlatform as ni}from"../adapters/platform-detector.js";import{signNxInvokeRequest as ri}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ai}from"../../../shared/dist/yolo/spec-envelope.js";import{CLIENT_VERSION as Dt}from"../version.js";import{createCapabilityCache as vr,executeInvokeQueryTransport as Cr,executeSecondaryNetworkMutation as ii}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as oi,STRICT_READ_ONLY_CLIENT_PROJECTION as wr,STRICT_READ_ONLY_SERVER_PROJECTION as ci,StrictReadOnlyError as Mt,canonicalizeInvokeEffects as si,createInvokeEffectContext as di,verifyStrictReadOnlyReceipt as pi}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as ui,assertInvokeInputEnvelopeV2 as li,assertProjectIdentityMigrationReceiptV1 as hi,buildProjectIdentityPublicDiagnostic as jt,createInvocationAdmissionReceipt as fi,projectInvokeInputEvidenceV1 as _r,verifyStrictDiagnoseReceiptV1 as gi}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as an,InvokeInputDecodeError as mi}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as yi,finalizeProjectIdentityMigration as Ei,prepareProjectIdentityMigration as Ii,ProjectIdentityMigrationError as Pn,readProjectIdentityMigrationPhase as Si}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as vi}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Ci}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as on}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Rr,classifyGitLifecycleStoryCheckpointProjectionSync as wi,ensureGitLifecycleRuntimeInitialized as _i,executeP205TransientAuthorities as Ri,persistGitLifecycleGraphAuthority as Ai,P205_COMPLETE_COMMAND as bi,gitLifecycleStoryWriteSet as Ar,readGitLifecycleRuntimeSync as cn,verifyLegacyCheckpointMigrationCandidateSync as xi}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Ti}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Pi}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as ki}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as br,extractTargetedYoloStoryId as Oi,refreshPrecollectedYoloSpecEnvelope as Ni}from"../yolo/spec-envelope-collector.js";const sn=ja(),kn=J(sn,"cache"),xr=J(kn,"menu-cache.json"),Tr=1440*60*1e3,Pr=3e4,kr=256*1024,Or=kr,Nr=.8,ft="[REDACTED]",Li=1e5,xt=2e3,Di=200,Mi=200,ji=12,Vi=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Ui=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Bi=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,On=Math.floor(kr*Nr),Lr=J(sn,".first-run-shown"),$i="pending-epic-claims.json",Dr=64;function Mr(e){return J(e,".neocortex",$i)}function Vt(e){const t=Mr(e);if(!Nt(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(Ue(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=r;if(a.schemaVersion!==1||!a.operations||typeof a.operations!="object"||Array.isArray(a.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(a.operations).length>Dr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,n]of Object.entries(a.operations)){if(!/^[a-f0-9]{64}$/.test(i)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return r}function Nn(e,t){const r=Mr(e);Wt(J(e,".neocortex"),{recursive:!0,mode:448});const a=`${r}.${process.pid}.${en()}.tmp`;tn(a,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),ir(a,r)}function Gi(e,t){return Ye("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Wi(e,t,r="create-epic"){const a=Gi(t,r),i=Vt(e),n=i.operations[a];if(n)return{key:n.idempotencyKey,fingerprint:a};if(Object.keys(i.operations).length>=Dr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=en(),s={...i.operations,[a]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Nn(e,{schemaVersion:1,operations:s}),{key:o,fingerprint:a}}function Hi(e,t){const r=Vt(e);if(!r.operations[t])return;const a={...r.operations};delete a[t],Nn(e,{schemaVersion:1,operations:a})}function jr(e,t,r,a,i){if(!/^[0-9a-f-]{36}$/.test(r)||!/^P[1-9][0-9]*$/.test(a)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=Vt(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==r||o.epicId!==a))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Nn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:r,epicId:a,...i?{planningProtocol:i}:{}}}})}function qi(){try{if(Nt(Lr))return;const e=Ua(),t=Ba(e);process.stderr.write(t);try{Wt(sn,{recursive:!0}),tn(Lr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Ln(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Fi(e){return ui(e,{registryVersion:bt,registryChecksum:At})}const Yi=new Set(["completed","aborted","cancelled"]),zi=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Se=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),be=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),W=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),Vr=240,Ji=/(https?:\/\/\S+|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH))/i;function Ki(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,ft).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,ft).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,ft).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,ft).replace(Ui,ft).replace(Bi,ft)}function ze(e,t){const r=Ki(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function Dn(e,t=0,r=new WeakSet){if(t>ji)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return ze(e,xt);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(r.has(e))return"[CIRCULAR]";r.add(e);try{if(Array.isArray(e))return e.slice(0,Di).map(i=>Dn(i,t+1,r));const a={};for(const[i,n]of Object.entries(e).slice(0,Mi)){if(Vi.test(i)){a[i]=ft;continue}const o=Dn(n,t+1,r);o!==void 0&&(a[i]=o)}return a}finally{r.delete(e)}}}function dn(e,t){return{instructions:ze(e??"",Li),metadata:t?Dn(t):void 0}}class pn extends Error{reason;source;byteLength;code;constructor(t,r,a,i,n){super(r),this.reason=a,this.source=i,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function Qi(e){const t=rn(e);return(t==="arch-plan"||t==="ui-ux-review")&&Xi(e,"--project-evidence")}function Xi(e,t){let r=null,a=-1,i=!1,n=!1;for(let o=0;o<=e.length;o+=1){const s=e[o];if(o===e.length||!r&&/\s/.test(s??"")){if(a>=0&&!i&&e.slice(a,o)===t)return!0;a=-1,i=!1,n=!1;continue}if(a<0&&(a=o),n){n=!1;continue}if(s==="\\"){n=!0;continue}(s==='"'||s==="'")&&(i=!0,r=r===s?null:r??s)}return!1}const Zi=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function eo(e,t){if(e.targetId!=="codex")return null;const r=t.CODEX_VERSION?.trim();if(r&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(r))return r;try{return Ve("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Zi)?.[1]??null}catch{return null}}class Mn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class jn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Vn=!1;function to(e){const t=[];if(!e||typeof e!="object")return t;const r=e,a=r.planning;if(a&&(a.current!==void 0||Array.isArray(a.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(r.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),r.epics&&typeof r.epics=="object"&&!Array.isArray(r.epics))for(const[n,o]of Object.entries(r.epics)){const s=o;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=r.epics&&typeof r.epics=="object"&&Object.keys(r.epics).length>0||r.stories&&typeof r.stories=="object"&&!Array.isArray(r.stories)&&Object.keys(r.stories).length>0||Array.isArray(r.stories)||a&&a.current!==void 0;return r.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):r.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(r.schema_version)} (expected: 1)`}),t}function no(e){if(!(Vn||e.length===0)){Vn=!0;try{const t=e.map(r=>` - ${r.message}`).join(`
3
3
  `);process.stderr.write(`[Neocortex] state.json schema drift detected:
4
4
  ${t}
5
5
  Run \`neocortex *migrate-state --preview\` to inspect or \`neocortex *migrate-state --apply\` to migrate.
6
6
  See docs/arquitetura-software/STATE-JSON-SCHEMA.md for the schema contract.
7
- `)}catch{}}}function Ss(){Mn=!1}function Dr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Yi(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Ki=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),Qi=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Xi(e,t){if(!(!u(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const a=JSON.stringify(e);if(Buffer.byteLength(a)>16384||Qi.test(a))return;const r=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(r(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!u(e.intake)||Object.keys(e.intake).some(n=>!Ki.has(n)))return;for(const[n,o]of Object.entries(e.intake))if(["examples","contracts"].includes(n)){const s=n==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(o)||o.length>16)return;for(const p of o)if(!u(p)||(r(p,s),Object.values(p).some(m=>typeof m!="string"||m.length>256)))return}else if(Array.isArray(o)){if(o.length>32||o.some(s=>typeof s!="string"||s.length>256))return}else if(typeof o=="string"){if(o.length>(n==="rawIntent"?xa:512))return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const i=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!u(n)||(r(n,i),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!u(e.degradeAuthorization))return;r(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const n of["reasonCodes","assumptionCodes"]){const o=e.degradeAuthorization[n];if(!Array.isArray(o)||o.length>32||o.some(s=>typeof s!="string"||s.length>128))return}}return JSON.parse(a)}catch{return}}function Lr(e){return e==="create-epic"||e==="discovered"?e:void 0}function Ue(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Zi(e){const t={};let a=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const i=e[r];if(!Array.isArray(i)||i.length>128||i.some(n=>an(n)===void 0)){a=!0;continue}t[r]=i.map(n=>an(n))}if(e.planning!==void 0)try{if(!u(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const s=r[o];if(!Array.isArray(s)||s.length>128||s.some(p=>!u(p)||an(p.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!u(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(s=>!u(s)||an(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...n}=yi(r);t.planning=n}catch{a=!0}return a&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function u(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ne(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function Z(e){if(typeof e!="string")return;const t=e.trim(),a=ne(e);return a===t?a:void 0}function Ce(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(a=>!a||a.startsWith(".")||a.endsWith(".lock")))return t}function x(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Be(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function ht(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function pn(e){if(!u(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),a=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),r=(l,v)=>Array.isArray(l)&&l.length<=v&&l.every(t)&&new Set(l).size===l.length?l:void 0,i=(l,v)=>{if(!(!u(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!a(l.requestHash)||!a(l.inputHash)||!a(l.stateHash)||!a(l.nonce)||!a(l.stageRevision)||!a(l.stageHash)||!a(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||v&&(!a(l.outputHash)||!a(l.artifactHash))))return{schemaVersion:2,...l.targetEpicId?{targetEpicId:l.targetEpicId}:{},requestId:l.requestId,requestHash:l.requestHash,inputHash:l.inputHash,stateHash:l.stateHash,nonce:l.nonce,stageCommand:l.stageCommand,stageRevision:l.stageRevision,stageHash:l.stageHash,catalogHash:l.catalogHash,...v?{outputHash:l.outputHash,artifactHash:l.artifactHash}:{}}},n=(l,v)=>{if(!(!u(l)||l.schemaVersion!=="1.1"||l.kind!==v||!a(l.receiptId)||!a(l.graphHash)||!a(l.evidenceHash)||!t(l.elementId)||!t(l.caseId)||!t(l.category)))return{schemaVersion:"1.1",kind:v,receiptId:l.receiptId,graphHash:l.graphHash,elementId:l.elementId,caseId:l.caseId,category:l.category,evidenceHash:l.evidenceHash}},o=(l,v)=>{if(!u(l)||l.kind!==v||!a(l.receiptId)||!r(l.evidenceIds,24)||v==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(l.status))||v==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(l.status)))return;const f=i(l,!0);if(!f)return;const h=v==="architecture-stage-validation"?n(l.isolated,"isolated"):void 0,C=v==="architecture-stage-validation"?n(l.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!h||!C)))return{...f,kind:v,receiptId:l.receiptId,status:l.status,evidenceIds:l.evidenceIds,...h&&C?{isolated:h,regression:C}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const p=r(e.questionIds,16);if(p&&(s.questionIds=p),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),a(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const l=Zn(e.nonUiScopeReceipt);if(!l||l.targetEpicId!==e.targetEpicId||l.graphRevision!==e.graphRevision||!u(e.accounting)||l.accountingId!==e.accounting.accountingId||!u(e.evidenceExpectation)||l.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=l}u(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&a(e.pactAnswerReceipt.stateSha256)&&a(e.pactAnswerReceipt.answersSha256)&&E(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const m=i(e.evidenceExpectation,!1);m&&(s.evidenceExpectation=m);const S=o(e.completionEvidence,"architecture-stage-completion"),_=o(e.validationEvidence,"architecture-stage-validation");if(S&&(s.completionEvidence=S),_&&(s.validationEvidence=_),u(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&a(e.reviewDecision.graphRevision)&&a(e.reviewDecision.artifactHash)&&a(e.reviewDecision.completionReceiptId)&&a(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const l=r(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(Bt(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(u(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=r(e.terminalMemoryCheckpoint.evidenceIds,24);l&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:l})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const l=e.acceptedStages.map(v=>{if(!u(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const f=o(v.completionEvidence,"architecture-stage-completion"),h=o(v.validationEvidence,"architecture-stage-validation");return f&&h?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:f,validationEvidence:h}:void 0});l.every(v=>v!==void 0)&&(s.acceptedStages=l)}if(u(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const l=r(e.accounting.receiptIds,32);l&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:l,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function eo(e){const t=u(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,a=u(t)?t.checkpoint:void 0,r=u(t)?t:void 0,i=u(a)?a:void 0,n=e.requestExecution,o=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",p=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&o.length===1&&u(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",m=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",S=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&o.length===2&&u(o[0])&&u(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&E(o[0],n.acceptedStages[0])&&E(o[1].completionEvidence,n.completionEvidence)&&E(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",_=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&o.length===2&&u(o[0])&&u(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",l=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&o.length===3&&u(o[0])&&u(o[1])&&u(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&E(o.slice(0,2),n.acceptedStages)&&E(o[2].completionEvidence,n.completionEvidence)&&E(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&o.length===3&&u(o[0])&&u(o[1])&&u(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",f=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&o.length===4&&u(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&E(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&E(o[3].completionEvidence,n.completionEvidence)&&E(o[3].validationEvidence,n.validationEvidence)&&E(i.questionIds,f)&&E(r?.questionIds,f)&&r?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,f)&&E(i.questionIds,[])&&E(i.pactAnswerReceipt,e.answerReceipt)&&E(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",N=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&u(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",P=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&u(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",M=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",I=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&u(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",b=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",re=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&u(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",$=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&u(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",W=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&r?.nextAction==="blocked",j=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&u(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",_e=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&u(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Y=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",O=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&u(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",U=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",at=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(k=>u(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&u(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Te=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",me=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",At=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&u(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&u(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",it=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&u(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",z=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&u(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&E(o[14].completionEvidence,n.completionEvidence)&&E(o[14].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&Bt(i.terminalMemoryCheckpoint,n)!==null&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",oe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&Bt(i.terminalMemoryCheckpoint,n)&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",ce=r?ya(n,r,Bt(n.terminalMemoryCheckpoint,n)&&E(i?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!u(t)||!u(a)||t.owner!=="root"||t.currentStageCommand!==a.currentStageCommand||t.continuationState!==a.continuationState||a.owner!=="root"||a.evidencePolicy!=="v2-required"||a.targetEpicId!==n.targetEpicId||a.graphRevision!==n.graphRevision||a.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(a.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(a.graphRevision))||!Array.isArray(a.acceptedStages)||!(ce||s||p||m||S||_||l||v||h||C||N||L||P||M||I||b||re||w||$||W||j||V||_e||Y||O||U||at||Te||me||At||it||z||oe)||!u(a.accounting)||a.accounting.charged!==!0||!E(pn(a),a))throw new Error("architecture-root-checkpoint-invalid");const Qe=X(e.projectRoot,".neocortex"),Oe=X(Qe,"state.json"),mt=X(Qe,"state.json.architecture.lock"),We=Gt(mt,"wx",384);let ee;try{const k=Nt(Oe);if(!k.isFile()||k.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const Pe=Ve(Oe,"utf8");if(Ge("sha256").update(Pe).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const J=JSON.parse(Pe),yt=u(J)&&u(J.archPlan)?J.archPlan:{};if(!u(J)||!u(J.epics)||!Object.hasOwn(J.epics,a.targetEpicId)||(e.initialBinding?yt.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(pn(yt.execution),n))||u(J.scope)&&J.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==$t(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(oe||ce==="complete-replay"){const Yt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,Xn(n))};if(!E(n.terminalMemoryCheckpoint,_n(e.projectRoot,Yt)))throw new Error("architecture-root-state-conflict");return}const Xe=en(),ye=je("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),K=wa(ye)?nr(ye):nr(e.projectRoot,ye);if(Ca(K)!==K)throw new Error("architecture-root-backup-dir-invalid");const bt=X(K,"neocortex-architecture");Wt(bt,{recursive:!0,mode:448});const T=Nt(bt);if(!T.isDirectory()||T.isSymbolicLink()||T.uid!==process.getuid?.()||(T.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const xt=X(bt,`state-backup-${Xe}.json`),g=Gt(xt,"wx",384);try{tn(g,Pe),nn(g)}finally{Ht(g)}const Tt=Gt(bt,"r");try{nn(Tt)}finally{Ht(Tt)}const ge={...J,archPlan:{...yt,execution:a}};ee=X(Qe,`state.json.architecture-tmp-${Xe}`);const ot=Gt(ee,"wx",384);try{tn(ot,`${JSON.stringify(ge,null,2)}
8
- `),nn(ot)}finally{Ht(ot)}if((z||ce==="complete")&&!E(n.terminalMemoryCheckpoint,_n(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==$t(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");tr(ee,Oe),ee=void 0;const Q=Gt(Qe,"r");try{nn(Q)}finally{Ht(Q)}}finally{if(ee)try{Rn(ee)}catch{}Ht(We),Rn(mt)}}function un(e,t){if(!u(e))return;const a={};for(const r of t){const i=e[r];if(typeof i=="boolean")a[r]=i;else if(typeof i=="number"&&Number.isFinite(i))a[r]=i;else if(typeof i=="string"){const n=ne(i);n&&(a[r]=n)}}return Object.keys(a).length>0?a:void 0}function ln(e){return e==="epic"||e==="story"?e:void 0}function Mr(e){if(!u(e)||e.schemaVersion!==1)return;const t=Z(e.ownerStoryId),a=Z(e.sessionId),r=Z(e.idempotencyKey),i=Be(e.acquiredAt),n=Be(e.expiresAt);if(!(!t||!a||!r||!i||!n||Date.parse(n)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:a,idempotencyKey:r,acquiredAt:i,expiresAt:n}}function jr(e){if(!u(e)||e.schemaVersion!==1)return;const t=Z(e.storyId),a=Z(e.epicId),r=Ce(e.branch),i=x(e.baseSha),n=x(e.headSha),o=Z(e.idempotencyKey),s=Be(e.recordedAt),p=Ue(e.commits).map(x).filter(L=>!!L).slice(0,256),m=Ue(e.receiptRefs).map(ht).filter(L=>!!L).slice(0,256),S=e.dispatchId===void 0?void 0:Z(e.dispatchId),_=e.bundleId===void 0?void 0:Z(e.bundleId),l=e.bundleDigest===void 0?void 0:x(e.bundleDigest),v=e.graphRevision===void 0?void 0:x(e.graphRevision),f=e.claimRevision===void 0?void 0:Z(e.claimRevision),h=to(e.qaReceipt),C=no(e.reviewReceipt),N=e.rootMemoryEffect===void 0?void 0:Ri(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!a||!t.startsWith(`${a}.`)||!r||!i||!n||i===n||!o||!s||p.length===0||m.length===0||!Array.isArray(e.commits)||p.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||m.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!S||e.bundleId!==void 0&&!_||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!f||e.rootMemoryEffect!==void 0&&(!N||N.storyId!==t||N.epicId!==a||N.executionBranch!==r||N.sourceHeadSha!==i||N.childClaimRevision!==f)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||h.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!Br(h,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:v})||C&&(!Br(C,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:v})||C.qaReceiptRef!==h?.receiptRef||C.receiptRef===h?.receiptRef)||!m.includes(String(h.receiptRef))||C&&(!m.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,idempotencyKey:o,...S?{dispatchId:S}:{},..._?{bundleId:_}:{},...l?{bundleDigest:l}:{},...v?{graphRevision:v}:{},...f?{claimRevision:f}:{},...N?{rootMemoryEffect:structuredClone(N)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:p,receiptRefs:m}}function to(e){if(!u(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=Z(e.storyId),a=Z(e.epicId),r=x(e.baseSha),i=x(e.headSha),n=x(e.bundleDigest),o=x(e.graphRevision),s=x(e.sourceEvidenceDigest),p=Be(e.checkedAt),m=ht(e.receiptRef),S=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,_=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?x(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?x(e.resultDigest):void 0,f=e.evidenceVersion==="p205-execution-v2"?Ue(e.gateIds).map(Z).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!p||!m||e.evidenceVersion==="p205-execution-v2"&&(!S||_!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!f||f.length===0||f.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:a,...e.evidenceVersion==="p205-execution-v2"?{contract:S,command:_,manifestDigest:l,gateIds:f,resultDigest:v}:{},baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:p,receiptRef:m}}function Vr(e){if(!u(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=Z(e.storyId),a=Z(e.epicId),r=Ce(e.branch),i=x(e.baseSha),n=x(e.headSha),o=x(e.aggregateHeadSha),s=x(e.commitBodyDigest),p=x(e.changedPathsDigest),m=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,S=x(e.effectiveClaimRevision),_=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=x(e.manifestDigest),v=Ue(e.gateIds).map(Z).filter(M=>!!M).slice(0,64),f=x(e.resultDigest),h=x(e.graphRevision),C=x(e.executionEvidenceDigest),N=x(e.sourceEvidenceDigest),L=Be(e.verifiedAt),P=Ue(e.reasonCodes).map(Z).filter(M=>!!M).slice(0,16);if(!(!t||!a||!r||!i||i.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!p||p.length!==64||!m||!S||S.length!==64||!_||!l||l.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!f||f.length!==64||!h||h.length!==64||!C||C.length!==64||!N||N.length!==64||!L||P.length===0||e.verdict==="verified"&&(v.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:p,claimVerification:m,effectiveClaimRevision:S,command:_,manifestDigest:l,gateIds:v,resultDigest:f,graphRevision:h,executionEvidenceDigest:C,sourceEvidenceDigest:N,verifiedAt:L,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function Ur(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!u(e)||Object.keys(e).some(l=>!t.includes(l))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const a=Z(e.storyId),r=Z(e.epicId),i=Ce(e.branch),n=x(e.baseSha),o=x(e.headSha),s=x(e.graphRevision),p=x(e.effectiveClaimRevision),m=x(e.sourceEvidenceDigest),S=Be(e.verifiedAt),_=Ue(e.reasonCodes).map(Z).filter(l=>!!l);if(!(!a||!r||!i||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!p||p.length!==64||!m||m.length!==64||!S||!Array.isArray(e.reasonCodes)||_.length!==1||_[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:a,epicId:r,branch:i,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:p,sourceEvidenceDigest:m,verifiedAt:S,reasonCodes:_,integrationAuthorized:!1,publicSafe:!0}}function no(e){if(!u(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=Z(e.storyId),a=Z(e.epicId),r=x(e.baseSha),i=x(e.headSha),n=x(e.bundleDigest),o=x(e.graphRevision),s=x(e.sourceEvidenceDigest),p=ht(e.qaReceiptRef),m=Be(e.reviewedAt),S=ht(e.receiptRef);if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!p||!m||!S))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:a,baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:p,verdict:e.verdict,reviewedAt:m,receiptRef:S}}function Br(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(a=>e[a]===t[a])}function $r(e){if(!u(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=Ce(e.originBranch),a=x(e.originHeadSha),r=Ce(e.executionBranch),i=Be(e.capturedAt);if(!(!t||!a||a.length<40||!r||!i||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:a,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:i}}function Wr(e){if(!u(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=x(e.executionHeadSha),a=x(e.graphRevision),r=Be(e.checkedAt),i=ht(e.receiptRef),n=Ue(e.gateIds).map(Z).filter(S=>!!S).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,p=o?x(e.manifestDigest):void 0,m=o?x(e.resultDigest):void 0;if(!(!t||t.length<40||!a||a.length!==64||!r||!i||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!p||p.length!==64||!m||m.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:p,resultDigest:m}:{},verdict:"passed",executionHeadSha:t,graphRevision:a,checkedAt:r,receiptRef:i,gateIds:n}}function jn(e){if(!u(e)||e.schemaVersion!==1)return;const t=un(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},a=Ue(e.receiptRefs).map(ht).filter(i=>!!i).slice(0,256),r=Ue(e.revertCommits).map(ne).filter(i=>!!i).slice(0,256);return{...t,...a.length?{receiptRefs:a}:{},...r.length?{revertCommits:r}:{}}}function ro(e){if(!(!u(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function Gr(e){if(!u(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=Z(e.epicId),a=Ce(e.executionBranch),r=Ce(e.originBranch),i=x(e.baseSha),n=x(e.executionHeadSha),o=e.mergeSha===void 0?void 0:x(e.mergeSha),s=e.pushedSha===void 0?void 0:x(e.pushedSha),p=Z(e.idempotencyKey),m=Be(e.attemptStartedAt),S=e.completedAt===void 0?void 0:Be(e.completedAt),_=Ue(e.localGateReceiptRefs).map(ht).filter(h=>!!h).slice(0,256),l=Ue(e.reasonCodes).map(Z).filter(h=>!!h).slice(0,64),v=io(e.candidateQa),f=ao(e.providerGuard);if(!(!t||!a||!r||!i||!n||!p||!m||_.length===0||l.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!f||f&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||f.prHeadSha!==o||f.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:a,originBranch:r,baseSha:i,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...lt(e.prNumber)?{prNumber:lt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:_,idempotencyKey:p,attemptStartedAt:m,...v?{candidateQa:v}:{},...f?{providerGuard:f}:{},...S?{completedAt:S}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function ao(e){if(!u(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),a=String(e.source),r=t==="recovered_exact_tree"?a==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(a),i=x(e.prHeadSha),n=x(e.originHeadSha),o=Be(e.checkedAt);if(!(!r||!i||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:a,prHeadSha:i,originHeadSha:n,checkedAt:o,publicSafe:!0}}function io(e){if(!u(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Ci)return;const a=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,x(e[o])])),r=Be(e.checkedAt),i=ht(e.receiptRef),n=Ue(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(a).some(o=>!o)||!r||!i||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...a,checkedAt:r,receiptRef:i,gateIds:n}}function oo(e){if(!u(e))return;const t={...ne(e.active_epic_id??e.activeEpicId)?{active_epic_id:ne(e.active_epic_id??e.activeEpicId)}:{},...ne(e.active_story_id??e.activeStoryId)?{active_story_id:ne(e.active_story_id??e.activeStoryId)}:{},...ne(e.active_step_id??e.activeStepId)?{active_step_id:ne(e.active_step_id??e.activeStepId)}:{},...ne(e.session_id??e.sessionId)?{session_id:ne(e.session_id??e.sessionId)}:{},...ne(e.started_at??e.startedAt)?{started_at:ne(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function co(e){const t=un(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),a=un(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=un(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...ne(e.physicalMergeStatus)?{physicalMergeStatus:ne(e.physicalMergeStatus)}:{},...ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ne(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ne(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...lt(e.issue_number??e.issueNumber)?{issue_number:lt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...a?{issueCloseAudit:a}:{},...r?{scopedCiEvidence:r}:{}}}class gt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const so=new Set(["yolo","yoloop","finalize-epic","audit"]);function Hr(e){return typeof e=="string"&&so.has(e)}function Fr(e,t={}){const a=X(e,".neocortex","state.json");if(!Ot(a))throw new gt("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ve(a,"utf8"))}catch{throw new gt("git-lifecycle-state-corrupt")}if(!u(r)||!u(r.epics)||!u(r.stories))throw new gt("git-lifecycle-state-shape-invalid");const i=Object.values(r.epics).some(n=>u(n)&&(n.branch_mode==="epic"||Ce(n.execution_branch)!==void 0));if(i)try{on(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new gt(o)}return{lifecycleDeclared:i,runtimeMissing:!1}}function hn(e,t={}){const a=X(e,".neocortex","state.json");if(!Ot(a)){if(t.epicAware&&!t.projectless)throw new gt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,i;try{const f=Ve(a,"utf-8");i=Ge("sha256").update(f).digest("hex");const h=JSON.parse(f),C=u(h.epics)?h.epics:{},N=Object.values(C).some(b=>u(b)&&(b.branch_mode==="epic"||Ce(b.execution_branch)!==void 0)),L=on(e,{required:!!(t.epicAware&&N&&!t.projectless)});r=vr(h,L);const P=u(r.stories)?r.stories:{},M=u(r.epics)?r.epics:{},I=u(h.stories)?h.stories:{};for(const[b,re]of Object.entries(P)){const w=u(re)?re:void 0;if(!w?.checkpoint)continue;const $=typeof w.epic_id=="string"?w.epic_id:b.split(".")[0],W=u(M[$])?M[$]:void 0,j=Ce(W?.execution_branch);if(!j)continue;const V=Ei(e,w.checkpoint,b,$,j,t.p205Authorities?.[b],Cr(b,w,u(w.checkpoint)?w.checkpoint:void 0));if(V.kind==="integration-authorized")w.checkpoint_verification=V.verification,delete w.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")w.scheduling_checkpoint_evidence=V.evidence,delete w.checkpoint,delete w.checkpoint_verification;else if(V.kind==="rejected"){w.checkpoint_verification=V.verification,delete w.scheduling_checkpoint_evidence;const _e=u(I[b])?I[b]:void 0;if(delete w.checkpoint,L.stories[b]?.checkpoint!==void 0)for(const Y of["status","last_step","steps_completed"])_e&&Object.prototype.hasOwnProperty.call(_e,Y)?w[Y]=structuredClone(_e[Y]):delete w[Y];["done","completed","merged"].includes(String(w.status).toLowerCase())&&(w.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const h=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new gt(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=zi(r);f.length>0&&Ji(f)}catch{}const n=r.config??r.project??{},o=r.stories??{},s={};for(const[f,h]of Object.entries(o)){const C=u(h.review_request)&&h.review_request.kind==="git-pull-request"?ro(h.review_request):jn(h.review_request);s[f]={id:h.id??f,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...Lr(h.source)?{source:Lr(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...ln(h.branch_mode)?{branch_mode:ln(h.branch_mode)}:{},...jr(h.checkpoint)?{checkpoint:jr(h.checkpoint)}:{},...Vr(h.checkpoint_verification)?{checkpoint_verification:Vr(h.checkpoint_verification)}:{},...Ur(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Ur(h.scheduling_checkpoint_evidence)}:{},...C?{review_request:C}:{},...jn(h.rollback_receipt)?{rollback_receipt:jn(h.rollback_receipt)}:{},...lt(h.workflow_issue)?{workflow_issue:lt(h.workflow_issue)}:{},...co(h),depends_on:Dr(h.depends_on),files_to_modify:Ue(h.files_to_modify),...Zi(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const p=r.epics??{},m={};for(const[f,h]of Object.entries(p)){const C=Yi(h.lifecycle_classification),N=Xi(h.createEpicPlanning,f);let L,P,M,I;if(N&&u(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&u(h.createEpicPlanningPhysical))try{rr(r,h.createEpicPlanningClaim.claimId,f,!0),L=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(L&&u(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&u(h.createEpicPlanningResearchPhysical))try{ar(r,h.createEpicPlanningClaim.claimId,f),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&N&&h.status==="generated"&&u(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&u(h.createEpicPlanningGenerationPhysical))try{if(ba(e,h.createEpicPlanningClaim.claimId,f).stateSha256!==i)throw new Error("planning-generation-snapshot-raced");M=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),L=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(M&&u(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const b=ir(e,h.createEpicPlanningClaim.claimId,f);if(b.stateSha256!==i)throw new Error("planning-memory-snapshot-raced");I=JSON.parse(JSON.stringify(b))}catch{}m[f]={id:h.id??f,title:h.title,...N?{createEpicPlanning:N}:{},...L?{createEpicPlanningPhysical:L}:{},...P?{createEpicPlanningResearchPhysical:P}:{},...M?{createEpicPlanningGenerationPhysical:M}:{},...I?{createEpicPlanningMemoryPhysical:I}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:Dr(h.depends_on),...ln(h.branch_mode)?{branch_mode:ln(h.branch_mode)}:{},...Ce(h.execution_branch)?{execution_branch:Ce(h.execution_branch)}:{},...Ce(h.origin_branch)?{origin_branch:Ce(h.origin_branch)}:{},...Mr(h.branch_lease)?{branch_lease:Mr(h.branch_lease)}:{},...$r(h.origin_binding)?{origin_binding:$r(h.origin_binding)}:{},...Wr(h.aggregate_qa_receipt)?{aggregate_qa_receipt:Wr(h.aggregate_qa_receipt)}:{},...lt(h.pr_number)?{pr_number:lt(h.pr_number)}:{},...ne(h.physicalMergeStatus)?{physicalMergeStatus:ne(h.physicalMergeStatus)}:{},...x(h.graph_revision)?{graph_revision:x(h.graph_revision)}:{},...Gr(h.terminal_git_receipt)?{terminal_git_receipt:Gr(h.terminal_git_receipt)}:{},...C?{lifecycle_classification:C}:{}}}const S=oo(r.current_session??r.currentSession),_=u(r.archPlan)?pn(r.archPlan.execution):void 0,l=r.epic_id_ledger,v=Array.isArray(l?.reserved_ids)?[...new Set(l.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:s,epics:m,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...S?{current_session:S}:{},..._?{archPlan:{execution:_}}:{}}}const Vn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Un="6a41a47ff2521f80c2296ed811b0f0b304c54750",Bn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",qr="30dccfff07f9c969be11ae1d28e62a09731a0768";function po(e,t){try{const a=t.indexOf(qr);if(a<1||t[a-1]!==Un)return new Map;const r=je("git",["show","--no-patch","--format=%P",qr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=je("git",["show","--no-patch","--format=%P",Bn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Un} ${Bn}`||i!==`${Vn.at(-1)[1]} ${Un}`)return new Map;const n=je("git",["rev-list","--first-parent","--reverse",Bn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
- `),o=new Map;let s=-1;for(const[p,[m,S]]of Vn.entries()){const _=n.indexOf(S);if(_<=s)return new Map;s=_,o.set(m,{headSha:S,position:p-Vn.length})}return o}catch{return new Map}}async function uo(e,t,a){if(!Hr(a))return{};if(Va(t,a))return{};try{const r=JSON.parse(Ve(X(e,".neocortex","state.json"),"utf8")),i=on(e,{required:!0}),n=vr(r,i),o=u(n.stories)?n.stories:{},s=u(n.epics)?n.epics:{},p=je("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=je("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),S=je("git",["rev-list","--first-parent","--reverse",p],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
- `).filter(Boolean),_=new Map(S.map((I,b)=>[I,b])),l=po(e,S),v=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],f=a==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,C=Object.entries(o).flatMap(([I,b])=>{if(v&&I!==v)return[];const re=u(b)?b:void 0,w=u(re?.checkpoint)?re.checkpoint:void 0;if(!w)return[];const $=typeof re?.epic_id=="string"?re.epic_id:I.split(".")[0];if(f&&$!==f)return[];const W=x(w?.headSha),j=$==="P222"?l.get(I):void 0,V=_.get(W??"")??(j&&j.headSha===W?j.position:void 0);if(!W||W.length<40||V===void 0)return h.add($),[];const _e=u(s[$])?s[$]:void 0;if(_e?.branch_mode!=="epic"||Ce(_e.execution_branch)!==m||Ce(w.branch)!==m)return h.add($),[];const Y=x(w.graphRevision);if(!Y||Y.length!==64)return h.add($),[];const O=x(w.claimRevision),U=[...Cr(I,re,w)].sort(),at=wi(e,w,I,$,m,U);if(!at&&O){if(U.length===0)return h.add($),[];const Te=je("git",["diff-tree","--no-commit-id","--name-only","-r","-z",W],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let me=[];if(w.rootMemoryEffect!==void 0)try{me=_i(e,w.rootMemoryEffect,{storyId:I,executionBranch:m,baseSha:String(w.baseSha),headRef:W,childPaths:U}).files.map(z=>z.path)}catch{return h.add($),[]}if(Te.length===0||Te.some(z=>!U.some(oe=>oe===z||oe.endsWith("/")&&z.startsWith(oe))&&!me.includes(z)))return h.add($),[];const At=Ge("sha256").update(U.join("\0")).digest("hex"),it=Ge("sha256").update(JSON.stringify(U)).digest("hex");if(O!==At&&O!==it)return h.add($),[]}else if(!at)return h.add($),[];return Y?.length===64?[{storyId:I,epicId:$,graphRevision:Y,checkpointHead:W,position:V}]:[]}),N=new Set(h);for(const[I,b]of Object.entries(s)){const re=u(b)?b:void 0,w=Array.isArray(re?.stories)?re.stories.filter(V=>typeof V=="string"):Object.keys(o).filter(V=>V.startsWith(`${I}.`)),$=C.filter(V=>V.epicId===I),W=w.filter(V=>$.some(_e=>_e.storyId===V)),j=[...$].sort((V,_e)=>V.position-_e.position).map(V=>V.storyId);(JSON.stringify(W)!==JSON.stringify(j)||new Set(j).size!==j.length)&&N.add(I)}const L={},P=[...new Set(C.filter(I=>!N.has(I.epicId)).map(I=>I.graphRevision))],M=P.length>0?await Si(e,{headSha:p,graphRevisions:P}):new Map;for(const I of C){if(N.has(I.epicId))continue;const b=M.get(I.graphRevision);if(!b)throw new Error("p205-transient-authority-missing");L[I.storyId]=b}return L}catch(r){const i=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${i}. Checkpoint projection remains fail-closed.
11
- `),{}}}function vs(e,t){return{kind:"full",trigger:e,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(t.stories).length,includedEpicCount:Object.keys(t.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",projectionMode:"full-compatible"}}const zr="neocortex:menu:cache";async function lo(e){try{const t=await e.get(zr);if(!t)return null;const a=JSON.parse(t);return a.version!==Dt||Date.now()-a.cachedAt>_r?null:a}catch{return null}}async function ho(e,t,a){try{const r={instructions:t,metadata:a,cachedAt:Date.now(),version:Dt};await e.set(zr,JSON.stringify(r),_r),go()}catch{}}function go(){try{Ot(wr)&&Rn(wr)}catch{}}function fo(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>cr(),()=>cr({strictReadOnly:!0}))}async function Jr(e,t,a){const r=a.mode==="strict";try{let i;if(r&&t)i=new An({cacheDir:Tn,passphrase:t,strictReadOnly:!0});else if(r)i=new or;else if(t){const S=X(cn,"cache");i=new An({cacheDir:S,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
- `),i=new or;const n=yr(a,i,"auth-cache"),o=yr(a,i,"tier-cache"),s=new Ta({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let p;if(r){const S=await s.inspectToken();if(S.status!=="authenticated")return S;p=S.token}else p=await s.getToken();if(!p)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const m=new Pa({cacheProvider:o,licenseClient:s});return{status:"authenticated",token:p,client:s,tierClient:m}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Yr=!1;function mo(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const Kr=3,gn=50;function yo(e){return new Promise(t=>setTimeout(t,e))}function Eo(e,t,a){return e.status>=500&&e.status<=599?!0:a&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function qt(e,t,a,r,i={}){const n=Math.max(1,Math.min(i.maxAttempts??Kr,Kr)),o=i.sleep??yo;let s=r,p=!1,m=!1,S=0;for(let _=1;_<=n;_+=1){const l=Math.max(Math.floor(Date.now()/1e3),S+1);S=l;const v=Io(t,a,s,{nowSeconds:l}),f=new AbortController,h=setTimeout(()=>f.abort(),Rr);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:v.headers,body:v.body,signal:f.signal}),N=await C.text().catch(()=>""),L=(()=>{try{return N?JSON.parse(N):{}}catch{return{}}})();if(C.status===401&&!p&&i.refreshToken&&(L.fallback_action==="refresh_token"||L.fallback_action==="re_authenticate")){p=!0;const P=await i.refreshToken();if(P&&_<n){s=P,i.onTokenChanged?.(P),await o(gn*_);continue}}if(C.status===401&&L.error_code==="SIGNATURE_EXPIRED"&&!m&&_<n){m=!0,await o(gn*_);continue}if(_<n&&Eo(C,L,i.allowReplayRetry===!0)){await o(gn*_);continue}return{response:C,text:N,parsed:L,networkFailure:!1}}catch{if(_<n){await o(gn*_);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function Io(e,t,a,r={}){const i=Buffer.from(JSON.stringify(t),"utf8"),n=Za({method:"POST",target:e,body:i,bearerToken:a,clientVersion:Dt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${a}`}}}function Qr(e){return Ge("sha256").update(e).digest("hex")}function So(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function vo(e,t,a){return`args-${Ge("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(a)).digest("hex")}`}async function Xr(e,t,a,r,i={}){const n=await qt(e,t,a,r,{...i,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:s}=n;if(!o.ok){const p=typeof s.error_code=="string"?s.error_code:`HTTP_${o.status}`,m=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${p}: ${m}`)}return s}async function Co(e,t,a,r){const i=Buffer.from(t,"utf8"),n=So(),o=[];for(let f=0,h=0;f<i.byteLength;f+=n,h++){const C=i.subarray(f,Math.min(f+n,i.byteLength));o.push({index:h,sha256:Qr(C),byteLength:C.byteLength})}const s=Qr(i),p=vo(s,i.byteLength,o),m=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let S=a;const _={refreshToken:r,onTokenChanged(f){S=f}};for(const f of o){const h=f.index*n,C=i.subarray(h,h+f.byteLength);await Xr(e,"/api/v1/invoke/materialization/chunks",{manifestId:p,index:f.index,sha256:f.sha256,byteLength:f.byteLength,contentBase64:C.toString("base64"),ttlSeconds:m,idempotencyKey:`${p}:${f.index}:${f.sha256}`},S,_)}const v=(await Xr(e,"/api/v1/invoke/materialization/manifests",{manifestId:p,sha256:s,byteLength:i.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:m,retry:{attempt:1,budget:3,idempotencyKey:p}},S,_)).argsRef;if(!v?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:v,chunks:o}}function Vt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function wo(...e){const t=new Set,a=[];for(const r of e)for(const i of r??[]){const n=ne(i);if(!(!n||t.has(n))&&(t.add(n),a.push(n),a.length>=16))return a}return a}function _o(e){const t=e.graphRetrieval;if(!u(t))return{accepted:!1,itemCount:0};const a=Array.isArray(t.items)?t.items.length:0;return{accepted:a>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:a}}function $n(e,t=Vt(e),a=[],r={}){const i=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,s=i?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??br,warningThresholdBytes:r.warningThresholdBytes??Pn,scope:{kind:s,...i?.projectionMode?{projectionMode:i.projectionMode}:{},commandId:i?.commandId??null,stateProjectionPolicy:i?.stateProjectionPolicy??null},includedStories:i?.includedStoryCount??n,omittedStories:i?.omittedStoryCount??0,includedEpics:i?.includedEpicCount??o,omittedEpics:i?.omittedEpicCount??0,graphRetrieval:_o(e.stateSnapshot),reasonCodes:wo(a,i?.reasonCodes),publicSafe:!0}}function Ro(e){const t=u(e.budget)?e.budget:void 0,a=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(a,12*1024))}function Ao(e){return u(e)?{stableId:ne(e.stableId)??"unknown",...u(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Zr(e){const t=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function bo(e){const t=e.graphRetrieval;if(!u(t)||!Array.isArray(t.items))return e;const a=Ro(t);let r=[...t.items],i=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>a&&r.length>0;){const o=r.pop();i=[...i,Ao(o)].slice(-32),n={...t,items:r,skipped:i,warnings:Zr(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>a&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Zr(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function ea(e,t={}){const a=t.limitBytes??br,r=t.warningThresholdBytes??Math.floor(a*xr),i=Vt(e);if(i<a)return{body:e,degraded:!1,telemetry:$n(e,i,["payload-within-limit"],{limitBytes:a,warningThresholdBytes:r})};let n={...e,stateSnapshot:Ma(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],s=Vt(n);s>=a&&(n={...n,stateSnapshot:bo(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],s=Vt(n));const p=$n(n,s,o,{limitBytes:a,warningThresholdBytes:r});if(s>=a){const m=n.stateSnapshot.scope?.projectionMode;throw m==="yolo-story"||m==="yoloop-target"||m==="yoloop-session"||m==="yoloop-discovery"||m==="structural-required"?new Ln(p):new Dn(p)}return{body:n,degraded:!0,telemetry:p}}function ta(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function xo(e){const t=Vt(e);if(t<Pn)return t;const a=$n(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${ta(e)} scope=${a.scope.kind} mode=${a.scope.projectionMode??a.scope.kind} payloadBytes=${a.payloadBytes} limit=${a.limitBytes} includedStories=${a.includedStories} omittedStories=${a.omittedStories} includedEpics=${a.includedEpics} omittedEpics=${a.omittedEpics} graphRetrieval.accepted=${a.graphRetrieval.accepted} graphRetrieval.itemCount=${a.graphRetrieval.itemCount} reasonCodes=${a.reasonCodes.join(",")||"none"}
13
- `),t}function na(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${ta(e)} scope.kind=${t.scope.kind} payloadBytes=${t.payloadBytes} limit=${t.limitBytes} includedStories=${t.includedStories} omittedStories=${t.omittedStories} includedEpics=${t.includedEpics} omittedEpics=${t.omittedEpics} graphRetrieval.accepted=${t.graphRetrieval.accepted} graphRetrieval.itemCount=${t.graphRetrieval.itemCount} reasonCodes=${t.reasonCodes.join(",")||"none"}
14
- `)}async function To(e){const t=Ha(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Po(t),metadata:ra(t)};const a=e.bootstrapper??qa;let r;try{r=await a({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Fa.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=ra(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:i};const n=i.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...i,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:i,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Po(e){return!e.reasonCodes.includes(Ga.SKIPPED_NON_CONTINUITY_COMMAND)}function ra(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:ke([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function ke(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function fn(e,t,a){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(a,r)):t}function mn(e,t){const a=process.env[e];if(!a)return t;const r=Number(a);return Number.isFinite(r)?r:t}function q(e,t=Nr){const a=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=He(a,t),i=$i.test(r)?ut:r;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Wn(e,t=Nr){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function Gn(e,t,a,r){const i=Wn(e?.targetId??t,120),n=e?.selectorKind??(i?Fn(i):void 0),o=(e?.relatedJobIds??[]).map(s=>Wn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:a,...n?{targetKind:n}:{},...i?{targetId:i}:{},...t?{targetJobId:q(t,120)}:{},...e?.jobId?{jobId:q(e.jobId,120)}:{},...e?.goalId?{goalId:q(e.goalId,120)}:{},...e?.loopId?{loopId:q(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:ke(r.length>0?r:[F.OK]),publicSafe:!0}}function nt(e,t,a,r,i=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":a&&r===0?"empty":"available":"unavailable",s=Wn(t[t.length-1]?.eventId,120),p=i.length>0?i:o==="unavailable"?[F.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[F.WATCH_NO_SUMMARIES_YET]:[F.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:q(e.generatedAt,80)}:{},renderedSummaryCount:r,...s?{latestEventId:s}:{},reasonCodes:ke(p),publicSafe:!0}}function Je(e,t,a,r,i=[],n){const o=r[r.length-1],s=a??o?.cursor,p=!!(s&&s!==t&&r.length>0),m=n??(p?"advanced":t||s?"unchanged":"not_started"),S=i.length>0?i:m==="advanced"?[F.WATCH_CURSOR_ADVANCED]:m==="unavailable"?[F.WATCH_EVIDENCE_UNAVAILABLE]:[F.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:m,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...s?{nextCursor:q(s,200)}:{},cursorAdvanced:p,...o?.eventId?{eventId:q(o.eventId,120)}:{},reasonCodes:ke(S),publicSafe:!0}}function Ye(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:ke([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function ko(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",a=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,i=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",p=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":a===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${a}`,`snapshot=${s}`,`generatedAt=${p}`,`cursor=${i}`,`current=${q(n,200)}`,`next=${q(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function Ke(e,t,a,r=!1){if(r){const i={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};a.write(t==="json"?`${JSON.stringify(i)}
7
+ `)}catch{}}}function Ps(){Vn=!1}function Ur(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ro(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const ao=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),io=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function oo(e,t){if(!(!l(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const r=JSON.stringify(e);if(Buffer.byteLength(r)>16384||io.test(r))return;const a=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!l(e.intake)||Object.keys(e.intake).some(n=>!ao.has(n)))return;for(const[n,o]of Object.entries(e.intake))if(["examples","contracts"].includes(n)){const s=n==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(o)||o.length>16)return;for(const u of o)if(!l(u)||(a(u,s),Object.values(u).some(g=>typeof g!="string"||g.length>256)))return}else if(Array.isArray(o)){if(o.length>32||o.some(s=>typeof s!="string"||s.length>256))return}else if(typeof o=="string"){if(o.length>(n==="rawIntent"?Na:512))return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const i=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!l(n)||(a(n,i),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!l(e.degradeAuthorization))return;a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const n of["reasonCodes","assumptionCodes"]){const o=e.degradeAuthorization[n];if(!Array.isArray(o)||o.length>32||o.some(s=>typeof s!="string"||s.length>128))return}}return JSON.parse(r)}catch{return}}function Br(e){return e==="create-epic"||e==="discovered"?e:void 0}function Be(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function co(e){const t={};let r=!1;for(const a of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[a]===void 0)continue;const i=e[a];if(!Array.isArray(i)||i.length>128||i.some(n=>on(n)===void 0)){r=!0;continue}t[a]=i.map(n=>on(n))}if(e.planning!==void 0)try{if(!l(e.planning))throw new Error("planning-shape");const a=e.planning;for(const o of["claims","semanticArtifacts"]){if(a[o]===void 0)continue;const s=a[o];if(!Array.isArray(s)||s.length>128||s.some(u=>!l(u)||on(u.ref)===void 0))throw new Error("planning-refs")}if(a.attempts!==void 0&&(!Array.isArray(a.attempts)||a.attempts.length>32))throw new Error("planning-attempts");for(const o of a.attempts??[]){if(!l(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(s=>!l(s)||on(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...n}=Ci(a);t.planning=n}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function l(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ee(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function K(e){if(typeof e!="string")return;const t=e.trim(),r=ee(e);return r===t?r:void 0}function _e(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(r=>!r||r.startsWith(".")||r.endsWith(".lock")))return t}function A(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function $e(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function mt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function un(e){if(!l(e))return;const t=h=>typeof h=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(h),r=h=>typeof h=="string"&&/^[a-f0-9]{64}$/.test(h),a=(h,v)=>Array.isArray(h)&&h.length<=v&&h.every(t)&&new Set(h).size===h.length?h:void 0,i=(h,v)=>{if(!(!l(h)||h.schemaVersion!==2||!t(h.requestId)||!t(h.stageCommand)||!r(h.requestHash)||!r(h.inputHash)||!r(h.stateHash)||!r(h.nonce)||!r(h.stageRevision)||!r(h.stageHash)||!r(h.catalogHash)||h.targetEpicId!==void 0&&!t(h.targetEpicId)||v&&(!r(h.outputHash)||!r(h.artifactHash))))return{schemaVersion:2,...h.targetEpicId?{targetEpicId:h.targetEpicId}:{},requestId:h.requestId,requestHash:h.requestHash,inputHash:h.inputHash,stateHash:h.stateHash,nonce:h.nonce,stageCommand:h.stageCommand,stageRevision:h.stageRevision,stageHash:h.stageHash,catalogHash:h.catalogHash,...v?{outputHash:h.outputHash,artifactHash:h.artifactHash}:{}}},n=(h,v)=>{if(!(!l(h)||h.schemaVersion!=="1.1"||h.kind!==v||!r(h.receiptId)||!r(h.graphHash)||!r(h.evidenceHash)||!t(h.elementId)||!t(h.caseId)||!t(h.category)))return{schemaVersion:"1.1",kind:v,receiptId:h.receiptId,graphHash:h.graphHash,elementId:h.elementId,caseId:h.caseId,category:h.category,evidenceHash:h.evidenceHash}},o=(h,v)=>{if(!l(h)||h.kind!==v||!r(h.receiptId)||!a(h.evidenceIds,24)||v==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(h.status))||v==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(h.status)))return;const y=i(h,!0);if(!y)return;const p=v==="architecture-stage-validation"?n(h.isolated,"isolated"):void 0,C=v==="architecture-stage-validation"?n(h.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!p||!C)))return{...y,kind:v,receiptId:h.receiptId,status:h.status,evidenceIds:h.evidenceIds,...p&&C?{isolated:p,regression:C}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const u=a(e.questionIds,16);if(u&&(s.questionIds=u),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),r(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const h=rr(e.nonUiScopeReceipt);if(!h||h.targetEpicId!==e.targetEpicId||h.graphRevision!==e.graphRevision||!l(e.accounting)||h.accountingId!==e.accounting.accountingId||!l(e.evidenceExpectation)||h.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=h}l(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&r(e.pactAnswerReceipt.stateSha256)&&r(e.pactAnswerReceipt.answersSha256)&&E(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const g=i(e.evidenceExpectation,!1);g&&(s.evidenceExpectation=g);const S=o(e.completionEvidence,"architecture-stage-completion"),_=o(e.validationEvidence,"architecture-stage-validation");if(S&&(s.completionEvidence=S),_&&(s.validationEvidence=_),l(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&r(e.reviewDecision.graphRevision)&&r(e.reviewDecision.artifactHash)&&r(e.reviewDecision.completionReceiptId)&&r(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const h=a(e.reviewDecision.evidenceIds,24);h&&h.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:h})}if($t(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(l(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const h=a(e.terminalMemoryCheckpoint.evidenceIds,24);h&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:h})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const h=e.acceptedStages.map(v=>{if(!l(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const y=o(v.completionEvidence,"architecture-stage-completion"),p=o(v.validationEvidence,"architecture-stage-validation");return y&&p?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:y,validationEvidence:p}:void 0});h.every(v=>v!==void 0)&&(s.acceptedStages=h)}if(l(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const h=a(e.accounting.receiptIds,32);h&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:h,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function so(e){const t=l(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,r=l(t)?t.checkpoint:void 0,a=l(t)?t:void 0,i=l(r)?r:void 0,n=e.requestExecution,o=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&o.length===0&&a?.nextAction==="delegate",u=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&o.length===1&&l(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",g=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",S=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&o.length===2&&l(o[0])&&l(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&E(o[0],n.acceptedStages[0])&&E(o[1].completionEvidence,n.completionEvidence)&&E(o[1].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",_=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&o.length===2&&l(o[0])&&l(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",h=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&o.length===3&&l(o[0])&&l(o[1])&&l(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&E(o.slice(0,2),n.acceptedStages)&&E(o[2].completionEvidence,n.completionEvidence)&&E(o[2].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&o.length===3&&l(o[0])&&l(o[1])&&l(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",y=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],p=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&o.length===4&&l(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&E(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&E(o[3].completionEvidence,n.completionEvidence)&&E(o[3].validationEvidence,n.validationEvidence)&&E(i.questionIds,y)&&E(a?.questionIds,y)&&a?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,y)&&E(i.questionIds,[])&&E(i.pactAnswerReceipt,e.answerReceipt)&&E(a?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&a?.nextAction==="resume",k=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&l(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",V=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&l(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",I=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&l(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",Q=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&l(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",D=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",B=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&l(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",N=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&a?.nextAction==="blocked",ae=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&l(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",M=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",$=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&l(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",Pe=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",st=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&l(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",X=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",O=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(j=>l(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&l(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",q=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",dt=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&a?.nextAction==="ask-user",Ne=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&l(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&l(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&a?.nextAction==="resume",ve=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&l(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&a?.nextAction==="delegate",We=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&l(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&E(o[14].completionEvidence,n.completionEvidence)&&E(o[14].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&$t(i.terminalMemoryCheckpoint,n)!==null&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&a?.nextAction==="complete",He=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&$t(i.terminalMemoryCheckpoint,n)&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&a?.nextAction==="complete",Z=a?Ca(n,a,$t(n.terminalMemoryCheckpoint,n)&&E(i?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!l(t)||!l(r)||t.owner!=="root"||t.currentStageCommand!==r.currentStageCommand||t.continuationState!==r.continuationState||r.owner!=="root"||r.evidencePolicy!=="v2-required"||r.targetEpicId!==n.targetEpicId||r.graphRevision!==n.graphRevision||r.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(r.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(r.graphRevision))||!Array.isArray(r.acceptedStages)||!(Z||s||u||g||S||_||h||v||p||C||k||V||T||P||I||w||Q||D||B||N||ae||M||$||Pe||st||X||O||q||dt||Ne||ve||We||He)||!l(r.accounting)||r.accounting.charged!==!0||!E(un(r),r))throw new Error("architecture-root-checkpoint-invalid");const le=J(e.projectRoot,".neocortex"),ie=J(le,"state.json"),Et=J(le,"state.json.architecture.lock"),qe=Ht(Et,"wx",384);let Fe;try{const j=Lt(ie);if(!j.isFile()||j.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const oe=Ue(ie,"utf8");if(Ye("sha256").update(oe).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const z=JSON.parse(oe),ke=l(z)&&l(z.archPlan)?z.archPlan:{};if(!l(z)||!l(z.epics)||!Object.hasOwn(z.epics,r.targetEpicId)||(e.initialBinding?ke.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(un(ke.execution),n))||l(z.scope)&&z.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Gt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(He||Z==="complete-replay"){const Pt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,nr(n))};if(!E(n.terminalMemoryCheckpoint,An(e.projectRoot,Pt)))throw new Error("architecture-root-state-conflict");return}const ce=en(),It=Ve("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Ke=xa(It)?or(It):or(e.projectRoot,It);if(ba(Ke)!==Ke)throw new Error("architecture-root-backup-dir-invalid");const ye=J(Ke,"neocortex-architecture");Wt(ye,{recursive:!0,mode:448});const Y=Lt(ye);if(!Y.isDirectory()||Y.isSymbolicLink()||Y.uid!==process.getuid?.()||(Y.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const In=J(ye,`state-backup-${ce}.json`),x=Ht(In,"wx",384);try{tn(x,oe),nn(x)}finally{qt(x)}const St=Ht(ye,"r");try{nn(St)}finally{qt(St)}const f={...z,archPlan:{...ke,execution:r}};Fe=J(le,`state.json.architecture-tmp-${ce}`);const vt=Ht(Fe,"wx",384);try{tn(vt,`${JSON.stringify(f,null,2)}
8
+ `),nn(vt)}finally{qt(vt)}if((We||Z==="complete")&&!E(n.terminalMemoryCheckpoint,An(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Gt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");ir(Fe,ie),Fe=void 0;const he=Ht(le,"r");try{nn(he)}finally{qt(he)}}finally{if(Fe)try{bn(Fe)}catch{}qt(qe),bn(Et)}}function ln(e,t){if(!l(e))return;const r={};for(const a of t){const i=e[a];if(typeof i=="boolean")r[a]=i;else if(typeof i=="number"&&Number.isFinite(i))r[a]=i;else if(typeof i=="string"){const n=ee(i);n&&(r[a]=n)}}return Object.keys(r).length>0?r:void 0}function hn(e){return e==="epic"||e==="story"?e:void 0}function $r(e){if(!l(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),r=K(e.sessionId),a=K(e.idempotencyKey),i=$e(e.acquiredAt),n=$e(e.expiresAt);if(!(!t||!r||!a||!i||!n||Date.parse(n)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:a,acquiredAt:i,expiresAt:n}}function Gr(e){if(!l(e)||e.schemaVersion!==1)return;const t=K(e.storyId),r=K(e.epicId),a=_e(e.branch),i=A(e.baseSha),n=A(e.headSha),o=K(e.idempotencyKey),s=$e(e.recordedAt),u=Be(e.commits).map(A).filter(V=>!!V).slice(0,256),g=Be(e.receiptRefs).map(mt).filter(V=>!!V).slice(0,256),S=e.dispatchId===void 0?void 0:K(e.dispatchId),_=e.bundleId===void 0?void 0:K(e.bundleId),h=e.bundleDigest===void 0?void 0:A(e.bundleDigest),v=e.graphRevision===void 0?void 0:A(e.graphRevision),y=e.claimRevision===void 0?void 0:K(e.claimRevision),p=po(e.qaReceipt),C=uo(e.reviewReceipt),k=e.rootMemoryEffect===void 0?void 0:Pi(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!r||!t.startsWith(`${r}.`)||!a||!i||!n||i===n||!o||!s||u.length===0||g.length===0||!Array.isArray(e.commits)||u.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||g.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!S||e.bundleId!==void 0&&!_||e.bundleDigest!==void 0&&(!h||h.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!y||e.rootMemoryEffect!==void 0&&(!k||k.storyId!==t||k.epicId!==r||k.executionBranch!==a||k.sourceHeadSha!==i||k.childClaimRevision!==y)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!p||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||p.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!qr(p,{storyId:t,epicId:r,baseSha:i,headSha:n,bundleDigest:h,graphRevision:v})||C&&(!qr(C,{storyId:t,epicId:r,baseSha:i,headSha:n,bundleDigest:h,graphRevision:v})||C.qaReceiptRef!==p?.receiptRef||C.receiptRef===p?.receiptRef)||!g.includes(String(p.receiptRef))||C&&(!g.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(p.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:a,baseSha:i,headSha:n,idempotencyKey:o,...S?{dispatchId:S}:{},..._?{bundleId:_}:{},...h?{bundleDigest:h}:{},...v?{graphRevision:v}:{},...y?{claimRevision:y}:{},...k?{rootMemoryEffect:structuredClone(k)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...p?{qaReceipt:p}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:u,receiptRefs:g}}function po(e){if(!l(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=K(e.storyId),r=K(e.epicId),a=A(e.baseSha),i=A(e.headSha),n=A(e.bundleDigest),o=A(e.graphRevision),s=A(e.sourceEvidenceDigest),u=$e(e.checkedAt),g=mt(e.receiptRef),S=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,_=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,h=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,y=e.evidenceVersion==="p205-execution-v2"?Be(e.gateIds).map(K).filter(p=>!!p).slice(0,64):void 0;if(!(!t||!r||!a||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!g||e.evidenceVersion==="p205-execution-v2"&&(!S||_!=="node scripts/test-root.mjs --gate complete"||!h||h.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!y||y.length===0||y.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:r,...e.evidenceVersion==="p205-execution-v2"?{contract:S,command:_,manifestDigest:h,gateIds:y,resultDigest:v}:{},baseSha:a,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:g}}function Wr(e){if(!l(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=K(e.storyId),r=K(e.epicId),a=_e(e.branch),i=A(e.baseSha),n=A(e.headSha),o=A(e.aggregateHeadSha),s=A(e.commitBodyDigest),u=A(e.changedPathsDigest),g=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,S=A(e.effectiveClaimRevision),_=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,h=A(e.manifestDigest),v=Be(e.gateIds).map(K).filter(P=>!!P).slice(0,64),y=A(e.resultDigest),p=A(e.graphRevision),C=A(e.executionEvidenceDigest),k=A(e.sourceEvidenceDigest),V=$e(e.verifiedAt),T=Be(e.reasonCodes).map(K).filter(P=>!!P).slice(0,16);if(!(!t||!r||!a||!i||i.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!g||!S||S.length!==64||!_||!h||h.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!y||y.length!==64||!p||p.length!==64||!C||C.length!==64||!k||k.length!==64||!V||T.length===0||e.verdict==="verified"&&(v.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:r,branch:a,baseSha:i,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:u,claimVerification:g,effectiveClaimRevision:S,command:_,manifestDigest:h,gateIds:v,resultDigest:y,graphRevision:p,executionEvidenceDigest:C,sourceEvidenceDigest:k,verifiedAt:V,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function Hr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!l(e)||Object.keys(e).some(h=>!t.includes(h))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=K(e.storyId),a=K(e.epicId),i=_e(e.branch),n=A(e.baseSha),o=A(e.headSha),s=A(e.graphRevision),u=A(e.effectiveClaimRevision),g=A(e.sourceEvidenceDigest),S=$e(e.verifiedAt),_=Be(e.reasonCodes).map(K).filter(h=>!!h);if(!(!r||!a||!i||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!g||g.length!==64||!S||!Array.isArray(e.reasonCodes)||_.length!==1||_[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:a,branch:i,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:u,sourceEvidenceDigest:g,verifiedAt:S,reasonCodes:_,integrationAuthorized:!1,publicSafe:!0}}function uo(e){if(!l(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=K(e.storyId),r=K(e.epicId),a=A(e.baseSha),i=A(e.headSha),n=A(e.bundleDigest),o=A(e.graphRevision),s=A(e.sourceEvidenceDigest),u=mt(e.qaReceiptRef),g=$e(e.reviewedAt),S=mt(e.receiptRef);if(!(!t||!r||!a||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!g||!S))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:a,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:u,verdict:e.verdict,reviewedAt:g,receiptRef:S}}function qr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function Fr(e){if(!l(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=_e(e.originBranch),r=A(e.originHeadSha),a=_e(e.executionBranch),i=$e(e.capturedAt);if(!(!t||!r||r.length<40||!a||!i||t===a))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:a,capturedFromCurrentCheckout:!0,capturedAt:i}}function Yr(e){if(!l(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),r=A(e.graphRevision),a=$e(e.checkedAt),i=mt(e.receiptRef),n=Be(e.gateIds).map(K).filter(S=>!!S).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,u=o?A(e.manifestDigest):void 0,g=o?A(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!a||!i||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!u||u.length!==64||!g||g.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:u,resultDigest:g}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:a,receiptRef:i,gateIds:n}}function Un(e){if(!l(e)||e.schemaVersion!==1)return;const t=ln(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=Be(e.receiptRefs).map(mt).filter(i=>!!i).slice(0,256),a=Be(e.revertCommits).map(ee).filter(i=>!!i).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...a.length?{revertCommits:a}:{}}}function lo(e){if(!(!l(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function zr(e){if(!l(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=K(e.epicId),r=_e(e.executionBranch),a=_e(e.originBranch),i=A(e.baseSha),n=A(e.executionHeadSha),o=e.mergeSha===void 0?void 0:A(e.mergeSha),s=e.pushedSha===void 0?void 0:A(e.pushedSha),u=K(e.idempotencyKey),g=$e(e.attemptStartedAt),S=e.completedAt===void 0?void 0:$e(e.completedAt),_=Be(e.localGateReceiptRefs).map(mt).filter(p=>!!p).slice(0,256),h=Be(e.reasonCodes).map(K).filter(p=>!!p).slice(0,64),v=fo(e.candidateQa),y=ho(e.providerGuard);if(!(!t||!r||!a||!i||!n||!u||!g||_.length===0||h.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!y||y&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||y.prHeadSha!==o||y.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:a,baseSha:i,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...gt(e.prNumber)?{prNumber:gt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:_,idempotencyKey:u,attemptStartedAt:g,...v?{candidateQa:v}:{},...y?{providerGuard:y}:{},...S?{completedAt:S}:{},retryEligible:e.retryEligible,reasonCodes:h,publicSafe:!0}}function ho(e){if(!l(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),a=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),i=A(e.prHeadSha),n=A(e.originHeadSha),o=$e(e.checkedAt);if(!(!a||!i||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:i,originHeadSha:n,checkedAt:o,publicSafe:!0}}function fo(e){if(!l(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==bi)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,A(e[o])])),a=$e(e.checkedAt),i=mt(e.receiptRef),n=Be(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(r).some(o=>!o)||!a||!i||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:a,receiptRef:i,gateIds:n}}function go(e){if(!l(e))return;const t={...ee(e.active_epic_id??e.activeEpicId)?{active_epic_id:ee(e.active_epic_id??e.activeEpicId)}:{},...ee(e.active_story_id??e.activeStoryId)?{active_story_id:ee(e.active_story_id??e.activeStoryId)}:{},...ee(e.active_step_id??e.activeStepId)?{active_step_id:ee(e.active_step_id??e.activeStepId)}:{},...ee(e.session_id??e.sessionId)?{session_id:ee(e.session_id??e.sessionId)}:{},...ee(e.started_at??e.startedAt)?{started_at:ee(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function mo(e){const t=ln(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=ln(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),a=ln(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...ee(e.physicalMergeStatus)?{physicalMergeStatus:ee(e.physicalMergeStatus)}:{},...ee(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ee(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ee(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ee(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...gt(e.issue_number??e.issueNumber)?{issue_number:gt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...a?{scopedCiEvidence:a}:{}}}class it extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const yo=new Set(["yolo","yoloop","finalize-epic","audit"]);function Jr(e){return typeof e=="string"&&yo.has(e)}function Bn(e,t={}){const r=J(e,".neocortex","state.json");if(!Nt(r))throw new it("git-lifecycle-state-missing");let a;try{a=JSON.parse(Ue(r,"utf8"))}catch{throw new it("git-lifecycle-state-corrupt")}if(!l(a)||!l(a.epics)||!l(a.stories))throw new it("git-lifecycle-state-shape-invalid");const i=Object.values(a.epics).some(n=>l(n)&&(n.branch_mode==="epic"||_e(n.execution_branch)!==void 0));if(i)try{cn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new it(o)}return{lifecycleDeclared:i,runtimeMissing:!1}}function fn(e,t={}){const r=J(e,".neocortex","state.json");if(!Nt(r)){if(t.epicAware&&!t.projectless)throw new it("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let a,i;try{const y=Ue(r,"utf-8");i=Ye("sha256").update(y).digest("hex");const p=JSON.parse(y),C=l(p.epics)?p.epics:{},k=Object.values(C).some(w=>l(w)&&(w.branch_mode==="epic"||_e(w.execution_branch)!==void 0)),V=cn(e,{required:!!(t.epicAware&&k&&!t.projectless)});a=Rr(p,V);const T=l(a.stories)?a.stories:{},P=l(a.epics)?a.epics:{},I=l(p.stories)?p.stories:{};for(const[w,Q]of Object.entries(T)){const D=l(Q)?Q:void 0;if(!D?.checkpoint)continue;const B=typeof D.epic_id=="string"?D.epic_id:w.split(".")[0],N=l(P[B])?P[B]:void 0,ae=_e(N?.execution_branch);if(!ae)continue;const M=wi(e,D.checkpoint,w,B,ae,t.p205Authorities?.[w],Ar(w,D,l(D.checkpoint)?D.checkpoint:void 0));if(M.kind==="integration-authorized")D.checkpoint_verification=M.verification,delete D.scheduling_checkpoint_evidence;else if(M.kind==="scheduling-only")D.scheduling_checkpoint_evidence=M.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(M.kind==="rejected"){D.checkpoint_verification=M.verification,delete D.scheduling_checkpoint_evidence;const $=l(I[w])?I[w]:void 0;if(delete D.checkpoint,V.stories[w]?.checkpoint!==void 0)for(const Pe of["status","last_step","steps_completed"])$&&Object.prototype.hasOwnProperty.call($,Pe)?D[Pe]=structuredClone($[Pe]):delete D[Pe];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(y){if(t.epicAware&&!t.projectless){const p=y instanceof Error&&/^git-lifecycle-/.test(y.message)?y.message:"git-lifecycle-state-corrupt";throw new it(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const y=to(a);y.length>0&&no(y)}catch{}const n=a.config??a.project??{},o=a.stories??{},s={};for(const[y,p]of Object.entries(o)){const C=l(p.review_request)&&p.review_request.kind==="git-pull-request"?lo(p.review_request):Un(p.review_request);s[y]={id:p.id??y,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",...Br(p.source)?{source:Br(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...hn(p.branch_mode)?{branch_mode:hn(p.branch_mode)}:{},...Gr(p.checkpoint)?{checkpoint:Gr(p.checkpoint)}:{},...Wr(p.checkpoint_verification)?{checkpoint_verification:Wr(p.checkpoint_verification)}:{},...Hr(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Hr(p.scheduling_checkpoint_evidence)}:{},...C?{review_request:C}:{},...Un(p.rollback_receipt)?{rollback_receipt:Un(p.rollback_receipt)}:{},...gt(p.workflow_issue)?{workflow_issue:gt(p.workflow_issue)}:{},...mo(p),depends_on:Ur(p.depends_on),files_to_modify:Be(p.files_to_modify),...co(p),risk:typeof p.risk=="string"?p.risk:void 0,blast_radius:typeof p.blast_radius=="number"?p.blast_radius:void 0}}const u=a.epics??{},g={};for(const[y,p]of Object.entries(u)){const C=ro(p.lifecycle_classification),k=oo(p.createEpicPlanning,y);let V,T,P,I;if(k&&l(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&l(p.createEpicPlanningPhysical))try{cr(a,p.createEpicPlanningClaim.claimId,y,!0),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(V&&l(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&l(p.createEpicPlanningResearchPhysical))try{sr(a,p.createEpicPlanningClaim.claimId,y),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&k&&p.status==="generated"&&l(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&l(p.createEpicPlanningGenerationPhysical))try{if(Oa(e,p.createEpicPlanningClaim.claimId,y).stateSha256!==i)throw new Error("planning-generation-snapshot-raced");P=JSON.parse(JSON.stringify(p.createEpicPlanningGenerationPhysical)),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical)),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(P&&l(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string")try{const w=dr(e,p.createEpicPlanningClaim.claimId,y);if(w.stateSha256!==i)throw new Error("planning-memory-snapshot-raced");I=JSON.parse(JSON.stringify(w))}catch{}g[y]={id:p.id??y,title:p.title,...k?{createEpicPlanning:k}:{},...V?{createEpicPlanningPhysical:V}:{},...T?{createEpicPlanningResearchPhysical:T}:{},...P?{createEpicPlanningGenerationPhysical:P}:{},...I?{createEpicPlanningMemoryPhysical:I}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:Ur(p.depends_on),...hn(p.branch_mode)?{branch_mode:hn(p.branch_mode)}:{},..._e(p.execution_branch)?{execution_branch:_e(p.execution_branch)}:{},..._e(p.origin_branch)?{origin_branch:_e(p.origin_branch)}:{},...$r(p.branch_lease)?{branch_lease:$r(p.branch_lease)}:{},...Fr(p.origin_binding)?{origin_binding:Fr(p.origin_binding)}:{},...Yr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Yr(p.aggregate_qa_receipt)}:{},...gt(p.pr_number)?{pr_number:gt(p.pr_number)}:{},...ee(p.physicalMergeStatus)?{physicalMergeStatus:ee(p.physicalMergeStatus)}:{},...A(p.graph_revision)?{graph_revision:A(p.graph_revision)}:{},...zr(p.terminal_git_receipt)?{terminal_git_receipt:zr(p.terminal_git_receipt)}:{},...C?{lifecycle_classification:C}:{}}}const S=go(a.current_session??a.currentSession),_=l(a.archPlan)?un(a.archPlan.execution):void 0,h=a.epic_id_ledger,v=Array.isArray(h?.reserved_ids)?[...new Set(h.reserved_ids.filter(y=>typeof y=="string"&&/^P\d+$/.test(y)))].slice(0,2048):[];return{schema_version:typeof a.schema_version=="number"?a.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:s,epics:g,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...S?{current_session:S}:{},..._?{archPlan:{execution:_}}:{}}}const $n=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Gn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Wn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",Kr="30dccfff07f9c969be11ae1d28e62a09731a0768";function Eo(e,t){try{const r=t.indexOf(Kr);if(r<1||t[r-1]!==Gn)return new Map;const a=Ve("git",["show","--no-patch","--format=%P",Kr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=Ve("git",["show","--no-patch","--format=%P",Wn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(a!==`${Gn} ${Wn}`||i!==`${$n.at(-1)[1]} ${Gn}`)return new Map;const n=Ve("git",["rev-list","--first-parent","--reverse",Wn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
+ `),o=new Map;let s=-1;for(const[u,[g,S]]of $n.entries()){const _=n.indexOf(S);if(_<=s)return new Map;s=_,o.set(g,{headSha:S,position:u-$n.length})}return o}catch{return new Map}}async function Io(e,t,r){if(!Jr(r))return{};if(gr(t,r))return{};try{const a=JSON.parse(Ue(J(e,".neocortex","state.json"),"utf8")),i=cn(e,{required:!0}),n=Rr(a,i),o=l(n.stories)?n.stories:{},s=l(n.epics)?n.epics:{},u=Ve("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=Ve("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),S=Ve("git",["rev-list","--first-parent","--reverse",u],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
+ `).filter(Boolean),_=new Map(S.map((I,w)=>[I,w])),h=Eo(e,S),v=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],y=r==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,p=new Set,C=Object.entries(o).flatMap(([I,w])=>{if(v&&I!==v)return[];const Q=l(w)?w:void 0,D=l(Q?.checkpoint)?Q.checkpoint:void 0;if(!D)return[];const B=typeof Q?.epic_id=="string"?Q.epic_id:I.split(".")[0];if(y&&B!==y)return[];const N=A(D?.headSha),ae=B==="P222"?h.get(I):void 0,M=_.get(N??"")??(ae&&ae.headSha===N?ae.position:void 0);if(!N||N.length<40||M===void 0)return p.add(B),[];const $=l(s[B])?s[B]:void 0;if($?.branch_mode!=="epic"||_e($.execution_branch)!==g||_e(D.branch)!==g)return p.add(B),[];const Pe=A(D.graphRevision);if(!Pe||Pe.length!==64)return p.add(B),[];const st=A(D.claimRevision),X=[...Ar(I,Q,D)].sort(),O=xi(e,D,I,B,g,X);if(!O&&st){if(X.length===0)return p.add(B),[];const q=Ve("git",["diff-tree","--no-commit-id","--name-only","-r","-z",N],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let dt=[];if(D.rootMemoryEffect!==void 0)try{dt=Ti(e,D.rootMemoryEffect,{storyId:I,executionBranch:g,baseSha:String(D.baseSha),headRef:N,childPaths:X}).files.map(We=>We.path)}catch{return p.add(B),[]}if(q.length===0||q.some(We=>!X.some(He=>He===We||He.endsWith("/")&&We.startsWith(He))&&!dt.includes(We)))return p.add(B),[];const Ne=Ye("sha256").update(X.join("\0")).digest("hex"),ve=Ye("sha256").update(JSON.stringify(X)).digest("hex");if(st!==Ne&&st!==ve)return p.add(B),[]}else if(!O)return p.add(B),[];return Pe?.length===64?[{storyId:I,epicId:B,graphRevision:Pe,checkpointHead:N,position:M}]:[]}),k=new Set(p);for(const[I,w]of Object.entries(s)){const Q=l(w)?w:void 0,D=Array.isArray(Q?.stories)?Q.stories.filter(M=>typeof M=="string"):Object.keys(o).filter(M=>M.startsWith(`${I}.`)),B=C.filter(M=>M.epicId===I),N=D.filter(M=>B.some($=>$.storyId===M)),ae=[...B].sort((M,$)=>M.position-$.position).map(M=>M.storyId);(JSON.stringify(N)!==JSON.stringify(ae)||new Set(ae).size!==ae.length)&&k.add(I)}const V={},T=[...new Set(C.filter(I=>!k.has(I.epicId)).map(I=>I.graphRevision))],P=T.length>0?await Ri(e,{headSha:u,graphRevisions:T}):new Map;for(const I of C){if(k.has(I.epicId))continue;const w=P.get(I.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");V[I.storyId]=w}return V}catch(a){const i=a instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(a.message)?a.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${i}. Checkpoint projection remains fail-closed.
11
+ `),{}}}function ks(e,t){return{kind:"full",trigger:e,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(t.stories).length,includedEpicCount:Object.keys(t.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",projectionMode:"full-compatible"}}const Qr="neocortex:menu:cache";async function So(e){try{const t=await e.get(Qr);if(!t)return null;const r=JSON.parse(t);return r.version!==Dt||Date.now()-r.cachedAt>Tr?null:r}catch{return null}}async function vo(e,t,r){try{const a={instructions:t,metadata:r,cachedAt:Date.now(),version:Dt};await e.set(Qr,JSON.stringify(a),Tr),Co()}catch{}}function Co(){try{Nt(xr)&&bn(xr)}catch{}}function Xr(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Tn(),()=>Tn({strictReadOnly:!0}))}async function Zr(e,t,r){const a=r.mode==="strict";try{let i;if(a&&t)i=new xn({cacheDir:kn,passphrase:t,strictReadOnly:!0});else if(a)i=new pr;else if(t){const S=J(sn,"cache");i=new xn({cacheDir:S,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
+ `),i=new pr;const n=vr(r,i,"auth-cache"),o=vr(r,i,"tier-cache"),s=new La({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:a});let u;if(a){const S=await s.inspectToken();if(S.status!=="authenticated")return S;u=S.token}else u=await s.getToken();if(!u)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const g=new Da({cacheProvider:o,licenseClient:s});return{status:"authenticated",token:u,client:s,tierClient:g}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let ea=!1;function wo(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const ta=3,gn=50;function _o(e){return new Promise(t=>setTimeout(t,e))}function Ro(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Yt(e,t,r,a,i={}){const n=Math.max(1,Math.min(i.maxAttempts??ta,ta)),o=i.sleep??_o;let s=a,u=!1,g=!1,S=0;for(let _=1;_<=n;_+=1){const h=Math.max(Math.floor(Date.now()/1e3),S+1);S=h;const v=Ao(t,r,s,{nowSeconds:h}),y=new AbortController,p=setTimeout(()=>y.abort(),Pr);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:v.headers,body:v.body,signal:y.signal}),k=await C.text().catch(()=>""),V=(()=>{try{return k?JSON.parse(k):{}}catch{return{}}})();if(C.status===401&&!u&&i.refreshToken&&(V.fallback_action==="refresh_token"||V.fallback_action==="re_authenticate")){u=!0;const T=await i.refreshToken();if(T&&_<n){s=T,i.onTokenChanged?.(T),await o(gn*_);continue}}if(C.status===401&&V.error_code==="SIGNATURE_EXPIRED"&&!g&&_<n){g=!0,await o(gn*_);continue}if(_<n&&Ro(C,V,i.allowReplayRetry===!0)){await o(gn*_);continue}return{response:C,text:k,parsed:V,networkFailure:!1}}catch{if(_<n){await o(gn*_);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(p)}}return{text:"",parsed:{},networkFailure:!0}}function Ao(e,t,r,a={}){const i=Buffer.from(JSON.stringify(t),"utf8"),n=ri({method:"POST",target:e,body:i,bearerToken:r,clientVersion:Dt,nowSeconds:a.nowSeconds,nonceBytes:a.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${r}`}}}function na(e){return Ye("sha256").update(e).digest("hex")}function bo(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function xo(e,t,r){return`args-${Ye("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function ra(e,t,r,a,i={}){const n=await Yt(e,t,r,a,{...i,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:s}=n;if(!o.ok){const u=typeof s.error_code=="string"?s.error_code:`HTTP_${o.status}`,g=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${u}: ${g}`)}return s}async function To(e,t,r,a){const i=Buffer.from(t,"utf8"),n=bo(),o=[];for(let y=0,p=0;y<i.byteLength;y+=n,p++){const C=i.subarray(y,Math.min(y+n,i.byteLength));o.push({index:p,sha256:na(C),byteLength:C.byteLength})}const s=na(i),u=xo(s,i.byteLength,o),g=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let S=r;const _={refreshToken:a,onTokenChanged(y){S=y}};for(const y of o){const p=y.index*n,C=i.subarray(p,p+y.byteLength);await ra(e,"/api/v1/invoke/materialization/chunks",{manifestId:u,index:y.index,sha256:y.sha256,byteLength:y.byteLength,contentBase64:C.toString("base64"),ttlSeconds:g,idempotencyKey:`${u}:${y.index}:${y.sha256}`},S,_)}const v=(await ra(e,"/api/v1/invoke/materialization/manifests",{manifestId:u,sha256:s,byteLength:i.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:g,retry:{attempt:1,budget:3,idempotencyKey:u}},S,_)).argsRef;if(!v?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:v,chunks:o}}function Ut(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Po(...e){const t=new Set,r=[];for(const a of e)for(const i of a??[]){const n=ee(i);if(!(!n||t.has(n))&&(t.add(n),r.push(n),r.length>=16))return r}return r}function ko(e){const t=e.graphRetrieval;if(!l(t))return{accepted:!1,itemCount:0};const r=Array.isArray(t.items)?t.items.length:0;return{accepted:r>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:r}}function Hn(e,t=Ut(e),r=[],a={}){const i=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,s=i?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:a.limitBytes??Or,warningThresholdBytes:a.warningThresholdBytes??On,scope:{kind:s,...i?.projectionMode?{projectionMode:i.projectionMode}:{},commandId:i?.commandId??null,stateProjectionPolicy:i?.stateProjectionPolicy??null},includedStories:i?.includedStoryCount??n,omittedStories:i?.omittedStoryCount??0,includedEpics:i?.includedEpicCount??o,omittedEpics:i?.omittedEpicCount??0,graphRetrieval:ko(e.stateSnapshot),reasonCodes:Po(r,i?.reasonCodes),publicSafe:!0}}function Oo(e){const t=l(e.budget)?e.budget:void 0,r=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(r,12*1024))}function No(e){return l(e)?{stableId:ee(e.stableId)??"unknown",...l(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function aa(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Lo(e){const t=e.graphRetrieval;if(!l(t)||!Array.isArray(t.items))return e;const r=Oo(t);let a=[...t.items],i=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>r&&a.length>0;){const o=a.pop();i=[...i,No(o)].slice(-32),n={...t,items:a,skipped:i,warnings:aa(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>r&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:aa(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function ia(e,t={}){const r=t.limitBytes??Or,a=t.warningThresholdBytes??Math.floor(r*Nr),i=Ut(e);if(i<r)return{body:e,degraded:!1,telemetry:Hn(e,i,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:a})};let n={...e,stateSnapshot:$a(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],s=Ut(n);s>=r&&(n={...n,stateSnapshot:Lo(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],s=Ut(n));const u=Hn(n,s,o,{limitBytes:r,warningThresholdBytes:a});if(s>=r){const g=n.stateSnapshot.scope?.projectionMode;throw g==="yolo-story"||g==="yoloop-target"||g==="yoloop-session"||g==="yoloop-discovery"||g==="structural-required"?new jn(u):new Mn(u)}return{body:n,degraded:!0,telemetry:u}}function oa(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Do(e){const t=Ut(e);if(t<On)return t;const r=Hn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${oa(e)} scope=${r.scope.kind} mode=${r.scope.projectionMode??r.scope.kind} payloadBytes=${r.payloadBytes} limit=${r.limitBytes} includedStories=${r.includedStories} omittedStories=${r.omittedStories} includedEpics=${r.includedEpics} omittedEpics=${r.omittedEpics} graphRetrieval.accepted=${r.graphRetrieval.accepted} graphRetrieval.itemCount=${r.graphRetrieval.itemCount} reasonCodes=${r.reasonCodes.join(",")||"none"}
13
+ `),t}function ca(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${oa(e)} scope.kind=${t.scope.kind} payloadBytes=${t.payloadBytes} limit=${t.limitBytes} includedStories=${t.includedStories} omittedStories=${t.omittedStories} includedEpics=${t.includedEpics} omittedEpics=${t.omittedEpics} graphRetrieval.accepted=${t.graphRetrieval.accepted} graphRetrieval.itemCount=${t.graphRetrieval.itemCount} reasonCodes=${t.reasonCodes.join(",")||"none"}
14
+ `)}async function Mo(e){const t=za(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:jo(t),metadata:sa(t)};const r=e.bootstrapper??Ka;let a;try{a=await r({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{a={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Ja.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=sa(t,a);if(a.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:i};const n=i.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...i,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:i,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function jo(e){return!e.reasonCodes.includes(Ya.SKIPPED_NON_CONTINUITY_COMMAND)}function sa(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Oe([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Oe(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function mn(e,t,r){const a=Math.floor(e??t);return Number.isFinite(a)?Math.max(1,Math.min(r,a)):t}function yn(e,t){const r=process.env[e];if(!r)return t;const a=Number(r);return Number.isFinite(a)?a:t}function H(e,t=Vr){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",a=ze(r,t),i=Ji.test(a)?ft:a;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function qn(e,t=Vr){if(!(typeof e!="string"||e.trim().length===0))return H(e,t)}function Fn(e,t,r,a){const i=qn(e?.targetId??t,120),n=e?.selectorKind??(i?zn(i):void 0),o=(e?.relatedJobIds??[]).map(s=>qn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...n?{targetKind:n}:{},...i?{targetId:i}:{},...t?{targetJobId:H(t,120)}:{},...e?.jobId?{jobId:H(e.jobId,120)}:{},...e?.goalId?{goalId:H(e.goalId,120)}:{},...e?.loopId?{loopId:H(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:Oe(a.length>0?a:[W.OK]),publicSafe:!0}}function ot(e,t,r,a,i=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":r&&a===0?"empty":"available":"unavailable",s=qn(t[t.length-1]?.eventId,120),u=i.length>0?i:o==="unavailable"?[W.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[W.WATCH_NO_SUMMARIES_YET]:[W.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:H(e.generatedAt,80)}:{},renderedSummaryCount:a,...s?{latestEventId:s}:{},reasonCodes:Oe(u),publicSafe:!0}}function Ze(e,t,r,a,i=[],n){const o=a[a.length-1],s=r??o?.cursor,u=!!(s&&s!==t&&a.length>0),g=n??(u?"advanced":t||s?"unchanged":"not_started"),S=i.length>0?i:g==="advanced"?[W.WATCH_CURSOR_ADVANCED]:g==="unavailable"?[W.WATCH_EVIDENCE_UNAVAILABLE]:[W.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:g,...e?{initialCursor:H(e,200)}:{},...t?{currentCursor:H(t,200)}:{},...s?{nextCursor:H(s,200)}:{},cursorAdvanced:u,...o?.eventId?{eventId:H(o.eventId,120)}:{},reasonCodes:Oe(S),publicSafe:!0}}function et(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Oe([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:H(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Vo(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",r=e.snapshotEvidence?.renderedSummaryCount??0,a=e.targetEvidence?.relatedJobCount??0,i=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",u=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":r===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${a}`,`summaries=${r}`,`snapshot=${s}`,`generatedAt=${u}`,`cursor=${i}`,`current=${H(n,200)}`,`next=${H(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function tt(e,t,r,a=!1){if(a){const i={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};r.write(t==="json"?`${JSON.stringify(i)}
15
15
  `:`[watch-status] status=${i.watchStatus} active=${i.active} summaries=${i.renderedSummaryCount} stop=${i.stopReason}
16
- `);return}if(t==="json"){a.write(JSON.stringify(e)+`
17
- `);return}a.write(ko(e)+`
18
- `)}function Oo(e,t,a){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:a,statusRecord:e,publicSafe:!0}}}function rt(e,t,a,r,i=!1){return i?{status:e,summariesEmitted:t,polls:a,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:a,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:a,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:Oo(r,t,a),publicSafe:!0}}function No(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",a=e.goalId?` goal=${q(e.goalId,100)}`:"",r=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${a}${r} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function Do(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:q(e.eventId,120),jobId:q(e.jobId,100),...e.goalId?{goalId:q(e.goalId,100)}:{},...e.loopId?{loopId:q(e.loopId,100)}:{},executionId:q(e.executionId,120),...e.reasonCode?{reasonCode:q(e.reasonCode,80)}:{},createdAt:q(e.createdAt,80),publicSummary:q(e.publicSummary),publicSafe:!0}}function Lo(e,t,a,r=!1){if(r){a.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
16
+ `);return}if(t==="json"){r.write(JSON.stringify(e)+`
17
+ `);return}r.write(Vo(e)+`
18
+ `)}function Uo(e,t,r){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:r,statusRecord:e,publicSafe:!0}}}function ct(e,t,r,a,i=!1){return i?{status:e,summariesEmitted:t,polls:r,reasonCodes:[],watchStatus:a.watchStatus,stopReason:a.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:a.watchStatus,stopReason:a.stopReason??"not_stopped",summariesEmitted:t,polls:r,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:r,reasonCodes:a.reasonCodes,watchStatus:a.watchStatus,stopReason:a.stopReason,targetEvidence:a.targetEvidence,snapshotEvidence:a.snapshotEvidence,cursorEvidence:a.cursorEvidence,statusRecord:a,metadata:Uo(a,t,r),publicSafe:!0}}function Bo(e){const t=e.reasonCode?` reason=${H(e.reasonCode,80)}`:"",r=e.goalId?` goal=${H(e.goalId,100)}`:"",a=e.loopId?` loop=${H(e.loopId,100)}`:"";return`[watch] ${H(e.createdAt,80)} event=${H(e.eventId,120)} job=${H(e.jobId,100)}${r}${a} execution=${H(e.executionId,120)}${t} -- ${H(e.publicSummary)}`}function $o(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:H(e.eventId,120),jobId:H(e.jobId,100),...e.goalId?{goalId:H(e.goalId,100)}:{},...e.loopId?{loopId:H(e.loopId,100)}:{},executionId:H(e.executionId,120),...e.reasonCode?{reasonCode:H(e.reasonCode,80)}:{},createdAt:H(e.createdAt,80),publicSummary:H(e.publicSummary),publicSafe:!0}}function Go(e,t,r,a=!1){if(a){r.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
19
19
  `:`[watch] A local processing update is available.
20
- `);return}if(t==="json"){a.write(JSON.stringify(Do(e))+`
21
- `);return}a.write(No(e)+`
22
- `)}function Hn(e){return Ui.has(e.status)}function Mo(e,t,a){if(t){const i=e.find(n=>n.jobId===t);return!!(i&&Hn(i))}return a<=0?!1:e.filter(i=>!Hn(i)).length===0}function jo(e,t,a,r){return a<r?!1:t?!e.some(i=>i.jobId===t&&!Hn(i)):e.length===0}function Vo(e,t){return t?.aborted?Promise.resolve():new Promise(a=>{const r=setTimeout(i,e);function i(){clearTimeout(r),t?.removeEventListener("abort",i),a()}t?.addEventListener("abort",i,{once:!0})})}function Uo(e){return e.includes(Ae.MALFORMED)?"malformed":e.includes(Ae.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Ae.MISSING)||e.includes(Ie.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function aa(e,t){const a=t?zt(t):void 0,r=ke([...e,Ie.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),i=Gn(a,a?.targetId,Uo(r),r),n=nt({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Je(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return Ye({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Bo(e,t,a,r,i=!1){const n=aa(e,oa(t));return Ke(n,a,r,i),rt("target-unresolved",0,0,n,i)}async function $o(e){if(e.signal?.aborted){const M=Gn(e.target??zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Ie.CANCELLED]),I=nt(void 0,[],!1,0),b=Je(e.initialCursor,e.initialCursor,e.initialCursor,[],[Ie.CANCELLED],"unavailable"),re=Ye({watchStatus:"stopped",active:!1,targetEvidence:M,snapshotEvidence:I,cursorEvidence:b,stopReason:"cancelled",reasonCodes:[Ie.CANCELLED]});return rt("cancelled",0,0,re,e.protectedOutput)}const t=e.target??zt(e.targetJobId),a=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const M=aa([Ae.MISSING,Ie.TARGET_UNRESOLVED]);return Ke(M,e.format,r,e.protectedOutput),rt("target-unresolved",0,0,M,e.protectedOutput)}const i=fn(e.limit??mn("NEOCORTEX_INVOKE_WATCH_LIMIT",hr),hr,50),n=Math.max(50,fn(e.pollIntervalMs??mn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",mr),mr,6e4)),o=fn(e.maxIdlePolls??mn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",gr),gr,120),s=fn(e.maxPolls??mn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",fr),fr,86400),p=e.sleep??Vo;let m=e.initialCursor,S=0,_=0,l=0;const v=Gn(t,a,"resolved",[F.OK]),f={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},h=Je(e.initialCursor,m,m,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");Ke(Ye({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:f,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,r,e.protectedOutput);let C;try{C=await Ja({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const M=nt(void 0,[],!1,S,[F.WATCH_SNAPSHOT_UNAVAILABLE]),I=Je(e.initialCursor,m,m,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),b=Ye({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:M,cursorEvidence:I,stopReason:"unavailable_evidence",reasonCodes:[Ie.STORE_UNAVAILABLE]});return Ke(b,e.format,r,e.protectedOutput),rt("store-unavailable",S,l,b,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const M=m,I=C.collectProcessingOutputSummaryCursor({...m?{cursor:m}:{},...t?{target:t}:{},...a?{jobId:a}:{},limit:i}),b=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),re=b.jobs;if(I.summaries.length>0){for(const W of I.summaries)Lo(W,e.format,r,e.protectedOutput),S+=1;m=I.nextCursor??I.summaries[I.summaries.length-1]?.cursor??m,_=0}else m=I.nextCursor??m,_+=1;const w=nt(b,I.summaries,!0,I.summaries.length),$=Je(e.initialCursor,M,m,I.summaries,I.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(Ke(Ye({watchStatus:I.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:w,cursorEvidence:$,stopReason:"not_stopped",reasonCodes:I.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:b.generatedAt}),e.format,r,e.protectedOutput),!I.hasMore&&Mo(re,a,S)){const W=nt(b,I.summaries,!1,S,[Ie.COMPLETED]),j=Je(e.initialCursor,M,m,I.summaries,[Ie.COMPLETED],"exhausted"),V=Ye({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:W,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[Ie.COMPLETED],generatedAt:b.generatedAt});return Ke(V,e.format,r,e.protectedOutput),rt("completed",S,l,V,e.protectedOutput)}if(!I.hasMore&&jo(re,a,_,o)){const W=nt(b,I.summaries,!1,S,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),j=Je(e.initialCursor,M,m,I.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),V=Ye({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:W,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[Ie.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:b.generatedAt});return Ke(V,e.format,r,e.protectedOutput),rt("idle-timeout",S,l,V,e.protectedOutput)}I.hasMore||await p(n,e.signal)}}catch{const M=nt(void 0,[],!1,S,[F.WATCH_SNAPSHOT_UNAVAILABLE]),I=Je(e.initialCursor,m,m,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),b=Ye({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:M,cursorEvidence:I,stopReason:"unavailable_evidence",reasonCodes:[Ie.STORE_UNAVAILABLE]});return Ke(b,e.format,r,e.protectedOutput),rt("store-unavailable",S,l,b,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const M=nt(void 0,[],!1,S,[Ie.CANCELLED]),I=Je(e.initialCursor,m,m,[],[Ie.CANCELLED],"unavailable"),b=Ye({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:M,cursorEvidence:I,stopReason:"cancelled",reasonCodes:[Ie.CANCELLED]});return Ke(b,e.format,r,e.protectedOutput),rt("cancelled",S,l,b,e.protectedOutput)}const N=nt(void 0,[],!1,S,[F.WATCH_STOP_MAX_POLLS_REACHED]),L=Je(e.initialCursor,m,m,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=Ye({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:L,stopReason:"max_polls_reached",reasonCodes:[Ie.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return Ke(P,e.format,r,e.protectedOutput),rt("max-polls",S,l,P,e.protectedOutput)}function Fe(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const a=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(a==="job"&&r!=="J"||a==="goal"&&r!=="G"||a==="loop"&&r!=="L"))return`${a}-${r}${t[3]}`}function Fn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function ia(e){const t=[],a=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=a.exec(e))!==null;){const i=Fe(r[1]);i&&t.push(i)}return ke(t)}function oa(e){return ia(e)[0]}function zt(e){const t=e?Fe(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function qn(e){return ke(e.filter(t=>typeof t=="string").map(t=>Fe(t)).filter(t=>!!t?.startsWith("job-J")))}function Wo(e,t){const a=qn(t).filter(r=>r!==e.targetId&&r!==e.jobId);return a.length>0?{...e,relatedJobIds:a}:e}function Go(e){if(!e)return;const t=u(e.target)?e.target:void 0,a=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Fe(e.targetId):typeof t?.targetId=="string"?Fe(t.targetId):typeof e.targetJobId=="string"?Fe(e.targetJobId):void 0,i=zt(r);if(!i||a&&a!==i.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=qn([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==i.targetId&&s!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Fe(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Fe(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Fe(e.loopId??t?.loopId)??i.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function ca(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(a==="jobs"||a==="job"||a==="continuity-jobs"||a==="61")&&r==="watch"}const we=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Ho=new Set(["create","start","resume"]),Fo=new Set(["create","resume","run-once"]);function zn(e,t,a,r,i){return{schemaVersion:1,contractVersion:"continuity-v1",...a?{command:a}:{},...r?{operation:r}:{},active:e,...i?{watchToken:i}:{},reasonCodes:ke(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function be(e,t=[],a,r){const i=t.length>0?t:[we.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:zn(!1,i,a,r),publicSafe:!0}}function qo(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t.slice(2).filter(n=>n==="--watch").length;if(a===0)return be(e,[],"jobs","watch");if(a!==1)return be(e,[we.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return ca(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?be(e,[we.AMBIGUOUS],"jobs","watch"):oa(r)?{args:r,watch:!0,reasonCodes:[we.ACTIVE],metadata:zn(!0,[we.ACTIVE],"jobs","watch"),publicSafe:!0}:be(e,[we.TARGET_INVALID],"jobs","watch"):be(e,[we.UNSUPPORTED],"jobs","watch")}function zo(e){const t=[];let a=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const i=r;let n="",o=!1,s=null;for(;r<e.length;){const p=e[r];if(s){if(p===s){o=!0,s=null,r+=1;continue}if(p==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=p,r+=1;continue}if(/\s/.test(p))break;if(p==='"'||p==="'"){o=!0,s=p,r+=1;continue}n+=p,r+=1}s&&(a=!0),t.push({value:n,start:i,end:r,quoted:o})}return{tokens:t,malformed:a}}function Jo(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Yo(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const a=t.value.toLowerCase();return(e==="goal"?Ho:Fo).has(a)?a:void 0}function Ko(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Qo(e){const{tokens:t,malformed:a}=zo(e),r=Jo(t[0]),i=Yo(r,t[1]);if(a)return be(e,[we.MALFORMED],r,i);const n=t.filter(l=>l.value==="--watch"&&!l.quoted),o=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(Ko);if(!(n.length>0||o.length>0||s.length>0))return be(e,[],r,i);if(n.length>1)return be(e,[we.DUPLICATE],r,i);if(n.length===1&&(o.length>0||s.length>0))return be(e,[we.AMBIGUOUS],r,i);if(o.length>0)return be(e,[we.QUOTED],r,i);if(s.length>0)return be(e,[we.MALFORMED],r,i);const m=n[0];if(!m)return be(e,[],r,i);if(t[t.length-1]!==m)return be(e,[we.NON_FINAL],r,i);if(!r||!i)return be(e,[we.UNRESOLVED],r,i);const S=`${e.slice(0,m.start)}${e.slice(m.end)}`.trim(),_={literal:"--watch",position:"final",start:m.start,end:m.end,quoted:!1,publicSafe:!0};return{args:S,watch:!0,reasonCodes:[we.ACTIVE],metadata:zn(!0,[we.ACTIVE],r,i,_),publicSafe:!0}}function Xo(e){return ca(e)?qo(e):Qo(e)}function Zo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Bi.has(t)):[]}function Ut(e){return{disabled:!0,reasonCodes:ke(e.length>0?e:[Ae.MISSING])}}function Jn(e,t,a=[],r){const i=zt(t);if(i)return{source:e,target:Wo(i,a),targetJobId:i.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function ec(e){const t=new Map;for(const a of e){const r=`${a.target.selectorKind}:${a.target.targetId}`,i=t.get(r);if(!i){t.set(r,a);continue}const n=ke([...i.target.relatedJobIds??[],...a.target.relatedJobIds??[]]);t.set(r,{...i,target:n.length>0?{...i.target,relatedJobIds:n}:i.target,initialCursor:i.initialCursor??a.initialCursor})}return Array.from(t.values())}function ft(e,t,a,r){return{source:e,hasEvidence:t,candidates:ec(a.filter(i=>!!i)),...r&&r.length>0?{disabledReasonCodes:ke(r)}:{}}}function tc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Jt(e,t){const a=ke(e.filter(r=>typeof r=="string").map(r=>Fe(r)).filter(r=>!!r));if(t){const r=a.find(i=>Fn(i)===t);if(r)return r}return a[0]}function yn(e,t){return ke(e.filter(a=>typeof a=="string").map(a=>Fe(a)).filter(a=>!!a)).find(a=>Fn(a)===t)}function nc(e){const t=u(e?.continuity)?e.continuity:void 0,a=u(t?.jobs)?t.jobs:void 0,r=u(a?.watcher)?a.watcher:void 0,i=Zo(r?.reasonCodes??a?.reasonCodes);if(!r)return ft("watcher-metadata",i.length>0,[],i);if(r.active===!1||i.length>0)return ft("watcher-metadata",!0,[],i.length>0?i:[Ae.MALFORMED]);if(r.serverHeldStream!==!1)return ft("watcher-metadata",!0,[],[Ae.SERVER_HELD_STREAM]);const n=Go(r);if(!n)return ft("watcher-metadata",!0,[],[Ae.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return ft("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function sa(e,t){const a=u(e.loopJobPlan)?e.loopJobPlan:void 0,r=u(a?.metadata)?a.metadata:void 0,i=u(e.metadata)?e.metadata:void 0,o=(t==="goal"?Jt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Jt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,r?.loopId,r?.jobId],"loop"))??Jt([e.jobId,e.targetJobId,i?.jobId,r?.jobId]);return Jn("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,i?.jobId,r?.jobId])}function rc(e){const t=u(e?.continuity)?e.continuity:void 0,a=u(t?.goal)?t.goal:void 0,r=u(t?.loop)?t.loop:void 0,i=[a?sa(a,"goal"):void 0,r?sa(r,"loop"):void 0],n=!!(a||r);return ft("goal-loop-continuity-metadata",n,i,n&&i.every(o=>!o)?[Ae.MISSING]:void 0)}function ac(e){return Array.isArray(e)?e.filter(u):u(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(u):u(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function da(e,t){const a=u(t.metadata)?t.metadata:void 0,r=yn([t.goalId,t.targetGoalId,t.campaignId,a?.goalId,a?.campaignId,t.jobId,a?.jobId],"goal"),i=yn([t.loopId,t.targetLoopId,a?.loopId,t.jobId,a?.jobId],"loop"),n=Jt([t.jobId,t.targetJobId,a?.jobId],"job"),o=r??i??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...qn([n,t.jobId,t.targetJobId,a?.jobId])),e.set(o,s)}function ic(e){const t=u(e.metadata)?e.metadata:void 0;return!!(yn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??yn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function oc(e){const t=u(e.metadata)?e.metadata:void 0;return!!Jt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function pa(e,t){const a=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];u(s)&&a.push(s)}const r=u(t.event)?t.event:void 0;u(r?.metadata)&&a.push(r.metadata),u(r?.processingOutputSummary)&&a.push(r.processingOutputSummary);const i=u(t.receipt)?t.receipt:void 0;u(i?.metadata)&&a.push(i.metadata);const n=a.some(oc);for(const o of a)da(e,o);(!n||ic(t))&&da(e,t)}function cc(e){const t=ac(e?.continuityStateUpdate),a=new Map;for(const i of t){pa(a,i);const n=Array.isArray(i.operations)?i.operations.filter(u):[];for(const o of n)pa(a,o)}const r=Array.from(a.values()).map(i=>Jn("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return ft("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(i=>!i)?[Ae.MISSING]:void 0)}function sc(e){const t=ia(e);return ft("explicit-args",t.length>0,t.map(a=>Jn("explicit-args",a)))}function dc(e,t){const a=[nc(e),rc(e),cc(e),sc(t)];for(let r=0;r<a.length;r+=1){const i=a[r];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return Ut(i.disabledReasonCodes);if(i.candidates.length!==1)return Ut([i.candidates.length>1?Ae.AMBIGUOUS:Ae.MISSING]);const n=i.candidates[0];for(const o of a.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Ut(o.disabledReasonCodes);if(o.candidates.length>1)return Ut([Ae.AMBIGUOUS]);const s=o.candidates[0];if(s&&!tc(n,s))return Ut([Ae.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Ut([Ae.MISSING])}async function ua(e,t,a,r={}){const n=await qt(e,"/api/v1/invoke",t,a,t.privateExecution?{...r,maxAttempts:1,allowReplayRetry:!1}:r);if(n.networkFailure||!n.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:o,text:s,parsed:p}=n;try{if(!o.ok)return t.privateExecution?{ok:!1,status:o.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:o.status,error:Object.keys(p).length>0?`${p.error_code??"ERROR"}: ${p.message??s}`:`HTTP ${o.status}: ${s}`,errorBody:Object.keys(p).length>0?p:void 0};const m=p,S=o.headers.get("X-Client-Version-Warning");return S&&!Yr&&(Yr=!0,process.stderr.write(`
20
+ `);return}if(t==="json"){r.write(JSON.stringify($o(e))+`
21
+ `);return}r.write(Bo(e)+`
22
+ `)}function Yn(e){return Yi.has(e.status)}function Wo(e,t,r){if(t){const i=e.find(n=>n.jobId===t);return!!(i&&Yn(i))}return r<=0?!1:e.filter(i=>!Yn(i)).length===0}function Ho(e,t,r,a){return r<a?!1:t?!e.some(i=>i.jobId===t&&!Yn(i)):e.length===0}function qo(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const a=setTimeout(i,e);function i(){clearTimeout(a),t?.removeEventListener("abort",i),r()}t?.addEventListener("abort",i,{once:!0})})}function Fo(e){return e.includes(be.MALFORMED)?"malformed":e.includes(be.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(be.MISSING)||e.includes(Se.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function da(e,t){const r=t?zt(t):void 0,a=Oe([...e,Se.TARGET_UNRESOLVED,W.WATCH_TARGET_UNRESOLVED]),i=Fn(r,r?.targetId,Fo(a),a),n=ot({generatedAt:new Date().toISOString()},[],!1,0,[W.WATCH_TARGET_UNRESOLVED]),o=Ze(void 0,void 0,void 0,[],[W.WATCH_TARGET_UNRESOLVED],"unavailable");return et({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:a,generatedAt:n.generatedAt})}function Yo(e,t,r,a,i=!1){const n=da(e,ua(t));return tt(n,r,a,i),ct("target-unresolved",0,0,n,i)}async function zo(e){if(e.signal?.aborted){const P=Fn(e.target??zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Se.CANCELLED]),I=ot(void 0,[],!1,0),w=Ze(e.initialCursor,e.initialCursor,e.initialCursor,[],[Se.CANCELLED],"unavailable"),Q=et({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:I,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[Se.CANCELLED]});return ct("cancelled",0,0,Q,e.protectedOutput)}const t=e.target??zt(e.targetJobId),r=e.targetJobId??t?.targetId,a=e.stdout??process.stdout;if(!t){const P=da([be.MISSING,Se.TARGET_UNRESOLVED]);return tt(P,e.format,a,e.protectedOutput),ct("target-unresolved",0,0,P,e.protectedOutput)}const i=mn(e.limit??yn("NEOCORTEX_INVOKE_WATCH_LIMIT",yr),yr,50),n=Math.max(50,mn(e.pollIntervalMs??yn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Sr),Sr,6e4)),o=mn(e.maxIdlePolls??yn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Er),Er,120),s=mn(e.maxPolls??yn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Ir),Ir,86400),u=e.sleep??qo;let g=e.initialCursor,S=0,_=0,h=0;const v=Fn(t,r,"resolved",[W.OK]),y={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[W.WATCH_RENDER_PENDING],publicSafe:!0},p=Ze(e.initialCursor,g,g,[],e.initialCursor?[W.WATCH_CURSOR_UNCHANGED]:[W.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");tt(et({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:y,cursorEvidence:p,stopReason:"not_stopped",reasonCodes:[W.OK]}),e.format,a,e.protectedOutput);let C;try{C=await Xa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=ot(void 0,[],!1,S,[W.WATCH_SNAPSHOT_UNAVAILABLE]),I=Ze(e.initialCursor,g,g,[],[W.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:I,stopReason:"unavailable_evidence",reasonCodes:[Se.STORE_UNAVAILABLE]});return tt(w,e.format,a,e.protectedOutput),ct("store-unavailable",S,h,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&h<s;){h+=1;const P=g,I=C.collectProcessingOutputSummaryCursor({...g?{cursor:g}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:i}),w=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Q=w.jobs;if(I.summaries.length>0){for(const N of I.summaries)Go(N,e.format,a,e.protectedOutput),S+=1;g=I.nextCursor??I.summaries[I.summaries.length-1]?.cursor??g,_=0}else g=I.nextCursor??g,_+=1;const D=ot(w,I.summaries,!0,I.summaries.length),B=Ze(e.initialCursor,P,g,I.summaries,I.summaries.length>0?[W.WATCH_CURSOR_ADVANCED]:[W.WATCH_NO_SUMMARIES_YET]);if(tt(et({watchStatus:I.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:D,cursorEvidence:B,stopReason:"not_stopped",reasonCodes:I.summaries.length>0?[W.WATCH_CURSOR_ADVANCED]:[W.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,a,e.protectedOutput),!I.hasMore&&Wo(Q,r,S)){const N=ot(w,I.summaries,!1,S,[Se.COMPLETED]),ae=Ze(e.initialCursor,P,g,I.summaries,[Se.COMPLETED],"exhausted"),M=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[Se.COMPLETED],generatedAt:w.generatedAt});return tt(M,e.format,a,e.protectedOutput),ct("completed",S,h,M,e.protectedOutput)}if(!I.hasMore&&Ho(Q,r,_,o)){const N=ot(w,I.summaries,!1,S,[W.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=Ze(e.initialCursor,P,g,I.summaries,[W.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),M=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[Se.IDLE_TIMEOUT,W.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return tt(M,e.format,a,e.protectedOutput),ct("idle-timeout",S,h,M,e.protectedOutput)}I.hasMore||await u(n,e.signal)}}catch{const P=ot(void 0,[],!1,S,[W.WATCH_SNAPSHOT_UNAVAILABLE]),I=Ze(e.initialCursor,g,g,[],[W.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:I,stopReason:"unavailable_evidence",reasonCodes:[Se.STORE_UNAVAILABLE]});return tt(w,e.format,a,e.protectedOutput),ct("store-unavailable",S,h,w,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const P=ot(void 0,[],!1,S,[Se.CANCELLED]),I=Ze(e.initialCursor,g,g,[],[Se.CANCELLED],"unavailable"),w=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:I,stopReason:"cancelled",reasonCodes:[Se.CANCELLED]});return tt(w,e.format,a,e.protectedOutput),ct("cancelled",S,h,w,e.protectedOutput)}const k=ot(void 0,[],!1,S,[W.WATCH_STOP_MAX_POLLS_REACHED]),V=Ze(e.initialCursor,g,g,[],[W.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:V,stopReason:"max_polls_reached",reasonCodes:[Se.MAX_POLLS,W.WATCH_STOP_MAX_POLLS_REACHED]});return tt(T,e.format,a,e.protectedOutput),ct("max-polls",S,h,T,e.protectedOutput)}function Je(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),a=t[2].toUpperCase();if(!(r==="job"&&a!=="J"||r==="goal"&&a!=="G"||r==="loop"&&a!=="L"))return`${r}-${a}${t[3]}`}function zn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function pa(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let a;for(;(a=r.exec(e))!==null;){const i=Je(a[1]);i&&t.push(i)}return Oe(t)}function ua(e){return pa(e)[0]}function zt(e){const t=e?Je(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function Jn(e){return Oe(e.filter(t=>typeof t=="string").map(t=>Je(t)).filter(t=>!!t?.startsWith("job-J")))}function Jo(e,t){const r=Jn(t).filter(a=>a!==e.targetId&&a!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function Ko(e){if(!e)return;const t=l(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,a=typeof e.targetId=="string"?Je(e.targetId):typeof t?.targetId=="string"?Je(t.targetId):typeof e.targetJobId=="string"?Je(e.targetJobId):void 0,i=zt(a);if(!i||r&&r!==i.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=Jn([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==i.targetId&&s!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Je(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Je(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Je(e.loopId??t?.loopId)??i.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function la(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),a=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&a==="watch"}const Re=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Qo=new Set(["create","start","resume"]),Xo=new Set(["create","resume","run-once"]);function Kn(e,t,r,a,i){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...a?{operation:a}:{},active:e,...i?{watchToken:i}:{},reasonCodes:Oe(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function xe(e,t=[],r,a){const i=t.length>0?t:[Re.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:Kn(!1,i,r,a),publicSafe:!0}}function Zo(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(n=>n==="--watch").length;if(r===0)return xe(e,[],"jobs","watch");if(r!==1)return xe(e,[Re.AMBIGUOUS],"jobs","watch");const a=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return la(a)?a.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?xe(e,[Re.AMBIGUOUS],"jobs","watch"):ua(a)?{args:a,watch:!0,reasonCodes:[Re.ACTIVE],metadata:Kn(!0,[Re.ACTIVE],"jobs","watch"),publicSafe:!0}:xe(e,[Re.TARGET_INVALID],"jobs","watch"):xe(e,[Re.UNSUPPORTED],"jobs","watch")}function ec(e){const t=[];let r=!1,a=0;for(;a<e.length;){for(;a<e.length&&/\s/.test(e[a]);)a+=1;if(a>=e.length)break;const i=a;let n="",o=!1,s=null;for(;a<e.length;){const u=e[a];if(s){if(u===s){o=!0,s=null,a+=1;continue}if(u==="\\"&&a+1<e.length){n+=e[a+1],a+=2;continue}n+=u,a+=1;continue}if(/\s/.test(u))break;if(u==='"'||u==="'"){o=!0,s=u,a+=1;continue}n+=u,a+=1}s&&(r=!0),t.push({value:n,start:i,end:a,quoted:o})}return{tokens:t,malformed:r}}function tc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function nc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?Qo:Xo).has(r)?r:void 0}function rc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function ac(e){const{tokens:t,malformed:r}=ec(e),a=tc(t[0]),i=nc(a,t[1]);if(r)return xe(e,[Re.MALFORMED],a,i);const n=t.filter(h=>h.value==="--watch"&&!h.quoted),o=t.filter(h=>h.value==="--watch"&&h.quoted),s=t.filter(rc);if(!(n.length>0||o.length>0||s.length>0))return xe(e,[],a,i);if(n.length>1)return xe(e,[Re.DUPLICATE],a,i);if(n.length===1&&(o.length>0||s.length>0))return xe(e,[Re.AMBIGUOUS],a,i);if(o.length>0)return xe(e,[Re.QUOTED],a,i);if(s.length>0)return xe(e,[Re.MALFORMED],a,i);const g=n[0];if(!g)return xe(e,[],a,i);if(t[t.length-1]!==g)return xe(e,[Re.NON_FINAL],a,i);if(!a||!i)return xe(e,[Re.UNRESOLVED],a,i);const S=`${e.slice(0,g.start)}${e.slice(g.end)}`.trim(),_={literal:"--watch",position:"final",start:g.start,end:g.end,quoted:!1,publicSafe:!0};return{args:S,watch:!0,reasonCodes:[Re.ACTIVE],metadata:Kn(!0,[Re.ACTIVE],a,i,_),publicSafe:!0}}function ic(e){return la(e)?Zo(e):ac(e)}function oc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&zi.has(t)):[]}function Bt(e){return{disabled:!0,reasonCodes:Oe(e.length>0?e:[be.MISSING])}}function Qn(e,t,r=[],a){const i=zt(t);if(i)return{source:e,target:Jo(i,r),targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}}function cc(e){const t=new Map;for(const r of e){const a=`${r.target.selectorKind}:${r.target.targetId}`,i=t.get(a);if(!i){t.set(a,r);continue}const n=Oe([...i.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(a,{...i,target:n.length>0?{...i.target,relatedJobIds:n}:i.target,initialCursor:i.initialCursor??r.initialCursor})}return Array.from(t.values())}function yt(e,t,r,a){return{source:e,hasEvidence:t,candidates:cc(r.filter(i=>!!i)),...a&&a.length>0?{disabledReasonCodes:Oe(a)}:{}}}function sc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Jt(e,t){const r=Oe(e.filter(a=>typeof a=="string").map(a=>Je(a)).filter(a=>!!a));if(t){const a=r.find(i=>zn(i)===t);if(a)return a}return r[0]}function En(e,t){return Oe(e.filter(r=>typeof r=="string").map(r=>Je(r)).filter(r=>!!r)).find(r=>zn(r)===t)}function dc(e){const t=l(e?.continuity)?e.continuity:void 0,r=l(t?.jobs)?t.jobs:void 0,a=l(r?.watcher)?r.watcher:void 0,i=oc(a?.reasonCodes??r?.reasonCodes);if(!a)return yt("watcher-metadata",i.length>0,[],i);if(a.active===!1||i.length>0)return yt("watcher-metadata",!0,[],i.length>0?i:[be.MALFORMED]);if(a.serverHeldStream!==!1)return yt("watcher-metadata",!0,[],[be.SERVER_HELD_STREAM]);const n=Ko(a);if(!n)return yt("watcher-metadata",!0,[],[be.MISSING]);const o=typeof a.initialCursor=="string"?a.initialCursor:void 0;return yt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ha(e,t){const r=l(e.loopJobPlan)?e.loopJobPlan:void 0,a=l(r?.metadata)?r.metadata:void 0,i=l(e.metadata)?e.metadata:void 0,o=(t==="goal"?Jt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Jt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,a?.loopId,a?.jobId],"loop"))??Jt([e.jobId,e.targetJobId,i?.jobId,a?.jobId]);return Qn("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,i?.jobId,a?.jobId])}function pc(e){const t=l(e?.continuity)?e.continuity:void 0,r=l(t?.goal)?t.goal:void 0,a=l(t?.loop)?t.loop:void 0,i=[r?ha(r,"goal"):void 0,a?ha(a,"loop"):void 0],n=!!(r||a);return yt("goal-loop-continuity-metadata",n,i,n&&i.every(o=>!o)?[be.MISSING]:void 0)}function uc(e){return Array.isArray(e)?e.filter(l):l(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(l):l(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function fa(e,t){const r=l(t.metadata)?t.metadata:void 0,a=En([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),i=En([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),n=Jt([t.jobId,t.targetJobId,r?.jobId],"job"),o=a??i??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...Jn([n,t.jobId,t.targetJobId,r?.jobId])),e.set(o,s)}function lc(e){const t=l(e.metadata)?e.metadata:void 0;return!!(En([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??En([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function hc(e){const t=l(e.metadata)?e.metadata:void 0;return!!Jt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function ga(e,t){const r=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];l(s)&&r.push(s)}const a=l(t.event)?t.event:void 0;l(a?.metadata)&&r.push(a.metadata),l(a?.processingOutputSummary)&&r.push(a.processingOutputSummary);const i=l(t.receipt)?t.receipt:void 0;l(i?.metadata)&&r.push(i.metadata);const n=r.some(hc);for(const o of r)fa(e,o);(!n||lc(t))&&fa(e,t)}function fc(e){const t=uc(e?.continuityStateUpdate),r=new Map;for(const i of t){ga(r,i);const n=Array.isArray(i.operations)?i.operations.filter(l):[];for(const o of n)ga(r,o)}const a=Array.from(r.values()).map(i=>Qn("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return yt("continuity-state-update-operation-log",t.length>0,a,t.length>0&&a.every(i=>!i)?[be.MISSING]:void 0)}function gc(e){const t=pa(e);return yt("explicit-args",t.length>0,t.map(r=>Qn("explicit-args",r)))}function mc(e,t){const r=[dc(e),pc(e),fc(e),gc(t)];for(let a=0;a<r.length;a+=1){const i=r[a];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return Bt(i.disabledReasonCodes);if(i.candidates.length!==1)return Bt([i.candidates.length>1?be.AMBIGUOUS:be.MISSING]);const n=i.candidates[0];for(const o of r.slice(a+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Bt(o.disabledReasonCodes);if(o.candidates.length>1)return Bt([be.AMBIGUOUS]);const s=o.candidates[0];if(s&&!sc(n,s))return Bt([be.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Bt([be.MISSING])}async function ma(e,t,r,a={}){const n=await Yt(e,"/api/v1/invoke",t,r,t.privateExecution?{...a,maxAttempts:1,allowReplayRetry:!1}:a);if(n.networkFailure||!n.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:o,text:s,parsed:u}=n;try{if(!o.ok)return t.privateExecution?{ok:!1,status:o.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:o.status,error:Object.keys(u).length>0?`${u.error_code??"ERROR"}: ${u.message??s}`:`HTTP ${o.status}: ${s}`,errorBody:Object.keys(u).length>0?u:void 0};const g=u,S=o.headers.get("X-Client-Version-Warning");return S&&!ea&&(ea=!0,process.stderr.write(`
23
23
  [Neocortex] ${S}
24
24
 
25
- `)),{ok:!0,status:o.status,data:m}}catch(m){return{ok:!1,status:0,error:(m instanceof Error?m.message:String(m)).includes("abort")?`Request timeout after ${Rr/1e3}s`:"Network error: invalid response"}}}async function pc(e,t,a){const r=await qt(e,"/api/v1/invoke/private-execution/consume",t,a,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function uc(e,t,a){const r=await qt(e,"/api/v1/invoke/private-execution/cancel",t,a,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function la(e,t,a,r={}){const i=await qt(e,"/api/v1/invoke/epic-claims/acknowledge",{...a,registryVersion:wt,registryChecksum:Ct},t,r);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===a.status&&(!a.planningCheckpoint||i.parsed.memoryReceiptId===a.planningCheckpoint.memoryReceiptId)}async function lc(e,t,a,r,i,n={}){if(!i)return 0;const o=jt(e);let s=0;for(const[p,m]of Object.entries(o.operations))m.planningProtocol==="root-staged-v1"||!m.claimId||!m.epicId||!t.epics?.[m.epicId]||!await la(a,r,{claimId:m.claimId,projectId:i,epicId:m.epicId,status:"materialized"},n)||(Mi(e,p),s+=1);return s}function hc(e,t){const a=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||a?.length!==1||!r)return;const i=a[0],n=i.certificate,o=n?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof r.epicId=="string"?r.epicId:"",p=e.epics[s],m=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],S=m.length===1&&typeof m[0]?.storyId=="string"?m[0].storyId:"",l=e.stories[S]?.checkpoint;if(!p||p.branch_mode!=="epic"||typeof p.execution_branch!="string"||typeof p.origin_branch!="string"||p.branch_lease!==void 0&&p.branch_lease!==null||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const f=(Array.isArray(p.stories)?p.stories.filter(h=>typeof h=="string"):[]).find(h=>{const C=e.stories[h];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(L=>typeof L=="string"):[]).every(L=>["done","completed","merged"].includes(String(e.stories[L]?.status)))});if(f)return{epicId:s,expectedNextStoryId:f,branchMode:"epic",executionBranch:p.execution_branch,originBranch:p.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:l.storyId,epicId:l.epicId,branch:l.branch,baseSha:l.baseSha,headSha:l.headSha,receiptRefs:[...l.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function gc(e){let t;try{if(t=e.inputEnvelope??rn(e.inputSource??"args",e.args),ci(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const a=t.rawArgs,r=Sr(t);let i=a,n=r;const o=Vi(a);if(o.outcome!=="resolved"){const c=di(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...y?{invocationInput:y}:{}},exitCode:1}}if(e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=On(e.projectRoot),p=o.selection.commandId,m=p==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),S=ka.find(c=>c.id===p),_=S?.subcommands.find(c=>c.id===o.selection.operationId),l=_?_.policy.strictReadOnly==="allow":S?.policy.strictReadOnly==="allow",v=p==="diagnose";let f;try{f=ai({invocationId:en(),intent:e.strictReadOnly||v?{schemaVersion:1,policy:ti,registryVersion:wt,registryChecksum:Ct}:void 0,registryVersion:wt,registryChecksum:Ct,registryAllowsStrict:l,requestCanonicalBytes:JSON.stringify({command:p})})}catch(c){if(c instanceof Lt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{f.beginProjection();for(const c of Ir)f.project(c);for(const c of ni)f.project(c);f.seal()}const h=f.mode==="strict";if(p==="create-epic"||p==="idea-diagnose")try{const c=fi(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof xn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const C=e.environment??process.env;if(e.privateExecutionBeta&&(p!=="yolo"&&p!=="research"&&p!=="write-spec"&&p!=="create-tasks"&&p!=="implement"&&p!=="exec"&&p!=="create-epic"&&p!=="idea-diagnose"&&p!=="idea-research"&&p!=="generate-epic"&&p!=="sync-openapi"&&p!=="chaos-plan"&&p!=="ui-ux-review"&&p!=="arch-prd"&&p!=="arch-architecture"&&p!=="arch-fitness-functions"&&p!=="arch-api-contracts"&&p!=="arch-api-integrations"&&p!=="arch-database"&&p!=="arch-security"&&p!=="arch-design-system"&&p!=="arch-performance"&&p!=="arch-testing"&&p!=="arch-infrastructure"&&p!=="arch-review"&&p!=="update-memory"&&p!=="arch-ux-design"&&p!=="generate-pacts"&&p!=="property-test"&&!m||h||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const N=Xa({cwd:s,env:C,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),L=N.targetId,P=e.privateExecutionBeta?void 0:Qa({cwd:s,env:C,targetFlag:e.platformTarget,nativeHostVersion:qi(N,C)},N);p!=="migrate-project-id"&&f.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>ji(),()=>{});const M=fo(f),I=(e.serverUrl??M?.serverUrl??Na).replace(/\/+$/,"");if(p==="migrate-project-id"){const c=await mi(I);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let y;try{y=gi(s)}catch(B){const fe=B instanceof xn?B.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:fe,errorCode:fe,exitCode:1}}d.push(Mt({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const R=hn(s);if(R.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const G=await Jr(I,M?.licenseKey,f);if(G.status!=="authenticated"){const B=G.status==="refresh-required";return{success:!1,error:B?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:B?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:B?1:2}}let ue;try{ue=ur(e.args.trim(),R)}catch(B){const fe=B instanceof lr?B.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:fe,errorCode:fe,metadata:{invocationDiagnostics:d},exitCode:1}}let te={args:a,projectRoot:s.replace(Ft(),"~"),stateSnapshot:ue,platformTarget:L,...P?{nativeHostAttestation:P}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:r,idempotencyKey:y.document.operationId,registryVersion:wt,registryChecksum:Ct};try{te=ea(te).body}catch(B){if(B instanceof Dn||B instanceof Ln)return{success:!1,error:B.message,errorCode:B.code,metadata:{invokePayload:B.telemetry,invocationDiagnostics:d},exitCode:1};throw B}const de=await Er("invoke-query",()=>ua(I,te,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(!de.ok||!de.data)return d.push(Mt({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:He(de.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",_t),errorCode:typeof de.errorBody?.error_code=="string"?de.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:de.status===401?2:1};const le=de.data.metadata?.projectIdentityMigration;try{si(le),d.push(Mt({phase:"seed",outcome:le.status,floor:le.acceptedLegacyFloor,licenseId:"local-client",projectId:le.projectId})),li(s,le),d.push(Mt({phase:"remote-acknowledged",outcome:le.status,floor:le.acceptedLegacyFloor,licenseId:"local-client",projectId:le.projectId})),hi(s,le),d.push(Mt({phase:"finalize",outcome:"finalized",floor:le.acceptedLegacyFloor,licenseId:"local-client",projectId:le.projectId}))}catch(B){d.push(Mt({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const fe=B instanceof xn?B.code:B instanceof Error?B.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:fe,errorCode:fe,metadata:{invocationDiagnostics:d},exitCode:1}}return f.complete(),{success:!0,instructions:de.data.instructions,metadata:{...de.data.metadata,invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
25
+ `)),{ok:!0,status:o.status,data:g}}catch(g){return{ok:!1,status:0,error:(g instanceof Error?g.message:String(g)).includes("abort")?`Request timeout after ${Pr/1e3}s`:"Network error: invalid response"}}}async function yc(e,t,r){const a=await Yt(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(a.networkFailure||!a.response||!a.response.ok)throw new Error("private-execution-delivery-unavailable");return a.parsed}async function Ec(e,t,r){const a=await Yt(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!a.response?.ok&&a.parsed.status==="cancelled"}async function ya(e,t,r,a={}){const i=await Yt(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:bt,registryChecksum:At},t,a);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===r.status&&(!r.planningCheckpoint||i.parsed.memoryReceiptId===r.planningCheckpoint.memoryReceiptId)}async function Ic(e,t,r,a,i,n={}){if(!i)return 0;const o=Vt(e);let s=0;for(const[u,g]of Object.entries(o.operations))g.planningProtocol==="root-staged-v1"||!g.claimId||!g.epicId||!t.epics?.[g.epicId]||!await ya(r,a,{claimId:g.claimId,projectId:i,epicId:g.epicId,status:"materialized"},n)||(Hi(e,u),s+=1);return s}function Sc(e,t){const r=t.state.pendingContinuationAuthorities,a=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!a)return;const i=r[0],n=i.certificate,o=n?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof a.epicId=="string"?a.epicId:"",u=e.epics[s],g=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],S=g.length===1&&typeof g[0]?.storyId=="string"?g[0].storyId:"",h=e.stories[S]?.checkpoint;if(!u||u.branch_mode!=="epic"||typeof u.execution_branch!="string"||typeof u.origin_branch!="string"||u.branch_lease!==void 0&&u.branch_lease!==null||!h||h.qaVerdict!=="passed"||h.reviewVerdict!=="approved"||!Array.isArray(h.receiptRefs))return;const y=(Array.isArray(u.stories)?u.stories.filter(p=>typeof p=="string"):[]).find(p=>{const C=e.stories[p];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(V=>typeof V=="string"):[]).every(V=>["done","completed","merged"].includes(String(e.stories[V]?.status)))});if(y)return{epicId:s,expectedNextStoryId:y,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:h.storyId,epicId:h.epicId,branch:h.branch,baseSha:h.baseSha,headSha:h.headSha,receiptRefs:[...h.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function vc(e){let t;try{if(t=e.inputEnvelope??an(e.inputSource??"args",e.args),li(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const r=t.rawArgs,a=_r(t);let i=r,n=a;const o=Fi(r);if(o.outcome!=="resolved"){const c=fi(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}if(e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=Ln(e.projectRoot),u=o.selection.commandId,g=u==="yolo"&&!gr(r,u)?Oi(r):null,S=u==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),_=Ma.find(c=>c.id===u),h=_?.subcommands.find(c=>c.id===o.selection.operationId),v=h?h.policy.strictReadOnly==="allow":_?.policy.strictReadOnly==="allow",y=u==="diagnose";let p;try{p=di({invocationId:en(),intent:e.strictReadOnly||y?{schemaVersion:1,policy:oi,registryVersion:bt,registryChecksum:At}:void 0,registryVersion:bt,registryChecksum:At,registryAllowsStrict:v,requestCanonicalBytes:JSON.stringify({command:u})})}catch(c){if(c instanceof Mt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of wr)p.project(c);for(const c of ci)p.project(c);p.seal()}const C=p.mode==="strict";if(u==="create-epic"||u==="idea-diagnose")try{const c=Si(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof Pn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const k=e.environment??process.env;if(e.privateExecutionBeta&&(u!=="yolo"&&u!=="research"&&u!=="write-spec"&&u!=="create-tasks"&&u!=="implement"&&u!=="exec"&&u!=="create-epic"&&u!=="idea-diagnose"&&u!=="idea-research"&&u!=="generate-epic"&&u!=="sync-openapi"&&u!=="chaos-plan"&&u!=="ui-ux-review"&&u!=="arch-prd"&&u!=="arch-architecture"&&u!=="arch-fitness-functions"&&u!=="arch-api-contracts"&&u!=="arch-api-integrations"&&u!=="arch-database"&&u!=="arch-security"&&u!=="arch-design-system"&&u!=="arch-performance"&&u!=="arch-testing"&&u!=="arch-infrastructure"&&u!=="arch-review"&&u!=="update-memory"&&u!=="arch-ux-design"&&u!=="generate-pacts"&&u!=="property-test"&&!S||C||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const V=ni({cwd:s,env:k,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=V.targetId,P=e.privateExecutionBeta?void 0:ti({cwd:s,env:k,targetFlag:e.platformTarget,nativeHostVersion:eo(V,k)},V);if(g)try{Bn(s,{allowMissingRuntime:!0})}catch(c){const d=c instanceof it?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
26
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let I=g?Tn({strictReadOnly:!0}):Xr(p);const w=(e.serverUrl??I?.serverUrl??Va).replace(/\/+$/,"");let Q;if(g){const c=await ki(w);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${ai}; Local YOLO/TDD Release Gate was not executed and no invoke request was sent.`,errorCode:"YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE",metadata:{yoloInvokeEnvelopeCapability:c},exitCode:1};try{Q=br({projectRoot:s,storyId:g,epicId:g.split(".")[0],inputSha256:n.sha256,onOmittedReferences:d=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${d}; core story artifacts preserved.
27
+ `)})}catch(d){const m=d instanceof Error&&/^yolo-spec-envelope-[a-z-]+$/.test(d.message)?d.message:"yolo-spec-envelope-unsafe";return{success:!1,error:m,errorCode:m,exitCode:1}}I=Xr(p)}if(u!=="migrate-project-id"&&p.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>qi(),()=>{}),u==="migrate-project-id"){const c=await vi(w);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let m;try{m=Ii(s)}catch(U){const Ee=U instanceof Pn?U.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}d.push(jt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const b=fn(s);if(b.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const F=await Zr(w,I?.licenseKey,p);if(F.status!=="authenticated"){const U=F.status==="refresh-required";return{success:!1,error:U?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:U?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:U?1:2}}let fe;try{fe=fr(e.args.trim(),b)}catch(U){const Ee=U instanceof mr?U.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}let se={args:r,projectRoot:s.replace(Ft(),"~"),stateSnapshot:fe,platformTarget:T,...P?{nativeHostAttestation:P}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:a,idempotencyKey:m.document.operationId,registryVersion:bt,registryChecksum:At};try{se=ia(se).body}catch(U){if(U instanceof Mn||U instanceof jn)return{success:!1,error:U.message,errorCode:U.code,metadata:{invokePayload:U.telemetry,invocationDiagnostics:d},exitCode:1};throw U}const pe=await Cr("invoke-query",()=>ma(w,se,F.token,{refreshToken:()=>F.client.forceRefresh()}));if(!pe.ok||!pe.data)return d.push(jt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:ze(pe.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",xt),errorCode:typeof pe.errorBody?.error_code=="string"?pe.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:pe.status===401?2:1};const ge=pe.data.metadata?.projectIdentityMigration;try{hi(ge),d.push(jt({phase:"seed",outcome:ge.status,floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId})),yi(s,ge),d.push(jt({phase:"remote-acknowledged",outcome:ge.status,floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId})),Ei(s,ge),d.push(jt({phase:"finalize",outcome:"finalized",floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId}))}catch(U){d.push(jt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ee=U instanceof Pn?U.code:U instanceof Error?U.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}return p.complete(),{success:!0,instructions:pe.data.instructions,metadata:{...pe.data.metadata,invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
26
28
  `),{success:!1,error:d.message,exitCode:1};d.changed&&(e={...e,args:d.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${d.reasonCodes.join(",")}
27
29
  `))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
28
- `),{success:!1,error:c,exitCode:1}}const b=Hr(p);if(b)try{Fr(s,{allowMissingRuntime:!0}).runtimeMissing&&(await f.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Ii(s),async()=>{}),Fr(s))}catch(c){const d=c instanceof gt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state and retry.
29
- `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(p!=="migrate-state")try{f.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ua(s,{args:e.args,canonicalCommandId:p}),()=>{})}catch(c){if(c instanceof Ba)return process.stderr.write(`${c.message}
30
+ `),{success:!1,error:c,exitCode:1}}const D=Jr(u);if(D)try{Bn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>_i(s),async()=>{}),Bn(s))}catch(c){const d=c instanceof it?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state and retry.
31
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(u!=="migrate-state")try{p.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Wa(s,{args:e.args,canonicalCommandId:u}),()=>{})}catch(c){if(c instanceof Ha)return process.stderr.write(`${c.message}
30
32
  `),{success:!1,error:c.message,exitCode:1};const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${d}. No request was sent; inspect .neocortex/state.json and rerun.
31
- `),{success:!1,error:d,exitCode:1}}let re;if(e.privateExecutionBeta&&(p==="sync-openapi"||p==="chaos-plan"||p==="arch-prd"||p==="arch-architecture"||p==="arch-fitness-functions"||p==="arch-api-contracts"||p==="arch-api-integrations"||p==="arch-database"||p==="arch-security"||p==="arch-design-system"||p==="arch-performance"||p==="arch-testing"||p==="arch-infrastructure"||p==="arch-review"||p==="update-memory"||p==="arch-ux-design"||p==="generate-pacts"||p==="property-test"||m))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");re=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let w;try{const c=await uo(s,e.args,p);w=hn(s,{epicAware:b,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&p==="create-epic"})}catch(c){const d=c instanceof gt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
32
- `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),d={args:e.args,projectRoot:s,logger:{info:y=>process.stderr.write(`${y}
33
- `),warn:y=>process.stderr.write(`${y}
34
- `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},i=d.args,n=Sr(rn(t.source,i)))}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${d}. Proceeding with raw args.
35
- `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const y=hc(w,d);w.yoloop=y?{...d,continuationRecoveryEvidence:y}:d}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const y=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${y}. No yoloop request was sent and no state was mutated.
36
- `),{success:!1,error:y,errorCode:y,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),d=await c(e.args,s,void 0,f,{includeExistingStore:!v});d&&(w.continuity=d)}catch(c){if(c instanceof Lt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${d}. Proceeding without continuity state.
37
- `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:w,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:d=>{console.warn(d)},info:d=>{console.error(d)}}})}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${d}. Proceeding without enrichment.
38
- `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(w.architecture_policy=d)}catch(c){const d=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${d}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:d}=await import("../yoloop/invoke-hooks.js"),y=await d({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:R=>process.stderr.write(`${R}
39
- `)}});y.applied&&y.metadata&&(w.graphRetrieval=y.metadata)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${d}. Proceeding without enrichment.
40
- `)}try{if(Gi(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),d=o.selection.uiUxReview?.architectureDir,y=c({projectRoot:s,...d?{candidatePaths:[d],includeFallbackInventory:!0}:{}});(y.evidence.length>0||y.exclusions.length>0)&&(w.projectEvidence=y)}}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${d}. Proceeding without local project evidence.
41
- `)}try{const c=await f.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:d}=await import("../checkpoint/index.js");return d(s)},async()=>{});c&&(w.implementCheckpoint=c)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${d}. Proceeding without checkpoint.
42
- `)}const $=M?.licenseKey?new An({cacheDir:Tn,passphrase:M.licenseKey,strictReadOnly:h}):null,W=i.trim();if(!W&&$){const c=await f.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>lo($),async()=>null);if(c)return f.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const j=await Jr(I,M?.licenseKey,f);if(j.status!=="authenticated"){const c=j.status==="refresh-required",d=!c&&M&&!M.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const y=pr(),R=sr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",y);R&&process.stderr.write(dr(R,y))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${d} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const V=w.config.project_id;try{await f.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>lc(s,w,I,j.token,V,{refreshToken:()=>j.client.forceRefresh()}),async()=>0)}catch{}const _e=fc(W);if(_e&&!v)try{const c=await j.tierClient.preFlightCheck(_e);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
43
- `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const Y=await To({args:W,projectRoot:s,platformTarget:L,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:f});if(Y.attachToRequest&&(w.runnerBootstrap=Y.metadata),Y.warning&&process.stderr.write(`[Neocortex] ${Y.warning}
44
- `),!Y.shouldContinue)return Y.error&&process.stderr.write(`[Neocortex] ${Y.error}
45
- `),{success:!1,error:Y.error??"Runner auto-bootstrap required but failed.",errorCode:Y.errorCode,exitCode:Y.exitCode??1};if(Y.metadata.command==="runner"&&(Y.metadata.operation==="status"||Y.metadata.operation==="doctor"))try{const c=e.runnerObserver??za;w.runnerOperationalStatus=await c(Y.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:f})}catch{}let O;try{const c=ja(W,w);if(c&&!c.ok){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
46
- `),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??ur(W,w),bn(W)==="migrate-state"&&(O={...O,migrationAuthority:$a(s)})}catch(c){if(c instanceof Wa)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof lr){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
47
- `),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!h)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),y=d(s);if(Ot(y.databasePath)){const R=await c(s);try{const G=R.store.listRecentNativeAgentDispatches(20);G.length>0&&(O.nativeAgentDispatches=G)}finally{R.store.close()}}}catch{}const U=bn(W);let at=!1;if(U==="arch-plan"&&!h&&O.archPlan?.execution===void 0){const c=Ia(i);if(c)try{if(!Object.hasOwn(w.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=$t(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},at=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((U==="arch-plan"||U?.startsWith("arch-")||U==="generate-pacts"||U==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==$t(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Te=V;if((U==="create-epic"||U==="idea-diagnose")&&!Te){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
48
- `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let me;try{me=f.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>U==="create-epic"||U==="idea-diagnose"?Li(s,W,U):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const At=me?.key;if(e.privateExecutionBeta&&U==="create-epic"&&me){const c=jt(s).operations[me.fingerprint],d=c?.epicId?w.epics[c.epicId]:void 0,y=u(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&y?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:d},stories:{...O.stories,...Object.fromEntries((Array.isArray(d.stories)?d.stories:[]).filter(R=>typeof R=="string"&&w.stories[R]?.epic_id===c.epicId).map(R=>[R,w.stories[R]]))}})}const it=h?{schemaVersion:1,invocationId:f.invocationId,intent:f.intent,clientProjection:ri(Ir.map(c=>({...c,count:1})))}:void 0;let z,oe,ce;if(e.privateExecutionBeta&&U==="idea-research")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,y=u(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const R=X(s,".neocortex/state.json"),G=Nt(R);if(!G.isFile()||G.isSymbolicLink()||G.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ue=Ve(R),te=JSON.parse(ue.toString("utf8")),de=rr(te,y.claimId,c),le=u(te)&&u(te.epics)&&u(te.epics[c])?te.epics[c]:void 0,B=u(le?.createEpicPlanningPhysical)?le.createEpicPlanningPhysical:void 0;if(B?.receiptId!==y.receiptId||!E(B,y))throw new Error("planning-research-predecessor-drift");const fe=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Ne={...process.env};for(const he of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ne[he];for(const he of fe){const De=Nt(X(s,he));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const qe=je("git",["show",`HEAD:${he}`],{cwd:s,env:Ne,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ve(X(s,he)).equals(qe))throw new Error("planning-research-source-uncommitted")}oe={claimId:y.claimId,epicId:c,diagnosisReceiptId:de.diagnosisReceiptId,intakeRevision:de.intakeRevision,physicalAcceptanceReceiptId:y.receiptId,sourceStateSha256:Ge("sha256").update(ue).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&U==="generate-epic")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,y=u(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const R=X(s,".neocortex/state.json"),G=Nt(R);if(!G.isFile()||G.isSymbolicLink()||G.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ue=Ve(R),te=JSON.parse(ue.toString("utf8")),de=ar(te,y.claimId,c),le=u(te)&&u(te.epics)&&u(te.epics[c])?te.epics[c]:void 0,B=u(le?.createEpicPlanningResearchPhysical)?le.createEpicPlanningResearchPhysical:void 0;if(B?.receiptId!==y.receiptId||!E(B,y))throw new Error("planning-generation-predecessor-drift");const fe=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Ne={...process.env};for(const he of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ne[he];for(const he of fe){const De=Nt(X(s,he));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const qe=je("git",["show",`HEAD:${he}`],{cwd:s,env:Ne,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ve(X(s,he)).equals(qe))throw new Error("planning-generation-source-uncommitted")}ce={claimId:y.claimId,epicId:c,diagnosisReceiptId:de.diagnosisReceiptId,researchReceiptId:de.researchReceiptId,intakeRevision:de.intakeRevision,physicalAcceptanceReceiptId:de.physicalAcceptanceReceiptId,sourceStateSha256:Ge("sha256").update(ue).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");z=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const Qe=z?{schemaVersion:1,hostKind:"codex-cli",hostVersion:z.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:z.observedAtMs}}:void 0;let Oe;if(U==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(Oe=er(s),!Oe)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let mt;if(U==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(mt=er(s),!mt||!E(O.archPlan.execution.pactAnswerReceipt,mt))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let We,ee,k;if(e.privateExecutionBeta&&U==="generate-pacts")try{const c=i.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(ee=Ea(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!ee||!E(d.pactAnswerReceipt,ee.receipt))throw new Error("private-execution-pact-admission-unverified");const y=Sa(s,ee.answers.generateProvider);if(y.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");We=y.writeSet,k={schemaVersion:1,targetEpicId:c,graphRevision:ee.receipt.graphRevision,answersSha256:ee.receipt.answersSha256,specSha256:We.specSha256,pathsSha256:We.pathsSha256,endpointCount:We.endpointCount,pathCount:We.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Pe,J;if(e.privateExecutionBeta&&U==="arch-ux-design")try{const c=i.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:y}=await import("../private-execution/ux-write-set.js");Pe=y(s,c),J={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Pe.adapterId,authoritySha256:Pe.authoritySha256,pathsSha256:Pe.pathsSha256,screenCount:Pe.screenCount,pathCount:Pe.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let yt,Xe,ye;if(e.privateExecutionBeta&&U==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),y=c(s);if(!y)throw new Error("private-execution-property-admission-unverified");yt=y.choices,Xe=y.plan,ye=d(y.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let K={args:i,projectRoot:s.replace(Ft(),"~"),stateSnapshot:O,...Oe?{architectureAnswerReceipt:Oe}:{},...k?{pactExecutionInput:k}:{},...J?{uxExecutionInput:J}:{},...ye?{propertyTestExecutionInput:ye}:{},platformTarget:L,...P?{nativeHostAttestation:P}:{},...Qe?{privateExecution:Qe}:{},projectId:Te,inputEvidence:n,idempotencyKey:At,registryVersion:wt,registryChecksum:Ct,...it?{strictReadOnly:it}:{}};const bt=Vt(K);if(!h&&e.inputSource&&e.inputSource!=="args"&&bt>=Pn)try{K={argsRef:(await ei(f,"secondary-mutation",()=>Co(I,i,j.token,()=>j.client.forceRefresh()),async()=>{throw new Lt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Ft(),"~"),stateSnapshot:O,...Oe?{architectureAnswerReceipt:Oe}:{},platformTarget:L,...P?{nativeHostAttestation:P}:{},...Qe?{privateExecution:Qe}:{},projectId:Te,inputEvidence:n,idempotencyKey:At,registryVersion:wt,registryChecksum:Ct,...it?{strictReadOnly:it}:{}}}catch(c){return c instanceof Lt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(U==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,d=O.scope?.targetEpicId;if(!c||!d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const{collectYoloSpecEnvelope:y}=await import("../yolo/spec-envelope-collector.js"),R=y({projectRoot:s,storyId:c,epicId:d,inputSha256:n.sha256,onOmittedReferences:G=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${G}; core story artifacts preserved.
49
- `)});if(/\sbranchless-preparation\s*$/.test(i))K={...K,yoloSpecEnvelope:R};else{const{collectYoloChangeEvidence:G,reconcileYoloChangeEvidenceLease:ue}=await import("../yolo/change-evidence-collector.js");await ue({projectRoot:s,storyId:c,epicId:d});const te=G({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:R.sourceRevision.headSha,storyId:c,epicId:d});K={...K,yoloSpecEnvelope:R,yoloChangeEvidence:te}}}catch(y){const R=y instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(y.message)?y.message:"yolo-spec-envelope-unsafe";return{success:!1,error:R,errorCode:R,exitCode:1}}}try{const c=ea(K);if(U==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};K=c.body,c.degraded?na(K,c.telemetry):xo(K)}catch(c){if(c instanceof Dn||c instanceof Ln)return na(K,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
50
- `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(U==="yolo"&&K.yoloSpecEnvelope)try{const{collectYoloSpecEnvelope:c}=await import("../yolo/spec-envelope-collector.js"),d=c({projectRoot:s,storyId:K.yoloSpecEnvelope.storyId,epicId:K.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:K.yoloSpecEnvelope.collectedAt});if(d.envelopeSha256!==K.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(K.yoloChangeEvidence){const{collectYoloChangeEvidence:y}=await import("../yolo/change-evidence-collector.js"),R=y({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:d.sourceRevision.headSha,storyId:d.storyId,epicId:d.epicId});if(R.pathsSha256!==K.yoloChangeEvidence.pathsSha256||R.baseSha!==K.yoloChangeEvidence.baseSha)throw new Error("yolo-spec-envelope-stale")}}catch{return{success:!1,error:"yolo-spec-envelope-stale",errorCode:"yolo-spec-envelope-stale",exitCode:1}}const T=U==="arch-plan"?K.stateSnapshot.archPlan?.execution:void 0;let xt;if(T?.owner==="root"&&(T.currentStageCommand==="arch-prd"||T.currentStageCommand==="arch-architecture"||T.currentStageCommand==="arch-fitness-functions"||T.currentStageCommand==="arch-api-contracts"||T.currentStageCommand==="generate-pacts"||T.currentStageCommand==="arch-api-integrations"||T.currentStageCommand==="arch-database"||T.currentStageCommand==="arch-security"||T.currentStageCommand==="arch-design-system"||T.currentStageCommand==="arch-ux-design"||T.currentStageCommand==="arch-performance"||T.currentStageCommand==="arch-testing"||T.currentStageCommand==="arch-infrastructure"||T.currentStageCommand==="arch-review"||T.currentStageCommand==="update-memory")&&(T.continuationState==="delegate"||T.continuationState==="advance"||T.currentStageCommand==="update-memory"&&T.continuationState==="complete"||T.currentStageCommand==="arch-review"&&T.continuationState==="ask-user"||T.currentStageCommand==="generate-pacts"&&T.continuationState==="ask-user"))try{const c=Ve(X(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),y=u(d.archPlan)?d.archPlan.execution:void 0;if(at?y!==void 0||!u(d.epics)||!Object.hasOwn(d.epics,String(T.targetEpicId))||T.graphSource!=="committed-epic-v1"||T.graphRevision!==$t(s,String(T.targetEpicId)):!E(pn(y),T))throw new Error("architecture-root-state-binding-invalid");if(xt=Ge("sha256").update(c).digest("hex"),Oe&&Oe.stateSha256!==xt)throw new Error("architecture-root-state-binding-invalid");if(T.currentStageCommand==="update-memory"&&T.childStatus==="succeeded"){const R=T.continuationState==="complete"&&Array.isArray(T.acceptedStages)?{...T,continuationState:"delegate",acceptedStages:T.acceptedStages.slice(0,Xn(T))}:T;if(!Bt(T.terminalMemoryCheckpoint,T)||!E(T.terminalMemoryCheckpoint,_n(s,R)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let g=await Er("invoke-query",()=>ua(I,K,j.token,{refreshToken:()=>j.client.forceRefresh()})),Tt;if(h&&g.ok)try{if(v){const d=g.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(R=>d[R]!==void 0))throw new Lt("readonly-response-conflict")}const c=g.data?.metadata.strictReadOnly;ii(f,c),v&&pi(g.data?.metadata.strictDiagnose,a,g.data?.instructions??""),Tt=c.security}catch(c){const d=c instanceof Lt?c.code:"readonly-receipt-mismatch";return{success:!1,error:d,errorCode:d,exitCode:1}}if(!g.ok&&g.status===426){const c=g.errorBody,d=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",y=c?.min_version??"unknown";return process.stderr.write(`
33
+ `),{success:!1,error:d,exitCode:1}}let B;if(e.privateExecutionBeta&&(u==="sync-openapi"||u==="chaos-plan"||u==="arch-prd"||u==="arch-architecture"||u==="arch-fitness-functions"||u==="arch-api-contracts"||u==="arch-api-integrations"||u==="arch-database"||u==="arch-security"||u==="arch-design-system"||u==="arch-performance"||u==="arch-testing"||u==="arch-infrastructure"||u==="arch-review"||u==="update-memory"||u==="arch-ux-design"||u==="generate-pacts"||u==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");B=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let N;try{const c=await Io(s,e.args,u);N=fn(s,{epicAware:D,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&u==="create-epic"})}catch(c){const d=c instanceof it?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
34
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),d={args:e.args,projectRoot:s,logger:{info:m=>process.stderr.write(`${m}
35
+ `),warn:m=>process.stderr.write(`${m}
36
+ `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},i=d.args,n=_r(an(t.source,i)))}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${d}. Proceeding with raw args.
37
+ `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=Sc(N,d);N.yoloop=m?{...d,continuationRecoveryEvidence:m}:d}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
38
+ `),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),d=await c(e.args,s,void 0,p,{includeExistingStore:!y});d&&(N.continuity=d)}catch(c){if(c instanceof Mt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${d}. Proceeding without continuity state.
39
+ `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:N,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:d=>{console.warn(d)},info:d=>{console.error(d)}}})}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${d}. Proceeding without enrichment.
40
+ `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(N.architecture_policy=d)}catch(c){const d=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${d}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:d}=await import("../yoloop/invoke-hooks.js"),m=await d({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:b=>process.stderr.write(`${b}
41
+ `)}});m.applied&&m.metadata&&(N.graphRetrieval=m.metadata)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${d}. Proceeding without enrichment.
42
+ `)}try{if(Qi(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),d=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...d?{candidatePaths:[d],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(N.projectEvidence=m)}}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${d}. Proceeding without local project evidence.
43
+ `)}try{const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:d}=await import("../checkpoint/index.js");return d(s)},async()=>{});c&&(N.implementCheckpoint=c)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${d}. Proceeding without checkpoint.
44
+ `)}const ae=I?.licenseKey?new xn({cacheDir:kn,passphrase:I.licenseKey,strictReadOnly:C}):null,M=i.trim();if(!M&&ae){const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>So(ae),async()=>null);if(c)return p.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const $=await Zr(w,I?.licenseKey,p);if($.status!=="authenticated"){const c=$.status==="refresh-required",d=!c&&I&&!I.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=hr(),b=ur(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);b&&process.stderr.write(lr(b,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${d} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const Pe=N.config.project_id;try{await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ic(s,N,w,$.token,Pe,{refreshToken:()=>$.client.forceRefresh()}),async()=>0)}catch{}const st=Cc(M);if(st&&!y)try{const c=await $.tierClient.preFlightCheck(st);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
45
+ `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const X=await Mo({args:M,projectRoot:s,platformTarget:T,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:p});if(X.attachToRequest&&(N.runnerBootstrap=X.metadata),X.warning&&process.stderr.write(`[Neocortex] ${X.warning}
46
+ `),!X.shouldContinue)return X.error&&process.stderr.write(`[Neocortex] ${X.error}
47
+ `),{success:!1,error:X.error??"Runner auto-bootstrap required but failed.",errorCode:X.errorCode,exitCode:X.exitCode??1};if(X.metadata.command==="runner"&&(X.metadata.operation==="status"||X.metadata.operation==="doctor"))try{const c=e.runnerObserver??Qa;N.runnerOperationalStatus=await c(X.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:p})}catch{}let O;try{const c=Ga(M,N);if(c&&!c.ok){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
48
+ `),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??fr(M,N),rn(M)==="migrate-state"&&(O={...O,migrationAuthority:qa(s)})}catch(c){if(c instanceof Fa)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof mr){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
49
+ `),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!C)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),m=d(s);if(Nt(m.databasePath)){const b=await c(s);try{const F=b.store.listRecentNativeAgentDispatches(20);F.length>0&&(O.nativeAgentDispatches=F)}finally{b.store.close()}}}catch{}const q=rn(M);let dt=!1;if(q==="arch-plan"&&!C&&O.archPlan?.execution===void 0){const c=_a(i);if(c)try{if(!Object.hasOwn(N.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=Gt(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},dt=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((q==="arch-plan"||q?.startsWith("arch-")||q==="generate-pacts"||q==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Gt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Ne=Pe;if((q==="create-epic"||q==="idea-diagnose")&&!Ne){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
50
+ `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let ve;try{ve=p.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>q==="create-epic"||q==="idea-diagnose"?Wi(s,M,q):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const We=ve?.key;if(e.privateExecutionBeta&&q==="create-epic"&&ve){const c=Vt(s).operations[ve.fingerprint],d=c?.epicId?N.epics[c.epicId]:void 0,m=l(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:d},stories:{...O.stories,...Object.fromEntries((Array.isArray(d.stories)?d.stories:[]).filter(b=>typeof b=="string"&&N.stories[b]?.epic_id===c.epicId).map(b=>[b,N.stories[b]]))}})}const He=C?{schemaVersion:1,invocationId:p.invocationId,intent:p.intent,clientProjection:si(wr.map(c=>({...c,count:1})))}:void 0;let Z,le,ie;if(e.privateExecutionBeta&&q==="idea-research")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,m=l(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const b=J(s,".neocortex/state.json"),F=Lt(b);if(!F.isFile()||F.isSymbolicLink()||F.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const fe=Ue(b),se=JSON.parse(fe.toString("utf8")),pe=cr(se,m.claimId,c),ge=l(se)&&l(se.epics)&&l(se.epics[c])?se.epics[c]:void 0,U=l(ge?.createEpicPlanningPhysical)?ge.createEpicPlanningPhysical:void 0;if(U?.receiptId!==m.receiptId||!E(U,m))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Le={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Le[me];for(const me of Ee){const De=Lt(J(s,me));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Qe=Ve("git",["show",`HEAD:${me}`],{cwd:s,env:Le,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ue(J(s,me)).equals(Qe))throw new Error("planning-research-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:pe.diagnosisReceiptId,intakeRevision:pe.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ye("sha256").update(fe).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&q==="generate-epic")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,m=l(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const b=J(s,".neocortex/state.json"),F=Lt(b);if(!F.isFile()||F.isSymbolicLink()||F.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const fe=Ue(b),se=JSON.parse(fe.toString("utf8")),pe=sr(se,m.claimId,c),ge=l(se)&&l(se.epics)&&l(se.epics[c])?se.epics[c]:void 0,U=l(ge?.createEpicPlanningResearchPhysical)?ge.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==m.receiptId||!E(U,m))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Le={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Le[me];for(const me of Ee){const De=Lt(J(s,me));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Qe=Ve("git",["show",`HEAD:${me}`],{cwd:s,env:Le,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ue(J(s,me)).equals(Qe))throw new Error("planning-generation-source-uncommitted")}ie={claimId:m.claimId,epicId:c,diagnosisReceiptId:pe.diagnosisReceiptId,researchReceiptId:pe.researchReceiptId,intakeRevision:pe.intakeRevision,physicalAcceptanceReceiptId:pe.physicalAcceptanceReceiptId,sourceStateSha256:Ye("sha256").update(fe).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");Z=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const Et=Z?{schemaVersion:1,hostKind:"codex-cli",hostVersion:Z.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:Z.observedAtMs}}:void 0;let qe;if(q==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(qe=ar(s),!qe)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let Fe;if(q==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(Fe=ar(s),!Fe||!E(O.archPlan.execution.pactAnswerReceipt,Fe))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let j,oe,z;if(e.privateExecutionBeta&&q==="generate-pacts")try{const c=i.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(oe=wa(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!oe||!E(d.pactAnswerReceipt,oe.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Ra(s,oe.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");j=m.writeSet,z={schemaVersion:1,targetEpicId:c,graphRevision:oe.receipt.graphRevision,answersSha256:oe.receipt.answersSha256,specSha256:j.specSha256,pathsSha256:j.pathsSha256,endpointCount:j.endpointCount,pathCount:j.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ke,ce;if(e.privateExecutionBeta&&q==="arch-ux-design")try{const c=i.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");ke=m(s,c),ce={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:ke.adapterId,authoritySha256:ke.authoritySha256,pathsSha256:ke.pathsSha256,screenCount:ke.screenCount,pathCount:ke.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let It,Ke,ye;if(e.privateExecutionBeta&&q==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");It=m.choices,Ke=m.plan,ye=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Y={args:i,projectRoot:s.replace(Ft(),"~"),stateSnapshot:O,...qe?{architectureAnswerReceipt:qe}:{},...z?{pactExecutionInput:z}:{},...ce?{uxExecutionInput:ce}:{},...ye?{propertyTestExecutionInput:ye}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...Et?{privateExecution:Et}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:bt,registryChecksum:At,...He?{strictReadOnly:He}:{}};const In=Ut(Y);if(!C&&e.inputSource&&e.inputSource!=="args"&&In>=On)try{Y={argsRef:(await ii(p,"secondary-mutation",()=>To(w,i,$.token,()=>$.client.forceRefresh()),async()=>{throw new Mt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Ft(),"~"),stateSnapshot:O,...qe?{architectureAnswerReceipt:qe}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...Et?{privateExecution:Et}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:bt,registryChecksum:At,...He?{strictReadOnly:He}:{}}}catch(c){return c instanceof Mt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(q==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,d=O.scope?.targetEpicId;if(!c||!d||!Q||Q.storyId!==c||Q.epicId!==d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const m=Ni(Q);if(/\sbranchless-preparation\s*$/.test(i))Y={...Y,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:b,reconcileYoloChangeEvidenceLease:F}=await import("../yolo/change-evidence-collector.js");await F({projectRoot:s,storyId:c,epicId:d});const fe=b({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d});Y={...Y,yoloSpecEnvelope:m,yoloChangeEvidence:fe}}}catch(m){const b=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:b,errorCode:b,exitCode:1}}}try{const c=ia(Y);if(q==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};Y=c.body,c.degraded?ca(Y,c.telemetry):Do(Y)}catch(c){if(c instanceof Mn||c instanceof jn)return ca(Y,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
51
+ `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(q==="yolo"&&Y.yoloSpecEnvelope)try{const c=br({projectRoot:s,storyId:Y.yoloSpecEnvelope.storyId,epicId:Y.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:Y.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==Y.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(Y.yoloChangeEvidence){const{collectYoloChangeEvidence:d}=await import("../yolo/change-evidence-collector.js"),m=d({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId});if(m.pathsSha256!==Y.yoloChangeEvidence.pathsSha256||m.baseSha!==Y.yoloChangeEvidence.baseSha)throw new Error("yolo-spec-envelope-stale")}}catch{return{success:!1,error:"yolo-spec-envelope-stale",errorCode:"yolo-spec-envelope-stale",exitCode:1}}const x=q==="arch-plan"?Y.stateSnapshot.archPlan?.execution:void 0;let St;if(x?.owner==="root"&&(x.currentStageCommand==="arch-prd"||x.currentStageCommand==="arch-architecture"||x.currentStageCommand==="arch-fitness-functions"||x.currentStageCommand==="arch-api-contracts"||x.currentStageCommand==="generate-pacts"||x.currentStageCommand==="arch-api-integrations"||x.currentStageCommand==="arch-database"||x.currentStageCommand==="arch-security"||x.currentStageCommand==="arch-design-system"||x.currentStageCommand==="arch-ux-design"||x.currentStageCommand==="arch-performance"||x.currentStageCommand==="arch-testing"||x.currentStageCommand==="arch-infrastructure"||x.currentStageCommand==="arch-review"||x.currentStageCommand==="update-memory")&&(x.continuationState==="delegate"||x.continuationState==="advance"||x.currentStageCommand==="update-memory"&&x.continuationState==="complete"||x.currentStageCommand==="arch-review"&&x.continuationState==="ask-user"||x.currentStageCommand==="generate-pacts"&&x.continuationState==="ask-user"))try{const c=Ue(J(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=l(d.archPlan)?d.archPlan.execution:void 0;if(dt?m!==void 0||!l(d.epics)||!Object.hasOwn(d.epics,String(x.targetEpicId))||x.graphSource!=="committed-epic-v1"||x.graphRevision!==Gt(s,String(x.targetEpicId)):!E(un(m),x))throw new Error("architecture-root-state-binding-invalid");if(St=Ye("sha256").update(c).digest("hex"),qe&&qe.stateSha256!==St)throw new Error("architecture-root-state-binding-invalid");if(x.currentStageCommand==="update-memory"&&x.childStatus==="succeeded"){const b=x.continuationState==="complete"&&Array.isArray(x.acceptedStages)?{...x,continuationState:"delegate",acceptedStages:x.acceptedStages.slice(0,nr(x))}:x;if(!$t(x.terminalMemoryCheckpoint,x)||!E(x.terminalMemoryCheckpoint,An(s,b)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let f=await Cr("invoke-query",()=>ma(w,Y,$.token,{refreshToken:()=>$.client.forceRefresh()})),vt;if(C&&f.ok)try{if(y){const d=f.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(b=>d[b]!==void 0))throw new Mt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;pi(p,c),y&&gi(f.data?.metadata.strictDiagnose,r,f.data?.instructions??""),vt=c.security}catch(c){const d=c instanceof Mt?c.code:"readonly-receipt-mismatch";return{success:!1,error:d,errorCode:d,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,d=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
51
52
  `),process.stderr.write(`==================================================
52
53
  `),process.stderr.write(` UPGRADE REQUIRED
53
54
  `),process.stderr.write(`==================================================
54
55
  `),process.stderr.write(`
55
56
  Your Neocortex version (${Dt}) is no longer supported.
56
- `),process.stderr.write(` Minimum required: ${y}
57
+ `),process.stderr.write(` Minimum required: ${m}
57
58
 
58
59
  `),process.stderr.write(` Run this command to update:
59
60
 
@@ -62,11 +63,11 @@ ${t}
62
63
  `),process.stderr.write(` After updating, re-run your command.
63
64
  `),process.stderr.write(`==================================================
64
65
 
65
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Dt} is below minimum ${y}. Run: ${d}`,exitCode:3}}if(!g.ok||!g.data){const c=g.status===401?2:(g.status===429||g.status>=500,1),d=mo(g);try{if(d){const y=pr(),R=sr(d,y);R&&process.stderr.write(dr(R,y))}}catch{}return{success:!1,error:He(g.error??"Unknown error from server",_t),...d?{errorCode:d}:{},exitCode:c}}let ge;try{ge=e.privateExecutionBeta&&U==="create-epic"&&me?jt(s).operations[me.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const ot=ge?.planningProtocol==="root-staged-v1"&&typeof ge.claimId=="string"&&typeof ge.epicId=="string"&&Ra(g.data,{claimId:ge.claimId,epicId:ge.epicId,...u(w.epics[ge.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:w.epics[ge.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!ot&&!_a(g.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(xt&&T&&g.data.metadata?.mode==="arch-plan"&&u(g.data.metadata.archPlan)&&u(g.data.metadata.archPlan.execution)&&(g.data.metadata.archPlan.execution.nextAction==="delegate"||g.data.metadata.archPlan.execution.nextAction==="resume"||g.data.metadata.archPlan.execution.nextAction==="ask-user"||g.data.metadata.archPlan.execution.nextAction==="complete"&&g.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||g.data.metadata.archPlan.execution.nextAction==="blocked"&&(g.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>eo({projectRoot:s,sourceStateSha256:xt,requestExecution:T,initialBinding:at,answerReceipt:Oe,pactRecordedReceipt:mt,metadata:g.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const d=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${d}. Root stage instruction was not released.
66
- `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!W&&g.data.metadata?.mode==="menu"&&$&&await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>ho($,g.data.instructions,g.data.metadata),async()=>{}).catch(()=>{}),g.data.metadata&&await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>j.tierClient.updateQuotaFromResponse(g.data.metadata),async()=>{}).catch(()=>{}),g.data.metadata?.stateMutated===!0)try{const c=await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:d}=await import("../yoloop/invoke-hooks.js");return d(g.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const d=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${d}
67
- `),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(g.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),y=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${He(d,_t)}).`;return process.stderr.write(`${y}
68
- `),{success:!1,error:y,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(g.data.metadata?.gitLifecycleGraphAuthority)try{await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>vi(s,g.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const d=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${d}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
69
- `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(g.data.metadata?.mode==="error"&&g.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
66
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Dt} is below minimum ${m}. Run: ${d}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),d=wo(f);try{if(d){const m=hr(),b=ur(d,m);b&&process.stderr.write(lr(b,m))}}catch{}return{success:!1,error:ze(f.error??"Unknown error from server",xt),...d?{errorCode:d}:{},exitCode:c}}let he;try{he=e.privateExecutionBeta&&q==="create-epic"&&ve?Vt(s).operations[ve.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Pt=he?.planningProtocol==="root-staged-v1"&&typeof he.claimId=="string"&&typeof he.epicId=="string"&&Pa(f.data,{claimId:he.claimId,epicId:he.epicId,...l(N.epics[he.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:N.epics[he.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!Pt&&!Ta(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(St&&x&&f.data.metadata?.mode==="arch-plan"&&l(f.data.metadata.archPlan)&&l(f.data.metadata.archPlan.execution)&&(f.data.metadata.archPlan.execution.nextAction==="delegate"||f.data.metadata.archPlan.execution.nextAction==="resume"||f.data.metadata.archPlan.execution.nextAction==="ask-user"||f.data.metadata.archPlan.execution.nextAction==="complete"&&f.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||f.data.metadata.archPlan.execution.nextAction==="blocked"&&(f.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>so({projectRoot:s,sourceStateSha256:St,requestExecution:x,initialBinding:dt,answerReceipt:qe,pactRecordedReceipt:Fe,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const d=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${d}. Root stage instruction was not released.
67
+ `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!M&&f.data.metadata?.mode==="menu"&&ae&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>vo(ae,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>$.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:d}=await import("../yoloop/invoke-hooks.js");return d(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const d=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${d}
68
+ `),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${ze(d,xt)}).`;return process.stderr.write(`${m}
69
+ `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Ai(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const d=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${d}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
70
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(f.data.metadata?.mode==="error"&&f.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
70
71
  `),process.stderr.write(`==================================================
71
72
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
72
73
  `),process.stderr.write(`==================================================
@@ -81,55 +82,55 @@ ${t}
81
82
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
82
83
  `),process.stderr.write(`==================================================
83
84
 
84
- `),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(g.data.metadata?.yoloopStateUpdate){const d=(g.data.metadata.yoloopStateUpdate.operations??[]).some(y=>y.type==="rollover_session");try{const y=await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:R}=await import("../yoloop/invoke-hooks.js");return R(g.data.metadata,s)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(y&&y.ok===!1){const R=y.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${R}. No yoloop continuation instructions were released.
85
- `),{success:!1,error:R,errorCode:R,exitCode:1}}}catch(y){if(d){const R=y instanceof Error?y.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${R}. No yoloop continuation instructions were released.
86
- `),{success:!1,error:R,errorCode:R,exitCode:1}}}}if(g.data.metadata?.continuityStateUpdate)try{const c=await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:d}=await import("../continuity/invoke-hooks.js");return d(g.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const d=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${d}. No continuity mutation was committed.
85
+ `),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(f.data.metadata?.yoloopStateUpdate){const d=(f.data.metadata.yoloopStateUpdate.operations??[]).some(m=>m.type==="rollover_session");try{const m=await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:b}=await import("../yoloop/invoke-hooks.js");return b(f.data.metadata,s)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(m&&m.ok===!1){const b=m.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${b}. No yoloop continuation instructions were released.
86
+ `),{success:!1,error:b,errorCode:b,exitCode:1}}}catch(m){if(d){const b=m instanceof Error?m.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${b}. No yoloop continuation instructions were released.
87
+ `),{success:!1,error:b,errorCode:b,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:d}=await import("../continuity/invoke-hooks.js");return d(f.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const d=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${d}. No continuity mutation was committed.
87
88
  `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${d}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${d}. No continuity mutation was committed.
88
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${He(d,_t)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(g.data.metadata?.tier_changed){const c=g.data.metadata.current_tier;try{await j.client.forceRefresh()?(await j.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
89
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${ze(d,xt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await $.client.forceRefresh()?(await $.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
89
90
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
90
91
  `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
91
- `)}}let Q,Yt=!1;if(e.privateExecutionBeta&&!ot)try{if(!z||!g.data.metadata?.privateExecution||!Te||g.data.metadata?.mode!=="yolo"&&g.data.metadata?.mode!=="step"&&g.data.metadata?.mode!=="pipeline"&&g.data.metadata?.mode!=="create-epic"&&g.data.metadata?.mode!=="utility"&&g.data.metadata?.mode!=="tech-debt"&&g.data.metadata?.mode!=="ui-ux-review"||typeof g.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:y,runPrivateCodexStep:R}=await import("../private-execution/codex-executor.js"),G=g.data.metadata.mode==="yolo",ue=g.data.metadata.mode==="ui-ux-review"&&g.data.metadata.resolvedTrigger==="ui-ux-review",te=g.data.metadata.mode==="create-epic",de=u(g.data.metadata.privateExecution)?g.data.metadata.privateExecution:void 0,le=u(de?.binding)?de.binding:void 0,B=te&&g.data.metadata.resolvedTrigger==="create-epic"&&le?.writeSetId==="idea-diagnosis-v1"&&g.data.metadata.stepId==="step-acd455ed";if(te&&!B)throw new Error("private-execution-planning-root-protocol-required");const fe=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-diagnose"||B,Ne=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-research",he=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-epic",De=te||fe;if(Ne&&!oe||he&&!ce)throw new Error("private-execution-planning-predecessor-unavailable");const qe=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="sync-openapi"||g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="chaos-plan"||m&&g.data.metadata.mode==="tech-debt"&&g.data.metadata.resolvedTrigger==="tech-debt",Ee=g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="arch-prd"||g.data.metadata.resolvedTrigger==="arch-architecture"||g.data.metadata.resolvedTrigger==="arch-fitness-functions"||g.data.metadata.resolvedTrigger==="arch-api-contracts"||g.data.metadata.resolvedTrigger==="arch-api-integrations"||g.data.metadata.resolvedTrigger==="arch-database"||g.data.metadata.resolvedTrigger==="arch-security"||g.data.metadata.resolvedTrigger==="arch-design-system"||g.data.metadata.resolvedTrigger==="arch-performance"||g.data.metadata.resolvedTrigger==="arch-testing"||g.data.metadata.resolvedTrigger==="arch-infrastructure"||g.data.metadata.resolvedTrigger==="arch-review"||g.data.metadata.resolvedTrigger==="update-memory")?g.data.metadata.resolvedTrigger:void 0,ct=Ee!==void 0,In=Ee==="arch-prd"?"arch-prd-docs-v1":Ee==="update-memory"?"arch-memory-canonical-v1":Ee==="arch-review"?"arch-review-doc-v1":Ee==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ee==="arch-testing"?"arch-testing-doc-v1":Ee==="arch-performance"?"arch-performance-doc-v1":Ee==="arch-design-system"?"arch-design-system-doc-v1":Ee==="arch-security"?"arch-security-doc-v1":Ee==="arch-database"?"arch-database-doc-v1":Ee==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ee==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ee==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",Ze=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-pacts",st=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="arch-ux-design",dt=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="property-test",Sn=m?"tech-debt":g.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",Yn=m?"tech-debt-registry-v1":Sn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",$e=O.archPlan?.execution,Qt=$e?.targetEpicId,Xt=$e?.graphRevision;if(ct&&($e?.currentStageCommand!==Ee||typeof Qt!="string"||!/^P[1-9][0-9]{0,11}$/.test(Qt)||typeof Xt!="string"||!/^[a-f0-9]{64}$/.test(Xt)))throw new Error("private-execution-architecture-admission-unverified");if(Ze&&(!k||!We||!ee||$e?.currentStageCommand!=="generate-pacts"||$e.continuationState!=="delegate"||$e.targetEpicId!==k.targetEpicId||$e.graphRevision!==k.graphRevision||!E($e.pactAnswerReceipt,ee.receipt)))throw new Error("private-execution-pact-admission-unverified");if(st&&(!J||!Pe||$e?.currentStageCommand!=="arch-ux-design"||$e.continuationState!=="delegate"||$e.targetEpicId!==J.targetEpicId||$e.graphRevision!==J.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(dt&&(!ye||!yt||!Xe||g.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let Kn;if(Ze){const{planPactToolchainManifest:ie,preparePactToolchainCandidate:pe}=await import("../private-execution/pact-toolchain.js");try{ie(s,ee.answers.generateProvider),Kn=pe(s,ee.answers.generateProvider)}catch(H){if(H.message!=="pact-toolchain-manifest-unsupported")throw H}}let Et,se,vn;const ae=g.data.metadata.gitLifecycleGraphAuthority,It=g.data.metadata.privateExecutionRootAction;let ze;if(G){if(!ae||typeof ae.storyId!="string"||typeof ae.graphRevision!="string"||typeof ae.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(ze=ae.storyId,It?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:A}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Re}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:pt}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Me,recordPrivateYoloCleanBaseline:Se}=await import("../private-execution/clean-baseline.js"),ve=A(g.data.metadata.privateExecution,{projectId:Te,commandId:"yolo",stepId:g.data.metadata.stepId,graphRevision:ae.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:z.hostVersion}),tt=await j.client.getToken();if(!tt)throw new Error("private-execution-auth-unavailable");if(!await uc(I,{leaseId:ve.leaseId,...ve.binding},tt))throw new Error("private-execution-setup-lease-cancel-unverified");const kt=Me(s),Zt=await Re({projectRoot:s,storyId:It.storyId});if(!Zt.ok)throw new Error("private-execution-root-setup-denied");await Se(s,Zt.value,kt);const{ensurePrivateYoloIsolatedSession:St}=await import("../private-execution/isolated-session.js");await St(s,It.storyId,ae.graphRevision,e.privateExecutionWorkspaceParent);const vt=await pt({projectRoot:s,storyId:It.storyId});if(!vt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${vt.reasonCode}`);Q={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:vt.value,publicSafe:!0};const Cn=sn(g.data.instructions,g.data.metadata);return f.complete(Tt),{success:!0,instructions:`# Setup do branch validado
92
+ `)}}let te,Xn=!1;if(e.privateExecutionBeta&&!Pt)try{if(!Z||!f.data.metadata?.privateExecution||!Ne||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:b}=await import("../private-execution/codex-executor.js"),F=f.data.metadata.mode==="yolo",fe=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",se=f.data.metadata.mode==="create-epic",pe=l(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,ge=l(pe?.binding)?pe.binding:void 0,U=se&&f.data.metadata.resolvedTrigger==="create-epic"&&ge?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(se&&!U)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||U,Le=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",De=se||Ee;if(Le&&!le||me&&!ie)throw new Error("private-execution-planning-predecessor-unavailable");const Qe=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ie=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,pt=Ie!==void 0,vn=Ie==="arch-prd"?"arch-prd-docs-v1":Ie==="update-memory"?"arch-memory-canonical-v1":Ie==="arch-review"?"arch-review-doc-v1":Ie==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ie==="arch-testing"?"arch-testing-doc-v1":Ie==="arch-performance"?"arch-performance-doc-v1":Ie==="arch-design-system"?"arch-design-system-doc-v1":Ie==="arch-security"?"arch-security-doc-v1":Ie==="arch-database"?"arch-database-doc-v1":Ie==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ie==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ie==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",nt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",ut=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",lt=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",Cn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",Zn=S?"tech-debt-registry-v1":Cn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ge=O.archPlan?.execution,Qt=Ge?.targetEpicId,Xt=Ge?.graphRevision;if(pt&&(Ge?.currentStageCommand!==Ie||typeof Qt!="string"||!/^P[1-9][0-9]{0,11}$/.test(Qt)||typeof Xt!="string"||!/^[a-f0-9]{64}$/.test(Xt)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!z||!j||!oe||Ge?.currentStageCommand!=="generate-pacts"||Ge.continuationState!=="delegate"||Ge.targetEpicId!==z.targetEpicId||Ge.graphRevision!==z.graphRevision||!E(Ge.pactAnswerReceipt,oe.receipt)))throw new Error("private-execution-pact-admission-unverified");if(ut&&(!ce||!ke||Ge?.currentStageCommand!=="arch-ux-design"||Ge.continuationState!=="delegate"||Ge.targetEpicId!==ce.targetEpicId||Ge.graphRevision!==ce.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(lt&&(!ye||!It||!Ke||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let er;if(nt){const{planPactToolchainManifest:re,preparePactToolchainCandidate:ue}=await import("../private-execution/pact-toolchain.js");try{re(s,oe.answers.generateProvider),er=ue(s,oe.answers.generateProvider)}catch(G){if(G.message!=="pact-toolchain-manifest-unsupported")throw G}}let Ct,de,wn;const ne=f.data.metadata.gitLifecycleGraphAuthority,wt=f.data.metadata.privateExecutionRootAction;let Xe;if(F){if(!ne||typeof ne.storyId!="string"||typeof ne.graphRevision!="string"||typeof ne.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Xe=ne.storyId,wt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:R}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Ae}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:ht}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:je,recordPrivateYoloCleanBaseline:Ce}=await import("../private-execution/clean-baseline.js"),we=R(f.data.metadata.privateExecution,{projectId:Ne,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:ne.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion}),at=await $.client.getToken();if(!at)throw new Error("private-execution-auth-unavailable");if(!await Ec(w,{leaseId:we.leaseId,...we.binding},at))throw new Error("private-execution-setup-lease-cancel-unverified");const Ot=je(s),Zt=await Ae({projectRoot:s,storyId:wt.storyId});if(!Zt.ok)throw new Error("private-execution-root-setup-denied");await Ce(s,Zt.value,Ot);const{ensurePrivateYoloIsolatedSession:_t}=await import("../private-execution/isolated-session.js");await _t(s,wt.storyId,ne.graphRevision,e.privateExecutionWorkspaceParent);const Rt=await ht({projectRoot:s,storyId:wt.storyId});if(!Rt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Rt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Rt.value,publicSafe:!0};const _n=dn(f.data.instructions,f.data.metadata);return p.complete(vt),{success:!0,instructions:`# Setup do branch validado
92
93
 
93
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Cn.metadata,privateExecutionReceipt:Q},exitCode:0}}let ie;try{ie=je("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(ie!==ae.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const pe=on(s,{required:!0}),H=typeof ae.epicId=="string"?pe.epics[ae.epicId]:void 0,D=u(H?.branch_lease)?H.branch_lease:void 0;if(!H||H.graph_revision!==ae.graphRevision||!D||D.ownerStoryId!==ae.storyId||typeof D.expiresAt!="string"||!Number.isFinite(Date.parse(D.expiresAt))||Date.parse(D.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="research"||g.data.metadata.resolvedTrigger==="write-spec"||g.data.metadata.resolvedTrigger==="create-tasks"||g.data.metadata.resolvedTrigger==="implement")||g.data.metadata.mode==="pipeline"&&g.data.metadata.resolvedTrigger==="exec"||te&&g.data.metadata.resolvedTrigger==="create-epic"||ue||fe||Ne||he||qe||ct||Ze||st||dt){if(!De&&!Ne&&!he&&!qe&&!ue&&!ct&&!Ze&&!st&&!dt&&typeof g.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(G){const{ensurePrivateYoloIsolatedSession:ie,reconcilePrivateYoloIsolatedSession:pe}=await import("../private-execution/isolated-session.js");if(It?.action==="checkpoint-epic-story")await pe(s,ze,ae.graphRevision);else{const H=await ie(s,ze,ae.graphRevision,e.privateExecutionWorkspaceParent),D=await y(H.workspace.workspacePath);if(D.hostVersion!==z.hostVersion)throw new Error("private-codex-version-drift");z=D}}if(Date.now()-z.observedAtMs>2e4){const ie=await y(z.projectRoot);if(ie.hostVersion!==z.hostVersion)throw new Error("private-codex-version-drift");z=ie}const Qn=await j.client.getToken();if(!Qn)throw new Error("private-execution-auth-unavailable");const Le=De?g.data.metadata.epicClaim:void 0;if(De&&(!Le||typeof Le.claimId!="string"||typeof Le.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(De){if(!me)throw new Error("private-execution-epic-claim-admission-unverified");f.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Or(s,me.fingerprint,Le.claimId,Le.epicId,B?"root-staged-v1":void 0),()=>{}),Yt=!0;const{preparePrivateYoloIsolatedWorkspace:ie,PRIVATE_EPIC_PENDING_SIDECAR:pe}=await import("../private-execution/isolated-workspace.js"),H=e.privateExecutionWorkspaceParent??X(Ft(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Wt(H,{recursive:!0,mode:448}),Et=ie(s,H,!0),vn=Ge("sha256").update(Ve(X(s,pe))).digest("hex");const D=await y(Et.workspacePath);if(D.hostVersion!==z.hostVersion)throw new Error("private-codex-version-drift");z=D}else if(!G&&!ue){const{preparePrivateYoloIsolatedWorkspace:ie}=await import("../private-execution/isolated-workspace.js"),pe=e.privateExecutionWorkspaceParent??X(Ft(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Wt(pe,{recursive:!0,mode:448}),se=ie(s,pe,Ne||he),qe||ct||Ze||st||dt){if(!re)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:D}=await import("../private-execution/isolated-workspace.js");D(se,re)}const H=await y(se.workspacePath);if(H.hostVersion!==z.hostVersion)throw new Error("private-codex-version-drift");z=H}const et=await c(g.data.metadata.privateExecution,{projectId:Te,commandId:G?"yolo":te?"create-epic":ct?Ee:Ze?"generate-pacts":st?"arch-ux-design":dt?"property-test":qe?Sn:g.data.metadata.mode==="pipeline"?"exec":g.data.metadata.resolvedTrigger,stepId:g.data.metadata.stepId,...G?{graphRevision:ae.graphRevision}:{...De?{claimId:Le.claimId,epicId:Le.epicId,...fe?{writeSetId:"idea-diagnosis-v1"}:{}}:Ne?{claimId:oe.claimId,epicId:oe.epicId,diagnosisReceiptId:oe.diagnosisReceiptId,intakeRevision:oe.intakeRevision,physicalAcceptanceReceiptId:oe.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:he?{claimId:ce.claimId,epicId:ce.epicId,diagnosisReceiptId:ce.diagnosisReceiptId,researchReceiptId:ce.researchReceiptId,intakeRevision:ce.intakeRevision,physicalAcceptanceReceiptId:ce.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:qe?{writeSetId:Yn}:ue?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ct?{targetEpicId:Qt,graphRevision:Xt,writeSetId:In}:Ze?{targetEpicId:k.targetEpicId,graphRevision:k.graphRevision,answersSha256:k.answersSha256,specSha256:k.specSha256,pathsSha256:k.pathsSha256,endpointCount:k.endpointCount,pathCount:k.pathCount}:st?{targetEpicId:J.targetEpicId,graphRevision:J.graphRevision,adapterId:J.adapterId,authoritySha256:J.authoritySha256,pathsSha256:J.pathsSha256,screenCount:J.screenCount,pathCount:J.pathCount}:dt?{prdPath:ye.prdPath,prdSha256:ye.prdSha256,planSha256:ye.planSha256,pathsSha256:ye.pathsSha256,aggregateCount:ye.aggregateCount,invariantCount:ye.invariantCount,pathCount:ye.pathCount,language:ye.language,numRuns:ye.numRuns}:{storyId:g.data.metadata.storyId},stateSnapshotSha256:d(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:z.hostVersion},ie=>pc(I,{...ie},Qn));if(ue){const{parsePrivateExecutionDescriptor:ie}=await import("../private-execution/delivery.js"),pe=ie(g.data.metadata.privateExecution);if(pe.schemaVersion!==11||pe.binding.commandId!=="ui-ux-review"||pe.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:H}=await import("../private-execution/private-report-store.js");Q={schemaVersion:1,outcome:"report-stored",report:await H({projectRoot:s,material:et,format:pe.binding.format,sha256:pe.materialSha256}),publicSafe:!0}}else if(It?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ie}=await import("../private-execution/root-checkpoint.js");Q={...await ie(s,It)}}else{const ie=fe?`${et}
94
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{..._n.metadata,privateExecutionReceipt:te},exitCode:0}}let re;try{re=Ve("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(re!==ne.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ue=cn(s,{required:!0}),G=typeof ne.epicId=="string"?ue.epics[ne.epicId]:void 0,L=l(G?.branch_lease)?G.branch_lease:void 0;if(!G||G.graph_revision!==ne.graphRevision||!L||L.ownerStoryId!==ne.storyId||typeof L.expiresAt!="string"||!Number.isFinite(Date.parse(L.expiresAt))||Date.parse(L.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="research"||f.data.metadata.resolvedTrigger==="write-spec"||f.data.metadata.resolvedTrigger==="create-tasks"||f.data.metadata.resolvedTrigger==="implement")||f.data.metadata.mode==="pipeline"&&f.data.metadata.resolvedTrigger==="exec"||se&&f.data.metadata.resolvedTrigger==="create-epic"||fe||Ee||Le||me||Qe||pt||nt||ut||lt){if(!De&&!Le&&!me&&!Qe&&!fe&&!pt&&!nt&&!ut&&!lt&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(F){const{ensurePrivateYoloIsolatedSession:re,reconcilePrivateYoloIsolatedSession:ue}=await import("../private-execution/isolated-session.js");if(wt?.action==="checkpoint-epic-story")await ue(s,Xe,ne.graphRevision);else{const G=await re(s,Xe,ne.graphRevision,e.privateExecutionWorkspaceParent),L=await m(G.workspace.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}}if(Date.now()-Z.observedAtMs>2e4){const re=await m(Z.projectRoot);if(re.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=re}const tr=await $.client.getToken();if(!tr)throw new Error("private-execution-auth-unavailable");const Me=De?f.data.metadata.epicClaim:void 0;if(De&&(!Me||typeof Me.claimId!="string"||typeof Me.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(De){if(!ve)throw new Error("private-execution-epic-claim-admission-unverified");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>jr(s,ve.fingerprint,Me.claimId,Me.epicId,U?"root-staged-v1":void 0),()=>{}),Xn=!0;const{preparePrivateYoloIsolatedWorkspace:re,PRIVATE_EPIC_PENDING_SIDECAR:ue}=await import("../private-execution/isolated-workspace.js"),G=e.privateExecutionWorkspaceParent??J(Ft(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Wt(G,{recursive:!0,mode:448}),Ct=re(s,G,!0),wn=Ye("sha256").update(Ue(J(s,ue))).digest("hex");const L=await m(Ct.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}else if(!F&&!fe){const{preparePrivateYoloIsolatedWorkspace:re}=await import("../private-execution/isolated-workspace.js"),ue=e.privateExecutionWorkspaceParent??J(Ft(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Wt(ue,{recursive:!0,mode:448}),de=re(s,ue,Le||me),Qe||pt||nt||ut||lt){if(!B)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:L}=await import("../private-execution/isolated-workspace.js");L(de,B)}const G=await m(de.workspacePath);if(G.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=G}const rt=await c(f.data.metadata.privateExecution,{projectId:Ne,commandId:F?"yolo":se?"create-epic":pt?Ie:nt?"generate-pacts":ut?"arch-ux-design":lt?"property-test":Qe?Cn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...F?{graphRevision:ne.graphRevision}:{...De?{claimId:Me.claimId,epicId:Me.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:Le?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:ie.claimId,epicId:ie.epicId,diagnosisReceiptId:ie.diagnosisReceiptId,researchReceiptId:ie.researchReceiptId,intakeRevision:ie.intakeRevision,physicalAcceptanceReceiptId:ie.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Qe?{writeSetId:Zn}:fe?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:pt?{targetEpicId:Qt,graphRevision:Xt,writeSetId:vn}:nt?{targetEpicId:z.targetEpicId,graphRevision:z.graphRevision,answersSha256:z.answersSha256,specSha256:z.specSha256,pathsSha256:z.pathsSha256,endpointCount:z.endpointCount,pathCount:z.pathCount}:ut?{targetEpicId:ce.targetEpicId,graphRevision:ce.graphRevision,adapterId:ce.adapterId,authoritySha256:ce.authoritySha256,pathsSha256:ce.pathsSha256,screenCount:ce.screenCount,pathCount:ce.pathCount}:lt?{prdPath:ye.prdPath,prdSha256:ye.prdSha256,planSha256:ye.planSha256,pathsSha256:ye.pathsSha256,aggregateCount:ye.aggregateCount,invariantCount:ye.invariantCount,pathCount:ye.pathCount,language:ye.language,numRuns:ye.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:d(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion},re=>yc(w,{...re},tr));if(fe){const{parsePrivateExecutionDescriptor:re}=await import("../private-execution/delivery.js"),ue=re(f.data.metadata.privateExecution);if(ue.schemaVersion!==11||ue.binding.commandId!=="ui-ux-review"||ue.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:G}=await import("../private-execution/private-report-store.js");te={schemaVersion:1,outcome:"report-stored",report:await G({projectRoot:s,material:rt,format:ue.binding.format,sha256:ue.materialSha256}),publicSafe:!0}}else if(wt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:re}=await import("../private-execution/root-checkpoint.js");te={...await re(s,wt)}}else{const re=Ee?`${rt}
94
95
 
95
96
  Private P01 handoff (local only):
96
- The durable reserved epic ID is ${Le.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Le.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
97
- `:Ne?`${et}
97
+ The durable reserved epic ID is ${Me.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Me.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
98
+ `:Le?`${rt}
98
99
 
99
100
  Private P02 handoff (local only):
100
- The admitted epic is ${oe.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${oe.epicId}/research.md and its transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P03 artifacts; do not auto-continue. The root will independently review and seal the research candidate.
101
- `:he?`${et}
101
+ The admitted epic is ${le.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${le.epicId}/research.md and its transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P03 artifacts; do not auto-continue. The root will independently review and seal the research candidate.
102
+ `:me?`${rt}
102
103
 
103
104
  Private P03 handoff (local only):
104
- The admitted epic is ${ce.epicId}. Generate exactly docs/epics/epic-${ce.epicId}.md, 1 to 24 contiguous docs/stories/${ce.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
105
- `:ct?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(et,Ee,In,Zn(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):Ze?`${et}
105
+ The admitted epic is ${ie.epicId}. Generate exactly docs/epics/epic-${ie.epicId}.md, 1 to 24 contiguous docs/stories/${ie.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
106
+ `:pt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,Ie,vn,rr(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
106
107
 
107
108
  Private A03.5 handoff (local only):
108
- ${JSON.stringify({consumer:ee.answers.consumer,provider:ee.answers.provider,matchersAggressive:ee.answers.matchersAggressive,generateProvider:ee.answers.generateProvider,brokerConfigured:ee.answers.brokerUrl!==null,allowedPaths:We.paths})}
109
+ ${JSON.stringify({consumer:oe.answers.consumer,provider:oe.answers.provider,matchersAggressive:oe.answers.matchersAggressive,generateProvider:oe.answers.generateProvider,brokerConfigured:oe.answers.brokerUrl!==null,allowedPaths:j.paths})}
109
110
  Read docs/api/openapi.yaml. Write only the listed new test files. Do not write package files, CI, Git, graph, or tracked configuration. Use describe and it from vitest for every consumer and provider test, plus expect for consumers. Consumer Pact imports are PactV3 and, only when matchersAggressive is true, MatchersV3. When false, use exact literal values and no matcher helpers or matchingRules. Provider imports Verifier. Do not import Node builtins, filesystem/path helpers or other packages; consumer application imports are allowed only for an existing tracked local client. Each consumer must use a literal HTTP method and concrete path in withRequest, willRespondWith and executeTest with actual response assertions. If no application client exists, label the direct fetch test a mock-only scaffold without claiming compatibility. If specifying a Pact output directory, use the literal pacts or pact-files without subdirectories. Never embed a broker URL. When brokerConfigured is false, verify only local pact files through literal pactUrls and never add broker configuration or token fields. When true, read PACT_BROKER_URL at runtime. Provider base URL may use PACT_PROVIDER_BASE_URL; missing runtime inputs must fail rather than skip. No network, install, provider startup, Git or QA authority is granted to the model.
110
- `:st?`${et}
111
+ `:ut?`${rt}
111
112
 
112
113
  Private A08 handoff (local only):
113
- ${JSON.stringify({targetEpicId:J.targetEpicId,graphRevision:J.graphRevision,adapterId:J.adapterId,approvedScreens:Pe.screens,allowedPaths:Pe.paths})}
114
+ ${JSON.stringify({targetEpicId:ce.targetEpicId,graphRevision:ce.graphRevision,adapterId:ce.adapterId,approvedScreens:ke.screens,allowedPaths:ke.paths})}
114
115
  Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
115
- `:dt?`${et}
116
+ `:lt?`${rt}
116
117
 
117
118
  Private property-test handoff (local only):
118
- ${JSON.stringify({language:Xe.language,numRuns:Xe.numRuns,aggregates:Xe.aggregates.map(D=>({name:D.name,implementationFile:D.implementationFile,testFile:D.testFile,invariantCount:D.invariantCount}))})}
119
+ ${JSON.stringify({language:Ke.language,numRuns:Ke.numRuns,aggregates:Ke.aggregates.map(L=>({name:L.name,implementationFile:L.implementationFile,testFile:L.testFile,invariantCount:L.invariantCount}))})}
119
120
  Read the PRD and implementation files inside this isolated clone. Write exactly the listed test files. Do not edit the PRD, state, Git, QA records or any other path. Scaffolds with unfinished assertions must fail explicitly; do not use skipped or todo tests. The root will write the confirmed PRD configuration and independently assess QA.
120
- `:et;let pe=ie;if(G){const{readPrivateYoloFrozenWriteSet:D}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:A}=await import("../private-execution/frozen-handoff.js"),Re=await D(s,ze,ae.executionBranch,ae.graphRevision);pe=A(ie,Re);const{resumePrivateYoloIsolatedSession:pt}=await import("../private-execution/isolated-session.js"),Me=await pt(s,ze,ae.graphRevision),Se=hn(s,{epicAware:!0}).stories[ze],ve=O.stories[ze];if(!Se||!ve||Se.status!==ve.status||JSON.stringify(Se.steps_completed)!==JSON.stringify(ve.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const tt=je("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();pe+=`
121
+ `:rt;let ue=re;if(F){const{readPrivateYoloFrozenWriteSet:L}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:R}=await import("../private-execution/frozen-handoff.js"),Ae=await L(s,Xe,ne.executionBranch,ne.graphRevision);ue=R(re,Ae);const{resumePrivateYoloIsolatedSession:ht}=await import("../private-execution/isolated-session.js"),je=await ht(s,Xe,ne.graphRevision),Ce=fn(s,{epicAware:!0}).stories[Xe],we=O.stories[Xe];if(!Ce||!we||Ce.status!==we.status||JSON.stringify(Ce.steps_completed)!==JSON.stringify(we.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const at=Ve("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ue+=`
121
122
  Root physical dispatch observations (data, not phase completion):
122
- `+JSON.stringify({storyId:ze,graphRevision:ae.graphRevision,sourceHeadSha:tt,privateSnapshotSha:Me.snapshotSha,effectiveStatus:Se.status,hostKind:"codex-cli",hostVersion:z.hostVersion})+`
123
+ `+JSON.stringify({storyId:Xe,graphRevision:ne.graphRevision,sourceHeadSha:at,privateSnapshotSha:je.snapshotSha,effectiveStatus:Ce.status,hostKind:"codex-cli",hostVersion:Z.hostVersion})+`
123
124
  Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
124
- `}const H=await R(pe,z,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...G?{expectedExecutionBranch:ae.executionBranch}:Et?{expectedExecutionBranch:Et.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(G){const{admitPrivateYoloIsolatedSessionStep:D}=await import("../private-execution/isolated-session.js"),A=await D(s,ze,ae.graphRevision);let Re;if(g.data.metadata.stepId===Aa){const Me=g.data.metadata.mutationQaFeature;if(!Me)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Me.enabled)Re={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Se,ve;try{const tt=A.session.workspace.workspacePath,kt=`sha:${A.session.workspace.baseSha}`,{planMutationQa:Zt}=await import("./mutation-qa.js"),St=Zt(tt,kt);if(St.headSha!==A.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let vt="not-run";if(St.outcome==="ready"){const{runAndRecordMutationQa:wn}=await import("./mutation-qa-checkpoint.js");if(vt=wn(tt,kt,St.planSha256).result.outcome,vt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Cn}=await import("./mutation-qa-gate.js");if(Se=Cn(tt,kt,St.planSha256),Se.followUpDebtRequired){const{recordMutationQaFollowUpDebt:wn}=await import("./mutation-qa-checkpoint.js");ve=wn(tt,kt,St.planSha256,Se.status,vt,s)}const{resumePrivateYoloIsolatedSession:ma}=await import("../private-execution/isolated-session.js");if((await ma(s,ze,ae.graphRevision)).snapshotSha!==A.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Se.blocksLocalQa||!Se.safeToContinueLocalQa&&!ve)throw new Error(`private-execution-mutation-qa-${Se.status}`);Re={...Se,...ve?{followUpDebt:{status:"recorded",owner:ve.owner,severity:ve.severity,reasonCode:ve.reasonCode,planSha256:ve.planSha256,publicSafe:!0}}:{}}}}const pt={schemaVersion:1,outcome:A.admission.outcome,sequence:A.session.sequence,snapshotSha:A.session.snapshotSha,patchSha256:A.admission.patchSha256,changedPathCount:A.admission.changedPaths.length};Q={...H,isolation:pt,...Re?{mutationQa:Re}:{}}}else if(Et){const{admitPrivateEpicClaimWorkspace:D,admitPrivateIdeaDiagnosisWorkspace:A}=await import("../private-execution/isolated-admission.js"),Re=fe?A(Et,Le.claimId,Le.epicId,me.fingerprint,vn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):D(Et,Le.claimId,Le.epicId,me.fingerprint,vn);Q={...H,isolation:{schemaVersion:1,outcome:Re.outcome,baseSha:Re.baseSha,patchSha256:Re.patchSha256,changedPathCount:Re.changedPaths.length}}}else if(se&&Ne){const{admitPrivateIdeaResearchWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,oe.claimId,oe.epicId,oe.diagnosisReceiptId,oe.intakeRevision,oe.sourceStateSha256);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(se&&he){const{admitPrivateGenerateEpicWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,ce.claimId,ce.epicId,ce.diagnosisReceiptId,ce.researchReceiptId,ce.intakeRevision,ce.sourceStateSha256);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(se&&Ze){const{admitPrivatePactWorkspace:D}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:A}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Re}=await import("../private-execution/pact-consumer-runtime.js"),pt=ee.answers.generateProvider,Me=D(se,k.targetEpicId,k.graphRevision,ee.receipt,We,Kn),Se=A(s,pt),ve=Re(s,We,pt);Q={...H,isolation:{schemaVersion:1,outcome:Me.outcome,baseSha:Me.baseSha,patchSha256:Me.patchSha256,changedPathCount:Me.changedPaths.length,consumerBindingCandidateCount:Me.consumerBindingCandidateCount,consumerScaffoldCount:Me.consumerScaffoldCount,toolchain:Se,consumerRuntime:ve}}}else if(se&&st){const{admitPrivateUxWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,J.targetEpicId,J.graphRevision,Pe);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(se&&dt){const{admitPrivatePropertyTestWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,yt,Xe);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(se&&ct){const{admitPrivateArchitectureStageWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,Ee,In,Qt,Xt);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(se&&qe){const{admitPrivateProjectStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,Sn,Yn);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(se){const{admitPrivateStateBoundStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),A=D(se,g.data.metadata.storyId);Q={...H,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else Q={...H}}}catch(c){const d=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:d,errorCode:d,exitCode:1}}let En;if(ot&&u(g.data.metadata.planningRootContinuation)&&g.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!ge?.claimId||!ge.epicId||!Te)throw new Error("missing-reservation");const c=ir(s,ge.claimId,ge.epicId);if(g.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=hn(s,{verifyPlanningGeneration:!0}),y=d.epics[ge.epicId];if(!u(y?.createEpicPlanningMemoryPhysical)||y.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const R={config:{project_id:Te},epics:{[ge.epicId]:y},stories:Object.fromEntries((Array.isArray(y.stories)?y.stories:[]).map(ue=>[ue,d.stories[ue]])),epic_id_ledger:d.epic_id_ledger};if(!await f.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>la(I,j.token,{claimId:ge.claimId,projectId:Te,epicId:ge.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:R}},{refreshToken:()=>j.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");En={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const Kt=sn(g.data.instructions,g.data.metadata),Pt=Q?.isolation,fa=Kt.metadata?.resolvedTrigger==="property-test"&&Pt!==null&&typeof Pt=="object"&&!Array.isArray(Pt)&&Pt.outcome==="admitted-unverified"&&Pt.checkpointAccepted===!1&&Pt.rootNextAction==="property-semantic-review-required";if(me&&!Yt&&!ot&&g.data.metadata?.mode!=="error")try{const c=g.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const d=c;if(d.outcome!=="reserved"||typeof d.claimId!="string"||typeof d.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");f.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Or(s,me.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return f.complete(Tt),{success:!0,instructions:Q?Q.outcome==="checkpoint-validated"?`# Checkpoint da story validado
125
+ `}const G=await b(ue,Z,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...F?{expectedExecutionBranch:ne.executionBranch}:Ct?{expectedExecutionBranch:Ct.executionBranch}:de?{expectedExecutionBranch:de.executionBranch}:{}});if(F){const{admitPrivateYoloIsolatedSessionStep:L}=await import("../private-execution/isolated-session.js"),R=await L(s,Xe,ne.graphRevision);let Ae;if(f.data.metadata.stepId===ka){const je=f.data.metadata.mutationQaFeature;if(!je)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!je.enabled)Ae={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Ce,we;try{const at=R.session.workspace.workspacePath,Ot=`sha:${R.session.workspace.baseSha}`,{planMutationQa:Zt}=await import("./mutation-qa.js"),_t=Zt(at,Ot);if(_t.headSha!==R.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Rt="not-run";if(_t.outcome==="ready"){const{runAndRecordMutationQa:Rn}=await import("./mutation-qa-checkpoint.js");if(Rt=Rn(at,Ot,_t.planSha256).result.outcome,Rt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:_n}=await import("./mutation-qa-gate.js");if(Ce=_n(at,Ot,_t.planSha256),Ce.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Rn}=await import("./mutation-qa-checkpoint.js");we=Rn(at,Ot,_t.planSha256,Ce.status,Rt,s)}const{resumePrivateYoloIsolatedSession:va}=await import("../private-execution/isolated-session.js");if((await va(s,Xe,ne.graphRevision)).snapshotSha!==R.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Ce.blocksLocalQa||!Ce.safeToContinueLocalQa&&!we)throw new Error(`private-execution-mutation-qa-${Ce.status}`);Ae={...Ce,...we?{followUpDebt:{status:"recorded",owner:we.owner,severity:we.severity,reasonCode:we.reasonCode,planSha256:we.planSha256,publicSafe:!0}}:{}}}}const ht={schemaVersion:1,outcome:R.admission.outcome,sequence:R.session.sequence,snapshotSha:R.session.snapshotSha,patchSha256:R.admission.patchSha256,changedPathCount:R.admission.changedPaths.length};te={...G,isolation:ht,...Ae?{mutationQa:Ae}:{}}}else if(Ct){const{admitPrivateEpicClaimWorkspace:L,admitPrivateIdeaDiagnosisWorkspace:R}=await import("../private-execution/isolated-admission.js"),Ae=Ee?R(Ct,Me.claimId,Me.epicId,ve.fingerprint,wn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):L(Ct,Me.claimId,Me.epicId,ve.fingerprint,wn);te={...G,isolation:{schemaVersion:1,outcome:Ae.outcome,baseSha:Ae.baseSha,patchSha256:Ae.patchSha256,changedPathCount:Ae.changedPaths.length}}}else if(de&&Le){const{admitPrivateIdeaResearchWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,le.claimId,le.epicId,le.diagnosisReceiptId,le.intakeRevision,le.sourceStateSha256);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(de&&me){const{admitPrivateGenerateEpicWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,ie.claimId,ie.epicId,ie.diagnosisReceiptId,ie.researchReceiptId,ie.intakeRevision,ie.sourceStateSha256);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(de&&nt){const{admitPrivatePactWorkspace:L}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:R}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Ae}=await import("../private-execution/pact-consumer-runtime.js"),ht=oe.answers.generateProvider,je=L(de,z.targetEpicId,z.graphRevision,oe.receipt,j,er),Ce=R(s,ht),we=Ae(s,j,ht);te={...G,isolation:{schemaVersion:1,outcome:je.outcome,baseSha:je.baseSha,patchSha256:je.patchSha256,changedPathCount:je.changedPaths.length,consumerBindingCandidateCount:je.consumerBindingCandidateCount,consumerScaffoldCount:je.consumerScaffoldCount,toolchain:Ce,consumerRuntime:we}}}else if(de&&ut){const{admitPrivateUxWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,ce.targetEpicId,ce.graphRevision,ke);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(de&&lt){const{admitPrivatePropertyTestWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,It,Ke);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(de&&pt){const{admitPrivateArchitectureStageWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,Ie,vn,Qt,Xt);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(de&&Qe){const{admitPrivateProjectStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,Cn,Zn);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(de){const{admitPrivateStateBoundStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(de,f.data.metadata.storyId);te={...G,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else te={...G}}}catch(c){const d=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:d,errorCode:d,exitCode:1}}let Sn;if(Pt&&l(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!he?.claimId||!he.epicId||!Ne)throw new Error("missing-reservation");const c=dr(s,he.claimId,he.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=fn(s,{verifyPlanningGeneration:!0}),m=d.epics[he.epicId];if(!l(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const b={config:{project_id:Ne},epics:{[he.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(fe=>[fe,d.stories[fe]])),epic_id_ledger:d.epic_id_ledger};if(!await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ya(w,$.token,{claimId:he.claimId,projectId:Ne,epicId:he.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:b}},{refreshToken:()=>$.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Sn={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const Kt=dn(f.data.instructions,f.data.metadata),kt=te?.isolation,Sa=Kt.metadata?.resolvedTrigger==="property-test"&&kt!==null&&typeof kt=="object"&&!Array.isArray(kt)&&kt.outcome==="admitted-unverified"&&kt.checkpointAccepted===!1&&kt.rootNextAction==="property-semantic-review-required";if(ve&&!Xn&&!Pt&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const d=c;if(d.outcome!=="reserved"||typeof d.claimId!="string"||typeof d.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>jr(s,ve.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return p.complete(vt),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
125
126
 
126
- O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:Q.outcome==="setup-accepted"?`# Setup do branch validado
127
+ O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:te.outcome==="setup-accepted"?`# Setup do branch validado
127
128
 
128
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:Q.outcome==="report-stored"?`# Relat\xF3rio privado salvo
129
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:te.outcome==="report-stored"?`# Relat\xF3rio privado salvo
129
130
 
130
- Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:fa?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
131
+ Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Sa?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
131
132
 
132
- O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Kt.instructions,metadata:Q?{...Kt.metadata,privateExecutionReceipt:Q}:{...Kt.metadata,...En?{planningMaterialization:En}:{}},exitCode:0}}function fc(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":bn(t):null}const ha="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",mc=`
133
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Kt.instructions,metadata:te?{...Kt.metadata,privateExecutionReceipt:te}:{...Kt.metadata,...Sn?{planningMaterialization:Sn}:{}},exitCode:0}}function Cc(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":rn(t):null}const Ea="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",wc=`
133
134
  neocortex-client invoke - Send orchestration request to server
134
135
 
135
136
  Usage:
@@ -200,12 +201,12 @@ Safety:
200
201
  Jobs console is Plane B/local-only: no hosted server call for raw output, no server-held stream, no raw persistence, and stdin requires explicit local confirmation.
201
202
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
202
203
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
203
- `.trim();function yc(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function xe(e,t,a,r){return new dn("INVOCATION_MALFORMED_INPUT",t,e,a,r)}function Rt(e){return xe("missing-input-value",`${e} requires a value. ${ha}`)}function Ec(e){try{if(!va(e).isFile())throw xe("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ve(e)}catch(t){throw t instanceof dn?t:xe("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Ic(){try{if(process.stdin.isTTY)throw xe("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ve(0)}catch(e){throw e instanceof dn?e:xe("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Sc(e,t={}){let a,r=!1,i,n,o="plain",s=!1,p,m,S=!1,_=!1,l;for(let P=0;P<e.length;P++)switch(e[P]){case"--args":{const I=e[++P];if(I===void 0)throw Rt("--args");if(a!==void 0)throw xe("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");a=I;break}case"--stdin":if(r)throw xe("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const I=e[++P];if(I===void 0)throw Rt("--args-file");if(i!==void 0)throw xe("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");i=I;break}case"--project-root":{const I=e[++P];if(I===void 0)throw Rt("--project-root");n=I;break}case"--format":{const I=e[++P];if(I===void 0)throw Rt("--format");if(I!=="json"&&I!=="plain")throw xe("unexpected-cli-token","--format accepts only json or plain.");o=I;break}case"--watch":s=!0;break;case"--server-url":{const I=e[++P];if(I===void 0)throw Rt("--server-url");p=I;break}case"--platform-target":{const I=e[++P];if(I===void 0)throw Rt("--platform-target");m=I;break}case"--strict-read-only":S=!0;break;case"--private-execution-beta":_=!0;break;case"--private-execution-model":{const I=e[++P];if(I===void 0)throw Rt("--private-execution-model");if(l!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(I))throw xe("unexpected-cli-token","Invalid or duplicate private execution model.");l=I;break}default:throw xe("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}if(l!==void 0&&(!_||S))throw xe("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const v=[a!==void 0?"args":void 0,r?"stdin":void 0,i!==void 0?"args-file":void 0].filter(P=>P!==void 0);if(v.length===0)throw xe("missing-input-value",ha);if(v.length>1)throw xe("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const f=v[0],h=f==="args"?a:f==="stdin"?(t.readStdin??Ic)():(t.readArgsFile??Ec)(i);let C;try{C=rn(f,h)}catch(P){throw P instanceof ui?xe("invalid-utf8",P.message,f):P}const N=f==="args"?Xo(C.rawArgs):be(C.rawArgs),L=N.args===C.rawArgs?C:rn(f,N.args);return{args:N.args,inputSource:f,inputEnvelope:L,projectRoot:n,format:o,watch:s||N.watch,commandLevelWatch:N.metadata,serverUrl:p,platformTarget:m,strictReadOnly:S,privateExecutionBeta:_,...l===void 0?{}:{privateExecutionModel:l}}}function ga(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function vc(e,t,a=process.stdout,r=process.stderr){if(t.format==="json"){const o=sn(e.instructions,e.metadata),s=ga(o.metadata,t.commandLevelWatch);if(t.watch){a.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:s,publicSafe:!0})+`
204
- `);return}a.write(JSON.stringify({instructions:o.instructions,metadata:s})+`
205
- `);return}const i=sn(e.instructions,e.metadata),n=ga(i.metadata,t.commandLevelWatch);a.write(i.instructions+`
206
- `),n&&r.write(JSON.stringify(n)+`
207
- `)}async function Cs(e=process.stdout,t=process.stderr){const a=i=>new Promise(n=>{let o=!1;const s=S=>{o||(o=!0,clearTimeout(m),setImmediate(()=>i.removeListener("error",p)),n(S))},p=()=>s(!1),m=setTimeout(()=>s(!1),1e4);i.once("error",p);try{i.write("",S=>s(!S))}catch{s(!1)}});return(await Promise.all([a(e),a(t)])).every(Boolean)}function Cc(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function ws(e){if(yc(e))return process.stdout.write(`${mc}
208
- `),0;let t;try{t=Sc(e)}catch(r){if(r instanceof dn)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
209
- `),1;throw r}if(Ya(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
210
- `),1):(await Ka({args:t.args,projectRoot:On(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const a=await gc({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}});if(!a.success){const r=a.metadata?.invocationInput,i=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:a.errorCode??(a.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:He(a.error??"",_t),...typeof i?.reason=="string"?{reason:He(i.reason,80)}:{},...typeof i?.source=="string"?{source:He(i.source,20)}:{},...Number.isSafeInteger(i?.byteLength)?{byte_length:i.byteLength}:{},...typeof i?.remediation=="string"?{remediation:He(i.remediation,_t)}:{}})+`
211
- `),a.exitCode}if(vc(a,t),t.watch){const r=new AbortController,i=Cc(r);try{const n=dc(a.metadata,t.args);n.disabled?Bo(n.reasonCodes??[Ie.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await $o({projectRoot:On(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{i()}}return 0}export{mc as INVOKE_HELP_TEXT,br as INVOKE_PAYLOAD_LIMIT_BYTES,Pn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,dn as InvokeCliInputError,Dn as InvokePayloadTooLargeError,Ln as InvokeStructuralContextTooLargeError,gt as StateSnapshotIntegrityError,Ss as __resetSchemaDriftWarnedForTests,lc as acknowledgeMaterializedPendingEpicClaims,Vi as admitClientInvocation,Fr as assertEpicAwareStateShapeBeforeRepair,po as boundedP222PremergeCheckpointPositions,Io as buildSignedInvokeAttempt,Mi as clearPendingEpicIdempotencyKey,uo as collectInvokeP205Authorities,hn as collectStateSnapshot,Vt as computeInvokeRequestBodySizeBytes,vs as createFullStateSnapshotScope,$n as createInvokePayloadTelemetry,zi as detectStateSchemaDrift,fc as extractPreFlightTrigger,Cs as flushInvokeCliOutput,Li as getOrCreatePendingEpicIdempotencyKey,ea as guardInvokeRequestBodySize,gc as invoke,ws as invokeCliHandler,Hr as isEpicAwareCommandId,xo as maybeEmitInvokePayloadSizeWarning,To as maybeRunInvokeRunnerAutoBootstrap,Sc as parseInvokeCliOptions,Xr as postMaterializationJson,Or as recordPendingEpicReservation,Xo as resolveInvokeCommandLevelWatch,On as resolveInvokeProjectRoot,mo as resolveInvokeTransportErrorCode,dc as resolveInvokeWatchTarget,sn as sanitizeInvokeCliOutput,la as sendEpicClaimAcknowledgement,ua as sendInvokeRequest,uc as sendPrivateExecutionCancelRequest,pc as sendPrivateExecutionConsumeRequest,Gi as shouldCollectProjectEvidenceForInvoke,$o as watchContinuityProcessingSummaries,vc as writeInvokeCliSuccessOutput};
204
+ `.trim();function _c(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Te(e,t,r,a){return new pn("INVOCATION_MALFORMED_INPUT",t,e,r,a)}function Tt(e){return Te("missing-input-value",`${e} requires a value. ${Ea}`)}function Rc(e){try{if(!Aa(e).isFile())throw Te("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ue(e)}catch(t){throw t instanceof pn?t:Te("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Ac(){try{if(process.stdin.isTTY)throw Te("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ue(0)}catch(e){throw e instanceof pn?e:Te("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function bc(e,t={}){let r,a=!1,i,n,o="plain",s=!1,u,g,S=!1,_=!1,h;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const I=e[++T];if(I===void 0)throw Tt("--args");if(r!==void 0)throw Te("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");r=I;break}case"--stdin":if(a)throw Te("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");a=!0;break;case"--args-file":{const I=e[++T];if(I===void 0)throw Tt("--args-file");if(i!==void 0)throw Te("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");i=I;break}case"--project-root":{const I=e[++T];if(I===void 0)throw Tt("--project-root");n=I;break}case"--format":{const I=e[++T];if(I===void 0)throw Tt("--format");if(I!=="json"&&I!=="plain")throw Te("unexpected-cli-token","--format accepts only json or plain.");o=I;break}case"--watch":s=!0;break;case"--server-url":{const I=e[++T];if(I===void 0)throw Tt("--server-url");u=I;break}case"--platform-target":{const I=e[++T];if(I===void 0)throw Tt("--platform-target");g=I;break}case"--strict-read-only":S=!0;break;case"--private-execution-beta":_=!0;break;case"--private-execution-model":{const I=e[++T];if(I===void 0)throw Tt("--private-execution-model");if(h!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(I))throw Te("unexpected-cli-token","Invalid or duplicate private execution model.");h=I;break}default:if(r!==void 0&&P&&(!P.startsWith("-")||P==="-")){r+=` ${P}`;break}throw Te("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(h!==void 0&&(!_||S))throw Te("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const v=[r!==void 0?"args":void 0,a?"stdin":void 0,i!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(v.length===0)throw Te("missing-input-value",Ea);if(v.length>1)throw Te("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const y=v[0],p=y==="args"?r:y==="stdin"?(t.readStdin??Ac)():(t.readArgsFile??Rc)(i);let C;try{C=an(y,p)}catch(T){throw T instanceof mi?Te("invalid-utf8",T.message,y):T}const k=y==="args"?ic(C.rawArgs):xe(C.rawArgs),V=k.args===C.rawArgs?C:an(y,k.args);return{args:k.args,inputSource:y,inputEnvelope:V,projectRoot:n,format:o,watch:s||k.watch,commandLevelWatch:k.metadata,serverUrl:u,platformTarget:g,strictReadOnly:S,privateExecutionBeta:_,...h===void 0?{}:{privateExecutionModel:h}}}function Ia(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function xc(e,t,r=process.stdout,a=process.stderr){if(t.format==="json"){const o=dn(e.instructions,e.metadata),s=Ia(o.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:s,publicSafe:!0})+`
205
+ `);return}r.write(JSON.stringify({instructions:o.instructions,metadata:s})+`
206
+ `);return}const i=dn(e.instructions,e.metadata),n=Ia(i.metadata,t.commandLevelWatch);r.write(i.instructions+`
207
+ `),n&&a.write(JSON.stringify(n)+`
208
+ `)}async function Os(e=process.stdout,t=process.stderr){const r=i=>new Promise(n=>{let o=!1;const s=S=>{o||(o=!0,clearTimeout(g),setImmediate(()=>i.removeListener("error",u)),n(S))},u=()=>s(!1),g=setTimeout(()=>s(!1),1e4);i.once("error",u);try{i.write("",S=>s(!S))}catch{s(!1)}});return(await Promise.all([r(e),r(t)])).every(Boolean)}function Tc(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Ns(e){if(_c(e))return process.stdout.write(`${wc}
209
+ `),0;let t;try{t=bc(e)}catch(a){if(a instanceof pn)return process.stderr.write(JSON.stringify({error_code:a.code,reason:a.reason,source:a.source,byte_length:a.byteLength,message:a.message,remediation:a.message})+`
210
+ `),1;throw a}if(Za(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
211
+ `),1):(await ei({args:t.args,projectRoot:Ln(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await vc({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}});if(!r.success){const a=r.metadata?.invocationInput,i=a&&typeof a=="object"&&!Array.isArray(a)?a:void 0;return process.stderr.write(JSON.stringify({error_code:r.errorCode??(r.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:ze(r.error??"",xt),...typeof i?.reason=="string"?{reason:ze(i.reason,80)}:{},...typeof i?.source=="string"?{source:ze(i.source,20)}:{},...Number.isSafeInteger(i?.byteLength)?{byte_length:i.byteLength}:{},...typeof i?.remediation=="string"?{remediation:ze(i.remediation,xt)}:{}})+`
212
+ `),r.exitCode}if(xc(r,t),t.watch){const a=new AbortController,i=Tc(a);try{const n=mc(r.metadata,t.args);n.disabled?Yo(n.reasonCodes??[Se.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await zo({projectRoot:Ln(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:a.signal})}finally{i()}}return 0}export{wc as INVOKE_HELP_TEXT,Or as INVOKE_PAYLOAD_LIMIT_BYTES,On as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,pn as InvokeCliInputError,Mn as InvokePayloadTooLargeError,jn as InvokeStructuralContextTooLargeError,it as StateSnapshotIntegrityError,Ps as __resetSchemaDriftWarnedForTests,Ic as acknowledgeMaterializedPendingEpicClaims,Fi as admitClientInvocation,Bn as assertEpicAwareStateShapeBeforeRepair,Eo as boundedP222PremergeCheckpointPositions,Ao as buildSignedInvokeAttempt,Hi as clearPendingEpicIdempotencyKey,Io as collectInvokeP205Authorities,fn as collectStateSnapshot,Ut as computeInvokeRequestBodySizeBytes,ks as createFullStateSnapshotScope,Hn as createInvokePayloadTelemetry,to as detectStateSchemaDrift,Cc as extractPreFlightTrigger,Os as flushInvokeCliOutput,Wi as getOrCreatePendingEpicIdempotencyKey,ia as guardInvokeRequestBodySize,vc as invoke,Ns as invokeCliHandler,Jr as isEpicAwareCommandId,Do as maybeEmitInvokePayloadSizeWarning,Mo as maybeRunInvokeRunnerAutoBootstrap,bc as parseInvokeCliOptions,ra as postMaterializationJson,jr as recordPendingEpicReservation,ic as resolveInvokeCommandLevelWatch,Ln as resolveInvokeProjectRoot,wo as resolveInvokeTransportErrorCode,mc as resolveInvokeWatchTarget,dn as sanitizeInvokeCliOutput,ya as sendEpicClaimAcknowledgement,ma as sendInvokeRequest,Ec as sendPrivateExecutionCancelRequest,yc as sendPrivateExecutionConsumeRequest,Qi as shouldCollectProjectEvidenceForInvoke,zo as watchContinuityProcessingSummaries,xc as writeInvokeCliSuccessOutput};