@ornexus/neocortex 4.60.72 → 4.60.74

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 (46) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1217 -1211
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/invoke.js +66 -66
  7. package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
  8. package/packages/client/dist/continuity/sqlite-store.js +60 -60
  9. package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
  10. package/packages/client/dist/git/epic-operational-state.js +2 -0
  11. package/packages/client/dist/git/git-lifecycle-store.d.ts +32 -1
  12. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  13. package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
  14. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -0
  15. package/packages/client/dist/migrations/state-json.d.ts +22 -0
  16. package/packages/client/dist/migrations/state-json.js +4 -4
  17. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  18. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -2
  19. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  20. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -8
  21. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  22. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -2
  23. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  24. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  25. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  26. package/packages/client/dist/runner/headless/types.js +2 -2
  27. package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
  28. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  29. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  30. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
  31. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
  32. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  33. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  34. package/packages/shared/dist/yolo/spec-envelope.js +3 -6
  35. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  36. package/targets-stubs/antigravity/gemini.md +1 -1
  37. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  38. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  39. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  40. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  41. package/targets-stubs/claude-code/neocortex.md +2 -2
  42. package/targets-stubs/codex/AGENTS.md +1 -1
  43. package/targets-stubs/cursor/agent.md +2 -2
  44. package/targets-stubs/gemini-cli/agent.md +2 -2
  45. package/targets-stubs/opencode/neocortex-root.md +1 -1
  46. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,54 +1,54 @@
1
- import{classifyNonUiArchitectureTransition as Aa,architectureMemoryPredecessorCount as or}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as cr}from"./shared-architecture-non-ui.js";import{createHash as Ve,randomUUID as nn}from"node:crypto";import{loadPactAnswerReceipt as sr,loadPactPrivateAnswers as ba}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Gt,deriveArchitectureTerminalMemoryReceipt as xn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Wt,explicitArchitectureEpicTarget as xa}from"./architecture-root-binding.js";import{derivePactWriteSet as Ta}from"../private-execution/pact-write-set.js";import{execFileSync as Ue}from"node:child_process";import{existsSync as Nt,readFileSync as Be,renameSync as dr,unlinkSync as Tn,writeFileSync as rn,mkdirSync as Ht,statSync as Pa,openSync as Ft,closeSync as qt,fsyncSync as an,realpathSync as ka,lstatSync as Lt}from"node:fs";import{isDeepStrictEqual as E}from"node:util";import{join as z,isAbsolute as Oa,resolve as Pn}from"node:path";import{homedir as Yt}from"node:os";import{isPrivateExecutionPublicEnvelope as Na,isPrivatePlanningRootPublicEnvelope as La,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Da}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as pr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as ur}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as lr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Ma}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as ja}from"../../../shared/dist/planning/diagnosis-state.js";import{LicenseClient as Va}from"../license/license-client.js";import{EncryptedCache as kn}from"../cache/encrypted-cache.js";import{NoOpCache as hr}from"../types/index.js";import{resolveClientPreFlightTrigger as on,TierAwareClient as Ua}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as gt,COMMAND_REGISTRY_VERSION as mt,GENERATED_CLIENT_COMMANDS as Ba}from"../generated/command-registry.generated.js";import{loadSecureConfig as On}from"../config/secure-config.js";import{neocortexProfileDirectory as $a}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as Ga}from"../constants.js";import{detectFirstRunLocale as Wa,renderFirstRunMessage as Ha}from"../i18n/first-run.js";import{humanizeError as fr,formatHumanizedError as gr,detectErrorLocale as mr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Fa,projectStateSnapshotForInvoke as yr,projectStateSnapshotResultV2ForInvoke as qa}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Ir,maybeRepairStateJsonBeforeInvoke as Ya,StateRepairHardStopError as Ja}from"../state/state-json-repair.js";import{StructuralDagError as Er}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as za,StateMigrationApplyError as Ka}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Qa,classifyRunnerBootstrapPolicyFromArgs as Xa}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Za,ensureRunnerSchedulerBootstrap as ei,observeRunnerOperationalStatus as ti}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Sr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as vr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Cr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as wr,openContinuityClientStateStore as ni}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ri,runLocalJobsConsoleCommand as ai}from"../runner/local-console.js";import{detectNativeHostAttestation as ii,detectPlatform as oi}from"../adapters/platform-detector.js";import{signNxInvokeRequest as ci}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as si}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as di}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as xt}from"../version.js";import{createCapabilityCache as _r,executeInvokeQueryTransport as Rr,executeSecondaryNetworkMutation as pi}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as ui,STRICT_READ_ONLY_CLIENT_PROJECTION as Ar,STRICT_READ_ONLY_SERVER_PROJECTION as li,StrictReadOnlyError as Dt,canonicalizeInvokeEffects as hi,createInvokeEffectContext as fi,verifyStrictReadOnlyReceipt as gi}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as mi,assertInvokeInputEnvelopeV2 as yi,assertProjectIdentityMigrationReceiptV1 as Ii,buildProjectIdentityPublicDiagnostic as Mt,createInvocationAdmissionReceipt as Ei,projectInvokeInputEvidenceV1 as br,verifyStrictDiagnoseReceiptV1 as Si}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as cn,InvokeInputDecodeError as vi}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as jt,createCompatibilityOffer as Ci,createLegacyCompatibilityResult as wi,isCompatibilityResultV1 as _i}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ri,finalizeProjectIdentityMigration as Ai,prepareProjectIdentityMigration as bi,ProjectIdentityMigrationError as Nn,readProjectIdentityMigrationPhase as xi}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Ti}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Pi}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as sn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as xr,classifyGitLifecycleStoryCheckpointProjectionSync as ki,ensureGitLifecycleRuntimeInitialized as Oi,executeP205TransientAuthorities as Ni,persistGitLifecycleGraphAuthority as Li,P205_COMPLETE_COMMAND as Di,gitLifecycleStoryWriteSet as Tr,readGitLifecycleRuntimeSync as dn,verifyLegacyCheckpointMigrationCandidateSync as Mi}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as ji}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Vi}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Ui}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as Pr,extractTargetedYoloStoryId as Bi,refreshPrecollectedYoloSpecEnvelope as $i}from"../yolo/spec-envelope-collector.js";const pn=$a(),Ln=z(pn,"cache"),kr=z(Ln,"menu-cache.json"),Or=1440*60*1e3,Nr=3e4,Lr=256*1024,Dr=Lr,Mr=.8,yt="[REDACTED]",Gi=1e5,Tt=2e3,Wi=200,Hi=200,Fi=12,qi=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Yi=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Ji=/(?: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,Dn=Math.floor(Lr*Mr),jr=z(pn,".first-run-shown"),zi="pending-epic-claims.json",Vr=64;function Ur(e){return z(e,".neocortex",zi)}function Vt(e){const t=Ur(e);if(!Nt(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(Be(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>Vr)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 Mn(e,t){const r=Ur(e);Ht(z(e,".neocortex"),{recursive:!0,mode:448});const a=`${r}.${process.pid}.${nn()}.tmp`;rn(a,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),dr(a,r)}function Ki(e,t){return Ve("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Qi(e,t,r="create-epic"){const a=Ki(t,r),i=Vt(e),n=i.operations[a];if(n)return{key:n.idempotencyKey,fingerprint:a};if(Object.keys(i.operations).length>=Vr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=nn(),s={...i.operations,[a]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Mn(e,{schemaVersion:1,operations:s}),{key:o,fingerprint:a}}function Xi(e,t){const r=Vt(e);if(!r.operations[t])return;const a={...r.operations};delete a[t],Mn(e,{schemaVersion:1,operations:a})}function Zi(e,t,r,a){const i=a.scope?.targetStoryId??a.current_session?.active_story_id??null,n=a.scope?.targetEpicId??a.current_session?.active_epic_id??null,o=i?a.stories[i]:void 0,s=Array.isArray(o?.steps_completed)?o.steps_completed.filter(y=>typeof y=="string"):[],u=r??Ve("sha256").update(`nx-yolo-project-path-v1\0${Pn(e)}`,"utf8").digest("hex"),g=JSON.stringify({projectBinding:u,args:t,storyId:i,epicId:n,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:s});return`yolo-${Ve("sha256").update(`nx-yolo-logical-operation-v1\0${g}`,"utf8").digest("hex")}`}function Br(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");Mn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:r,epicId:a,...i?{planningProtocol:i}:{}}}})}function eo(){try{if(Nt(jr))return;const e=Wa(),t=Ha(e);process.stderr.write(t);try{Ht(pn,{recursive:!0}),rn(jr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function jn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function to(e){if(e==="REGISTRY_PROJECTION_DRIFT")return{success:!1,error:'REGISTRY_RECONCILIATION_REQUIRED: the installed client registry was rejected. Run `neocortex-client reconcile-registry --project-root "$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)" --check-latest`, then retry.',errorCode:"REGISTRY_RECONCILIATION_REQUIRED",metadata:{registryReconciliation:{reasonCode:"REGISTRY_RECONCILIATION_REQUIRED",authority:"local-and-public-npm-only",publicSafe:!0}},exitCode:1}}function no(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const a=di(t.releaseBlocked);return!a||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:a},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function ro(e){return mi(e,{registryVersion:mt,registryChecksum:gt})}const ao=new Set(["completed","aborted","cancelled"]),io=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"}),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"}),$r=240,oo=/(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 co(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,yt).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,yt).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,yt).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,yt).replace(Yi,yt).replace(Ji,yt)}function Je(e,t){const r=co(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function Vn(e,t=0,r=new WeakSet){if(t>Fi)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Je(e,Tt);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,Wi).map(i=>Vn(i,t+1,r));const a={};for(const[i,n]of Object.entries(e).slice(0,Hi)){if(qi.test(i)){a[i]=yt;continue}const o=Vn(n,t+1,r);o!==void 0&&(a[i]=o)}return a}finally{r.delete(e)}}}function un(e,t){return{instructions:Je(e??"",Gi),metadata:t?Vn(t):void 0}}class ln 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 so(e){const t=on(e);return(t==="arch-plan"||t==="ui-ux-review")&&po(e,"--project-evidence")}function po(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 uo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function lo(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 Ue("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(uo)?.[1]??null}catch{return null}}function Un(){return Ci({clientVersion:xt,registryVersion:mt,registryChecksum:gt})}class Bn 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 $n 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 Gn=!1;function ho(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 fo(e){if(!(Gn||e.length===0)){Gn=!0;try{const t=e.map(r=>` - ${r.message}`).join(`
1
+ import{classifyNonUiArchitectureTransition as xi,architectureMemoryPredecessorCount as or}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as cr}from"./shared-architecture-non-ui.js";import{createHash as Ue,randomUUID as nn}from"node:crypto";import{loadPactAnswerReceipt as sr,loadPactPrivateAnswers as Ti}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ht,deriveArchitectureTerminalMemoryReceipt as xn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Gt,explicitArchitectureEpicTarget as Pi}from"./architecture-root-binding.js";import{derivePactWriteSet as ki}from"../private-execution/pact-write-set.js";import{execFileSync as $e}from"node:child_process";import{existsSync as Nt,readFileSync as He,renameSync as dr,unlinkSync as Tn,writeFileSync as rn,mkdirSync as Wt,statSync as Oi,openSync as Ft,closeSync as qt,fsyncSync as an,realpathSync as Ni,lstatSync as Lt}from"node:fs";import{isDeepStrictEqual as E}from"node:util";import{join as K,isAbsolute as Li,resolve as Pn}from"node:path";import{homedir as Yt}from"node:os";import{isPrivateExecutionPublicEnvelope as Di,isPrivatePlanningRootPublicEnvelope as Mi,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ji}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as pr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as lr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as ur}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Vi}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as Bi}from"../../../shared/dist/planning/diagnosis-state.js";import{LicenseClient as Ui}from"../license/license-client.js";import{EncryptedCache as kn}from"../cache/encrypted-cache.js";import{NoOpCache as hr}from"../types/index.js";import{resolveClientPreFlightTrigger as on,TierAwareClient as $i}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as mt,COMMAND_REGISTRY_VERSION as yt,GENERATED_CLIENT_COMMANDS as Hi}from"../generated/command-registry.generated.js";import{loadSecureConfig as On}from"../config/secure-config.js";import{neocortexProfileDirectory as Gi}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as Wi}from"../constants.js";import{detectFirstRunLocale as Fi,renderFirstRunMessage as qi}from"../i18n/first-run.js";import{humanizeError as gr,formatHumanizedError as fr,detectErrorLocale as mr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Yi,projectStateSnapshotForInvoke as yr,projectStateSnapshotResultV2ForInvoke as Ji}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Ir,maybeRepairStateJsonBeforeInvoke as zi,StateRepairHardStopError as Ki}from"../state/state-json-repair.js";import{StructuralDagError as Er}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Qi,StateMigrationApplyError as Xi}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Zi,classifyRunnerBootstrapPolicyFromArgs as ea}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as ta,ensureRunnerSchedulerBootstrap as na,observeRunnerOperationalStatus as ra}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Sr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as vr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Cr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as wr,openContinuityClientStateStore as ia}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as aa,runLocalJobsConsoleCommand as oa}from"../runner/local-console.js";import{detectNativeHostAttestation as ca,detectPlatform as sa}from"../adapters/platform-detector.js";import{signNxInvokeRequest as da}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as pa}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as la}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as xt}from"../version.js";import{createCapabilityCache as _r,executeInvokeQueryTransport as Rr,executeSecondaryNetworkMutation as ua}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as ha,STRICT_READ_ONLY_CLIENT_PROJECTION as Ar,STRICT_READ_ONLY_SERVER_PROJECTION as ga,StrictReadOnlyError as Dt,canonicalizeInvokeEffects as fa,createInvokeEffectContext as ma,verifyStrictReadOnlyReceipt as ya}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ia,assertInvokeInputEnvelopeV2 as Ea,assertProjectIdentityMigrationReceiptV1 as Sa,buildProjectIdentityPublicDiagnostic as Mt,createInvocationAdmissionReceipt as va,projectInvokeInputEvidenceV1 as br,verifyStrictDiagnoseReceiptV1 as Ca}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as cn,InvokeInputDecodeError as wa}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as jt,createCompatibilityOffer as _a,createLegacyCompatibilityResult as Ra,isCompatibilityResultV1 as Aa}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as ba,finalizeProjectIdentityMigration as xa,prepareProjectIdentityMigration as Ta,ProjectIdentityMigrationError as Nn,readProjectIdentityMigrationPhase as Pa}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as ka}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Oa}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as sn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as Na,epicHeadReconciliationPathsDigest as xr,epicHeadReconciliationRangeDigest as La}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Tr,classifyGitLifecycleStoryCheckpointProjectionSync as Da,ensureGitLifecycleRuntimeInitialized as Ma,executeP205TransientAuthorities as ja,persistGitLifecycleGraphAuthority as Va,P205_COMPLETE_COMMAND as Ba,gitLifecycleStoryWriteSet as Pr,readGitLifecycleRuntimeSync as dn,verifyLegacyCheckpointMigrationCandidateSync as Ua}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as $a}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Ha}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Ga}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as kr,extractTargetedYoloStoryId as Wa,refreshPrecollectedYoloSpecEnvelope as Fa}from"../yolo/spec-envelope-collector.js";const pn=Gi(),Ln=K(pn,"cache"),Or=K(Ln,"menu-cache.json"),Nr=1440*60*1e3,Lr=3e4,Dr=256*1024,Mr=Dr,jr=.8,It="[REDACTED]",qa=1e5,Tt=2e3,Ya=200,Ja=200,za=12,Ka=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Qa=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Xa=/(?: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,Dn=Math.floor(Dr*jr),Vr=K(pn,".first-run-shown"),Za="pending-epic-claims.json",Br=64;function Ur(e){return K(e,".neocortex",Za)}function Vt(e){const t=Ur(e);if(!Nt(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(He(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const i=r;if(i.schemaVersion!==1||!i.operations||typeof i.operations!="object"||Array.isArray(i.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(i.operations).length>Br)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(i.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!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 Mn(e,t){const r=Ur(e);Wt(K(e,".neocortex"),{recursive:!0,mode:448});const i=`${r}.${process.pid}.${nn()}.tmp`;rn(i,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),dr(i,r)}function eo(e,t){return Ue("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function to(e,t,r="create-epic"){const i=eo(t,r),a=Vt(e),n=a.operations[i];if(n)return{key:n.idempotencyKey,fingerprint:i};if(Object.keys(a.operations).length>=Br)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=nn(),s={...a.operations,[i]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Mn(e,{schemaVersion:1,operations:s}),{key:o,fingerprint:i}}function no(e,t){const r=Vt(e);if(!r.operations[t])return;const i={...r.operations};delete i[t],Mn(e,{schemaVersion:1,operations:i})}function ro(e,t,r,i){const a=i.scope?.targetStoryId??i.current_session?.active_story_id??null,n=i.scope?.targetEpicId??i.current_session?.active_epic_id??null,o=a?i.stories[a]:void 0,s=Array.isArray(o?.steps_completed)?o.steps_completed.filter(y=>typeof y=="string"):[],l=r??Ue("sha256").update(`nx-yolo-project-path-v1\0${Pn(e)}`,"utf8").digest("hex"),f=JSON.stringify({projectBinding:l,args:t,storyId:a,epicId:n,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:s});return`yolo-${Ue("sha256").update(`nx-yolo-logical-operation-v1\0${f}`,"utf8").digest("hex")}`}function $r(e,t,r,i,a){if(!/^[0-9a-f-]{36}$/.test(r)||!/^P[1-9][0-9]*$/.test(i)||a!==void 0&&a!=="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!==i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Mn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:r,epicId:i,...a?{planningProtocol:a}:{}}}})}function io(){try{if(Nt(Vr))return;const e=Fi(),t=qi(e);process.stderr.write(t);try{Wt(pn,{recursive:!0}),rn(Vr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function jn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function ao(e){if(e==="REGISTRY_PROJECTION_DRIFT")return{success:!1,error:'REGISTRY_RECONCILIATION_REQUIRED: the installed client registry was rejected. Run `neocortex-client reconcile-registry --project-root "$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)" --check-latest`, then retry.',errorCode:"REGISTRY_RECONCILIATION_REQUIRED",metadata:{registryReconciliation:{reasonCode:"REGISTRY_RECONCILIATION_REQUIRED",authority:"local-and-public-npm-only",publicSafe:!0}},exitCode:1}}function oo(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const i=la(t.releaseBlocked);return!i||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:i},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function co(e){return Ia(e,{registryVersion:yt,registryChecksum:mt})}const so=new Set(["completed","aborted","cancelled"]),po=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Ce=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"}),xe=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"}),Hr=240,lo=/(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 uo(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,It).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,It).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,It).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,It).replace(Qa,It).replace(Xa,It)}function Je(e,t){const r=uo(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function Vn(e,t=0,r=new WeakSet){if(t>za)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Je(e,Tt);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,Ya).map(a=>Vn(a,t+1,r));const i={};for(const[a,n]of Object.entries(e).slice(0,Ja)){if(Ka.test(a)){i[a]=It;continue}const o=Vn(n,t+1,r);o!==void 0&&(i[a]=o)}return i}finally{r.delete(e)}}}function ln(e,t){return{instructions:Je(e??"",qa),metadata:t?Vn(t):void 0}}class un extends Error{reason;source;byteLength;code;constructor(t,r,i,a,n){super(r),this.reason=i,this.source=a,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function ho(e){const t=on(e);return(t==="arch-plan"||t==="ui-ux-review")&&go(e,"--project-evidence")}function go(e,t){let r=null,i=-1,a=!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(i>=0&&!a&&e.slice(i,o)===t)return!0;i=-1,a=!1,n=!1;continue}if(i<0&&(i=o),n){n=!1;continue}if(s==="\\"){n=!0;continue}(s==='"'||s==="'")&&(a=!0,r=r===s?null:r??s)}return!1}const fo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function mo(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 $e("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(fo)?.[1]??null}catch{return null}}function Bn(){return _a({clientVersion:xt,registryVersion:yt,registryChecksum:mt})}class Un 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 $n 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 Hn=!1;function yo(e){const t=[];if(!e||typeof e!="object")return t;const r=e,i=r.planning;if(i&&(i.current!==void 0||Array.isArray(i.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 a=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)||i&&i.current!==void 0;return r.schema_version===void 0?a&&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 Io(e){if(!(Hn||e.length===0)){Hn=!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 Gs(){Gn=!1}function Gr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function go(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const mo=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"]),yo=/(?:[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 Io(e,t){if(!(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const r=JSON.stringify(e);if(Buffer.byteLength(r)>16384||yo.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"]),!h(e.intake)||Object.keys(e.intake).some(n=>!mo.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(!h(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"?ja: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&&(!h(n)||(a(n,i),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!h(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 Wr(e){return e==="create-epic"||e==="discovered"?e:void 0}function $e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Eo(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=>sn(n)===void 0)){r=!0;continue}t[a]=i.map(n=>sn(n))}if(e.planning!==void 0)try{if(!h(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=>!h(u)||sn(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(!h(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=>!h(s)||sn(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...n}=Pi(a);t.planning=n}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function It(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 Ge(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 Et(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 hn(e){if(!h(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),r=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),a=(l,v)=>Array.isArray(l)&&l.length<=v&&l.every(t)&&new Set(l).size===l.length?l:void 0,i=(l,v)=>{if(!(!h(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!r(l.requestHash)||!r(l.inputHash)||!r(l.stateHash)||!r(l.nonce)||!r(l.stageRevision)||!r(l.stageHash)||!r(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||v&&(!r(l.outputHash)||!r(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(!(!h(l)||l.schemaVersion!=="1.1"||l.kind!==v||!r(l.receiptId)||!r(l.graphHash)||!r(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(!h(l)||l.kind!==v||!r(l.receiptId)||!a(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 I=i(l,!0);if(!I)return;const p=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"&&(!p||!C)))return{...I,kind:v,receiptId:l.receiptId,status:l.status,evidenceIds:l.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 l=cr(e.nonUiScopeReceipt);if(!l||l.targetEpicId!==e.targetEpicId||l.graphRevision!==e.graphRevision||!h(e.accounting)||l.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||l.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=l}h(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 y=o(e.completionEvidence,"architecture-stage-completion"),w=o(e.validationEvidence,"architecture-stage-validation");if(y&&(s.completionEvidence=y),w&&(s.validationEvidence=w),h(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 l=a(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(Gt(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=a(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(!h(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const I=o(v.completionEvidence,"architecture-stage-completion"),p=o(v.validationEvidence,"architecture-stage-validation");return I&&p?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:I,validationEvidence:p}:void 0});l.every(v=>v!==void 0)&&(s.acceptedStages=l)}if(h(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=a(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 So(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,r=h(t)?t.checkpoint:void 0,a=h(t)?t:void 0,i=h(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&&h(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",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&o.length===2&&h(o[0])&&h(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",w=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&a?.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&&h(o[0])&&h(o[1])&&h(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&&h(o[0])&&h(o[1])&&h(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",I=["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&&h(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,I)&&E(a?.questionIds,I)&&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,I)&&E(i.questionIds,[])&&E(i.pactAnswerReceipt,e.answerReceipt)&&E(a?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&a?.nextAction==="resume",O=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=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(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=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(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",S=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=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",_=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=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",M=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",$=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=>h(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"&&h(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",ie=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=>h(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"&&h(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",D=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&a?.nextAction==="delegate",G=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=>h(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"&&h(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=>h(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"&&h(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",k=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=>h(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"&&h(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&a?.nextAction==="resume",W=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",ke=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(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)&&h(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"&&h(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",He=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)&&h(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)&&Gt(i.terminalMemoryCheckpoint,n)!==null&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&a?.nextAction==="complete",Fe=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)&&Gt(i.terminalMemoryCheckpoint,n)&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&a?.nextAction==="complete",Z=a?Aa(n,a,Gt(n.terminalMemoryCheckpoint,n)&&E(i?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(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||y||w||l||v||p||C||O||V||T||P||S||_||Q||M||$||N||ie||D||G||Pe||st||X||k||W||dt||ke||ve||He||Fe)||!h(r.accounting)||r.accounting.charged!==!0||!E(hn(r),r))throw new Error("architecture-root-checkpoint-invalid");const le=z(e.projectRoot,".neocortex"),oe=z(le,"state.json"),vt=z(le,"state.json.architecture.lock"),qe=Ft(vt,"wx",384);let Ye;try{const j=Lt(oe);if(!j.isFile()||j.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ce=Be(oe,"utf8");if(Ve("sha256").update(ce).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const J=JSON.parse(ce),Oe=h(J)&&h(J.archPlan)?J.archPlan:{};if(!h(J)||!h(J.epics)||!Object.hasOwn(J.epics,r.targetEpicId)||(e.initialBinding?Oe.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(hn(Oe.execution),n))||h(J.scope)&&J.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Wt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Fe||Z==="complete-replay"){const ye={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,or(n))};if(!E(n.terminalMemoryCheckpoint,xn(e.projectRoot,ye)))throw new Error("architecture-root-state-conflict");return}const se=nn(),Ct=Ue("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Ke=Oa(Ct)?Pn(Ct):Pn(e.projectRoot,Ct);if(ka(Ke)!==Ke)throw new Error("architecture-root-backup-dir-invalid");const me=z(Ke,"neocortex-architecture");Ht(me,{recursive:!0,mode:448});const Y=Lt(me);if(!Y.isDirectory()||Y.isSymbolicLink()||Y.uid!==process.getuid?.()||(Y.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const vn=z(me,`state-backup-${se}.json`),x=Ft(vn,"wx",384);try{rn(x,ce),an(x)}finally{qt(x)}const wt=Ft(me,"r");try{an(wt)}finally{qt(wt)}const f={...J,archPlan:{...Oe,execution:r}};Ye=z(le,`state.json.architecture-tmp-${se}`);const pt=Ft(Ye,"wx",384);try{rn(pt,`${JSON.stringify(f,null,2)}
8
- `),an(pt)}finally{qt(pt)}if((He||Z==="complete")&&!E(n.terminalMemoryCheckpoint,xn(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Wt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");dr(Ye,oe),Ye=void 0;const $t=Ft(le,"r");try{an($t)}finally{qt($t)}}finally{if(Ye)try{Tn(Ye)}catch{}qt(qe),Tn(vt)}}function fn(e,t){if(!h(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 gn(e){return e==="epic"||e==="story"?e:void 0}function Hr(e){if(!h(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),r=K(e.sessionId),a=K(e.idempotencyKey),i=Ge(e.acquiredAt),n=Ge(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 Fr(e){if(!h(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=Ge(e.recordedAt),u=$e(e.commits).map(A).filter(V=>!!V).slice(0,256),g=$e(e.receiptRefs).map(Et).filter(V=>!!V).slice(0,256),y=e.dispatchId===void 0?void 0:K(e.dispatchId),w=e.bundleId===void 0?void 0:K(e.bundleId),l=e.bundleDigest===void 0?void 0:A(e.bundleDigest),v=e.graphRevision===void 0?void 0:A(e.graphRevision),I=e.claimRevision===void 0?void 0:K(e.claimRevision),p=vo(e.qaReceipt),C=Co(e.reviewReceipt),O=e.rootMemoryEffect===void 0?void 0:Vi(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&&!y||e.bundleId!==void 0&&!w||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!I||e.rootMemoryEffect!==void 0&&(!O||O.storyId!==t||O.epicId!==r||O.executionBranch!==a||O.sourceHeadSha!==i||O.childClaimRevision!==I)||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||!Jr(p,{storyId:t,epicId:r,baseSha:i,headSha:n,bundleDigest:l,graphRevision:v})||C&&(!Jr(C,{storyId:t,epicId:r,baseSha:i,headSha:n,bundleDigest:l,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,...y?{dispatchId:y}:{},...w?{bundleId:w}:{},...l?{bundleDigest:l}:{},...v?{graphRevision:v}:{},...I?{claimRevision:I}:{},...O?{rootMemoryEffect:structuredClone(O)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...p?{qaReceipt:p}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:u,receiptRefs:g}}function vo(e){if(!h(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=Ge(e.checkedAt),g=Et(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?$e(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"&&(!y||w!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.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:y,command:w,manifestDigest:l,gateIds:I,resultDigest:v}:{},baseSha:a,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:g}}function qr(e){if(!h(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,y=A(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=A(e.manifestDigest),v=$e(e.gateIds).map(K).filter(P=>!!P).slice(0,64),I=A(e.resultDigest),p=A(e.graphRevision),C=A(e.executionEvidenceDigest),O=A(e.sourceEvidenceDigest),V=Ge(e.verifiedAt),T=$e(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||!y||y.length!==64||!w||!l||l.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!I||I.length!==64||!p||p.length!==64||!C||C.length!==64||!O||O.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:y,command:w,manifestDigest:l,gateIds:v,resultDigest:I,graphRevision:p,executionEvidenceDigest:C,sourceEvidenceDigest:O,verifiedAt:V,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function Yr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(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 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),y=Ge(e.verifiedAt),w=$e(e.reasonCodes).map(K).filter(l=>!!l);if(!(!r||!a||!i||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!g||g.length!==64||!y||!Array.isArray(e.reasonCodes)||w.length!==1||w[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:y,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Co(e){if(!h(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=Et(e.qaReceiptRef),g=Ge(e.reviewedAt),y=Et(e.receiptRef);if(!(!t||!r||!a||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!g||!y))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:y}}function Jr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function zr(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=_e(e.originBranch),r=A(e.originHeadSha),a=_e(e.executionBranch),i=Ge(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 Kr(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),r=A(e.graphRevision),a=Ge(e.checkedAt),i=Et(e.receiptRef),n=$e(e.gateIds).map(K).filter(y=>!!y).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 Wn(e){if(!h(e)||e.schemaVersion!==1)return;const t=fn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=$e(e.receiptRefs).map(Et).filter(i=>!!i).slice(0,256),a=$e(e.revertCommits).map(ee).filter(i=>!!i).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...a.length?{revertCommits:a}:{}}}function wo(e){if(!(!h(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 Qr(e){if(!h(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=Ge(e.attemptStartedAt),y=e.completedAt===void 0?void 0:Ge(e.completedAt),w=$e(e.localGateReceiptRefs).map(Et).filter(p=>!!p).slice(0,256),l=$e(e.reasonCodes).map(K).filter(p=>!!p).slice(0,64),v=Ro(e.candidateQa),I=_o(e.providerGuard);if(!(!t||!r||!a||!i||!n||!u||!g||w.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&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==o||I.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:a,baseSha:i,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...It(e.prNumber)?{prNumber:It(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:u,attemptStartedAt:g,...v?{candidateQa:v}:{},...I?{providerGuard:I}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function _o(e){if(!h(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=Ge(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 Ro(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Di)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,A(e[o])])),a=Ge(e.checkedAt),i=Et(e.receiptRef),n=$e(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 Ao(e){if(!h(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 bo(e){const t=fn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=fn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),a=fn(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)}:{},...It(e.issue_number??e.issueNumber)?{issue_number:It(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 xo=new Set(["yolo","yoloop","finalize-epic","audit"]);function Xr(e){return typeof e=="string"&&xo.has(e)}function Hn(e,t={}){const r=z(e,".neocortex","state.json");if(!Nt(r))throw new it("git-lifecycle-state-missing");let a;try{a=JSON.parse(Be(r,"utf8"))}catch{throw new it("git-lifecycle-state-corrupt")}if(!h(a)||!h(a.epics)||!h(a.stories))throw new it("git-lifecycle-state-shape-invalid");const i=Object.values(a.epics).some(n=>h(n)&&(n.branch_mode==="epic"||_e(n.execution_branch)!==void 0));if(i)try{dn(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 mn(e,t={}){const r=z(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 I=Be(r,"utf-8");i=Ve("sha256").update(I).digest("hex");const p=JSON.parse(I),C=h(p.epics)?p.epics:{},O=Object.values(C).some(_=>h(_)&&(_.branch_mode==="epic"||_e(_.execution_branch)!==void 0)),V=dn(e,{required:!!(t.epicAware&&O&&!t.projectless)});a=xr(p,V);const T=h(a.stories)?a.stories:{},P=h(a.epics)?a.epics:{},S=h(p.stories)?p.stories:{};for(const[_,Q]of Object.entries(T)){const M=h(Q)?Q:void 0;if(!M?.checkpoint)continue;const $=typeof M.epic_id=="string"?M.epic_id:_.split(".")[0],N=h(P[$])?P[$]:void 0,ie=_e(N?.execution_branch);if(!ie)continue;const D=ki(e,M.checkpoint,_,$,ie,t.p205Authorities?.[_],Tr(_,M,h(M.checkpoint)?M.checkpoint:void 0));if(D.kind==="integration-authorized")M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;else if(D.kind==="scheduling-only")M.scheduling_checkpoint_evidence=D.evidence,delete M.checkpoint,delete M.checkpoint_verification;else if(D.kind==="rejected"){M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;const G=h(S[_])?S[_]:void 0;if(delete M.checkpoint,V.stories[_]?.checkpoint!==void 0)for(const Pe of["status","last_step","steps_completed"])G&&Object.prototype.hasOwnProperty.call(G,Pe)?M[Pe]=structuredClone(G[Pe]):delete M[Pe];["done","completed","merged"].includes(String(M.status).toLowerCase())&&(M.status="blocked")}}}catch(I){if(t.epicAware&&!t.projectless){const p=I instanceof Error&&/^git-lifecycle-/.test(I.message)?I.message:"git-lifecycle-state-corrupt";throw new it(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const I=ho(a);I.length>0&&fo(I)}catch{}const n=a.config??a.project??{},o=a.stories??{},s={};for(const[I,p]of Object.entries(o)){const C=h(p.review_request)&&p.review_request.kind==="git-pull-request"?wo(p.review_request):Wn(p.review_request);s[I]={id:p.id??I,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",...Wr(p.source)?{source:Wr(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...gn(p.branch_mode)?{branch_mode:gn(p.branch_mode)}:{},...Fr(p.checkpoint)?{checkpoint:Fr(p.checkpoint)}:{},...qr(p.checkpoint_verification)?{checkpoint_verification:qr(p.checkpoint_verification)}:{},...Yr(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Yr(p.scheduling_checkpoint_evidence)}:{},...C?{review_request:C}:{},...Wn(p.rollback_receipt)?{rollback_receipt:Wn(p.rollback_receipt)}:{},...It(p.workflow_issue)?{workflow_issue:It(p.workflow_issue)}:{},...bo(p),depends_on:Gr(p.depends_on),files_to_modify:$e(p.files_to_modify),...Eo(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[I,p]of Object.entries(u)){const C=go(p.lifecycle_classification),O=Io(p.createEpicPlanning,I);let V,T,P,S;if(O&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningPhysical))try{pr(a,p.createEpicPlanningClaim.claimId,I,!0),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(V&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningResearchPhysical))try{ur(a,p.createEpicPlanningClaim.claimId,I),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&O&&p.status==="generated"&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningGenerationPhysical))try{if(Ma(e,p.createEpicPlanningClaim.claimId,I).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&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string")try{const _=lr(e,p.createEpicPlanningClaim.claimId,I);if(_.stateSha256!==i)throw new Error("planning-memory-snapshot-raced");S=JSON.parse(JSON.stringify(_))}catch{}g[I]={id:p.id??I,title:p.title,...O?{createEpicPlanning:O}:{},...V?{createEpicPlanningPhysical:V}:{},...T?{createEpicPlanningResearchPhysical:T}:{},...P?{createEpicPlanningGenerationPhysical:P}:{},...S?{createEpicPlanningMemoryPhysical:S}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:Gr(p.depends_on),...gn(p.branch_mode)?{branch_mode:gn(p.branch_mode)}:{},..._e(p.execution_branch)?{execution_branch:_e(p.execution_branch)}:{},..._e(p.origin_branch)?{origin_branch:_e(p.origin_branch)}:{},...Hr(p.branch_lease)?{branch_lease:Hr(p.branch_lease)}:{},...zr(p.origin_binding)?{origin_binding:zr(p.origin_binding)}:{},...Kr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Kr(p.aggregate_qa_receipt)}:{},...It(p.pr_number)?{pr_number:It(p.pr_number)}:{},...ee(p.physicalMergeStatus)?{physicalMergeStatus:ee(p.physicalMergeStatus)}:{},...A(p.graph_revision)?{graph_revision:A(p.graph_revision)}:{},...Qr(p.terminal_git_receipt)?{terminal_git_receipt:Qr(p.terminal_git_receipt)}:{},...C?{lifecycle_classification:C}:{}}}const y=Ao(a.current_session??a.currentSession),w=h(a.archPlan)?hn(a.archPlan.execution):void 0,l=a.epic_id_ledger,v=Array.isArray(l?.reserved_ids)?[...new Set(l.reserved_ids.filter(I=>typeof I=="string"&&/^P\d+$/.test(I)))].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}}:{},...y?{current_session:y}:{},...w?{archPlan:{execution:w}}:{}}}const Fn=[["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"]],qn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Yn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",Zr="30dccfff07f9c969be11ae1d28e62a09731a0768";function To(e,t){try{const r=t.indexOf(Zr);if(r<1||t[r-1]!==qn)return new Map;const a=Ue("git",["show","--no-patch","--format=%P",Zr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=Ue("git",["show","--no-patch","--format=%P",Yn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(a!==`${qn} ${Yn}`||i!==`${Fn.at(-1)[1]} ${qn}`)return new Map;const n=Ue("git",["rev-list","--first-parent","--reverse",Yn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
- `),o=new Map;let s=-1;for(const[u,[g,y]]of Fn.entries()){const w=n.indexOf(y);if(w<=s)return new Map;s=w,o.set(g,{headSha:y,position:u-Fn.length})}return o}catch{return new Map}}async function Po(e,t,r){if(!Xr(r))return{};if(Ir(t,r))return{};try{const a=JSON.parse(Be(z(e,".neocortex","state.json"),"utf8")),i=dn(e,{required:!0}),n=xr(a,i),o=h(n.stories)?n.stories:{},s=h(n.epics)?n.epics:{},u=Ue("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=Ue("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),y=Ue("git",["rev-list","--first-parent","--reverse",u],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
- `).filter(Boolean),w=new Map(y.map((S,_)=>[S,_])),l=To(e,y),v=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],I=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(([S,_])=>{if(v&&S!==v)return[];const Q=h(_)?_:void 0,M=h(Q?.checkpoint)?Q.checkpoint:void 0;if(!M)return[];const $=typeof Q?.epic_id=="string"?Q.epic_id:S.split(".")[0];if(I&&$!==I)return[];const N=A(M?.headSha),ie=$==="P222"?l.get(S):void 0,D=w.get(N??"")??(ie&&ie.headSha===N?ie.position:void 0);if(!N||N.length<40||D===void 0)return p.add($),[];const G=h(s[$])?s[$]:void 0;if(G?.branch_mode!=="epic"||_e(G.execution_branch)!==g||_e(M.branch)!==g)return p.add($),[];const Pe=A(M.graphRevision);if(!Pe||Pe.length!==64)return p.add($),[];const st=A(M.claimRevision),X=[...Tr(S,Q,M)].sort(),k=Mi(e,M,S,$,g,X);if(!k&&st){if(X.length===0)return p.add($),[];const W=Ue("git",["diff-tree","--no-commit-id","--name-only","-r","-z",N],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let dt=[];if(M.rootMemoryEffect!==void 0)try{dt=ji(e,M.rootMemoryEffect,{storyId:S,executionBranch:g,baseSha:String(M.baseSha),headRef:N,childPaths:X}).files.map(He=>He.path)}catch{return p.add($),[]}if(W.length===0||W.some(He=>!X.some(Fe=>Fe===He||Fe.endsWith("/")&&He.startsWith(Fe))&&!dt.includes(He)))return p.add($),[];const ke=Ve("sha256").update(X.join("\0")).digest("hex"),ve=Ve("sha256").update(JSON.stringify(X)).digest("hex");if(st!==ke&&st!==ve)return p.add($),[]}else if(!k)return p.add($),[];return Pe?.length===64?[{storyId:S,epicId:$,graphRevision:Pe,checkpointHead:N,position:D}]:[]}),O=new Set(p);for(const[S,_]of Object.entries(s)){const Q=h(_)?_:void 0,M=Array.isArray(Q?.stories)?Q.stories.filter(D=>typeof D=="string"):Object.keys(o).filter(D=>D.startsWith(`${S}.`)),$=C.filter(D=>D.epicId===S),N=M.filter(D=>$.some(G=>G.storyId===D)),ie=[...$].sort((D,G)=>D.position-G.position).map(D=>D.storyId);(JSON.stringify(N)!==JSON.stringify(ie)||new Set(ie).size!==ie.length)&&O.add(S)}const V={},T=[...new Set(C.filter(S=>!O.has(S.epicId)).map(S=>S.graphRevision))],P=T.length>0?await Ni(e,{headSha:u,graphRevisions:T}):new Map;for(const S of C){if(O.has(S.epicId))continue;const _=P.get(S.graphRevision);if(!_)throw new Error("p205-transient-authority-missing");V[S.storyId]=_}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 Ws(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 ea="neocortex:menu:cache";async function ko(e){try{const t=await e.get(ea);if(!t)return null;const r=JSON.parse(t);return r.version!==xt||Date.now()-r.cachedAt>Or?null:r}catch{return null}}async function Oo(e,t,r){try{const a={instructions:t,metadata:r,cachedAt:Date.now(),version:xt};await e.set(ea,JSON.stringify(a),Or),No()}catch{}}function No(){try{Nt(kr)&&Tn(kr)}catch{}}function ta(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>On(),()=>On({strictReadOnly:!0}))}async function na(e,t,r){const a=r.mode==="strict";try{let i;if(a&&t)i=new kn({cacheDir:Ln,passphrase:t,strictReadOnly:!0});else if(a)i=new hr;else if(t){const y=z(pn,"cache");i=new kn({cacheDir:y,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
- `),i=new hr;const n=_r(r,i,"auth-cache"),o=_r(r,i,"tier-cache"),s=new Va({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:a});let u;if(a){const y=await s.inspectToken();if(y.status!=="authenticated")return y;u=y.token}else u=await s.getToken();if(!u)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const g=new Ua({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 ra=!1;function Lo(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 aa=3,yn=50;function Do(e){return new Promise(t=>setTimeout(t,e))}function Mo(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Jt(e,t,r,a,i={}){const n=Math.max(1,Math.min(i.maxAttempts??aa,aa)),o=i.sleep??Do;let s=a,u=!1,g=!1,y=0;for(let w=1;w<=n;w+=1){const l=Math.max(Math.floor(Date.now()/1e3),y+1);y=l;const v=jo(t,r,s,{nowSeconds:l}),I=new AbortController,p=setTimeout(()=>I.abort(),Nr);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:v.headers,body:v.body,signal:I.signal});if(i.admitResponseBeforeBodyRead&&!i.admitResponseBeforeBodyRead(C))return{response:C,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const O=await C.text().catch(()=>""),V=C.ok&&i.deferSuccessfulJsonParsing?{}:(()=>{try{return O?JSON.parse(O):{}}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&&w<n){s=T,i.onTokenChanged?.(T),await o(yn*w);continue}}if(C.status===401&&V.error_code==="SIGNATURE_EXPIRED"&&!g&&w<n){g=!0,await o(yn*w);continue}if(w<n&&Mo(C,V,i.allowReplayRetry===!0)){await o(yn*w);continue}return{response:C,text:O,parsed:V,networkFailure:!1}}catch{if(w<n){await o(yn*w);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(p)}}return{text:"",parsed:{},networkFailure:!0}}function jo(e,t,r,a={}){const i=Buffer.from(JSON.stringify(t),"utf8"),n=ci({method:"POST",target:e,body:i,bearerToken:r,clientVersion:xt,nowSeconds:a.nowSeconds,nonceBytes:a.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${r}`}}}function ia(e){return Ve("sha256").update(e).digest("hex")}function Vo(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Uo(e,t,r){return`args-${Ve("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function oa(e,t,r,a,i={}){const n=await Jt(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 Bo(e,t,r,a){const i=Buffer.from(t,"utf8"),n=Vo(),o=[];for(let I=0,p=0;I<i.byteLength;I+=n,p++){const C=i.subarray(I,Math.min(I+n,i.byteLength));o.push({index:p,sha256:ia(C),byteLength:C.byteLength})}const s=ia(i),u=Uo(s,i.byteLength,o),g=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let y=r;const w={refreshToken:a,onTokenChanged(I){y=I}};for(const I of o){const p=I.index*n,C=i.subarray(p,p+I.byteLength);await oa(e,"/api/v1/invoke/materialization/chunks",{manifestId:u,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:C.toString("base64"),ttlSeconds:g,idempotencyKey:`${u}:${I.index}:${I.sha256}`},y,w)}const v=(await oa(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}},y,w)).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 $o(...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 Go(e){const t=e.graphRetrieval;if(!h(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 Jn(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??Dr,warningThresholdBytes:a.warningThresholdBytes??Dn,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:Go(e.stateSnapshot),reasonCodes:$o(r,i?.reasonCodes),publicSafe:!0}}function Wo(e){const t=h(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 Ho(e){return h(e)?{stableId:ee(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function ca(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Fo(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const r=Wo(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,Ho(o)].slice(-32),n={...t,items:a,skipped:i,warnings:ca(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:ca(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function sa(e,t={}){const r=t.limitBytes??Dr,a=t.warningThresholdBytes??Math.floor(r*Mr),i=Ut(e);if(i<r)return{body:e,degraded:!1,telemetry:Jn(e,i,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:a})};let n={...e,stateSnapshot:Fa(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],s=Ut(n);s>=r&&(n={...n,stateSnapshot:Fo(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],s=Ut(n));const u=Jn(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 $n(u):new Bn(u)}return{body:n,degraded:!0,telemetry:u}}function da(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function qo(e){const t=Ut(e);if(t<Dn)return t;const r=Jn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${da(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 pa(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${da(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 Yo(e){const t=Xa(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Jo(t),metadata:ua(t)};const r=e.bootstrapper??ei;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:[Za.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=ua(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(Qa.SKIPPED_NON_CONTINUITY_COMMAND)}function ua(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:Ne([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Ne(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function In(e,t,r){const a=Math.floor(e??t);return Number.isFinite(a)?Math.max(1,Math.min(r,a)):t}function En(e,t){const r=process.env[e];if(!r)return t;const a=Number(r);return Number.isFinite(a)?a:t}function q(e,t=$r){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",a=Je(r,t),i=oo.test(a)?yt:a;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function zn(e,t=$r){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function Kn(e,t,r,a){const i=zn(e?.targetId??t,120),n=e?.selectorKind??(i?Xn(i):void 0),o=(e?.relatedJobIds??[]).map(s=>zn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...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:Ne(a.length>0?a:[F.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=zn(t[t.length-1]?.eventId,120),u=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:a,...s?{latestEventId:s}:{},reasonCodes:Ne(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"),y=i.length>0?i:g==="advanced"?[F.WATCH_CURSOR_ADVANCED]:g==="unavailable"?[F.WATCH_EVIDENCE_UNAVAILABLE]:[F.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:g,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...s?{nextCursor:q(s,200)}:{},cursorAdvanced:u,...o?.eventId?{eventId:q(o.eventId,120)}:{},reasonCodes:Ne(y),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:Ne([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function zo(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=${q(n,200)}`,`next=${q(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
- `:`[watch-status] status=${i.watchStatus} active=${i.active} summaries=${i.renderedSummaryCount} stop=${i.stopReason}
7
+ `)}catch{}}}function Ys(){Hn=!1}function Gr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Eo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const So=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"]),vo=/(?:[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 Co(e,t){if(!(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const r=JSON.stringify(e);if(Buffer.byteLength(r)>16384||vo.test(r))return;const i=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(i(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake)||Object.keys(e.intake).some(n=>!So.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 l of o)if(!h(l)||(i(l,s),Object.values(l).some(f=>typeof f!="string"||f.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"?Bi:512))return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const a=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!h(n)||(i(n,a),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return;i(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 Wr(e){return e==="create-epic"||e==="discovered"?e:void 0}function Ee(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function wo(e){const t={};let r=!1;for(const i of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[i]===void 0)continue;const a=e[i];if(!Array.isArray(a)||a.length>128||a.some(n=>sn(n)===void 0)){r=!0;continue}t[i]=a.map(n=>sn(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const i=e.planning;for(const o of["claims","semanticArtifacts"]){if(i[o]===void 0)continue;const s=i[o];if(!Array.isArray(s)||s.length>128||s.some(l=>!h(l)||sn(l.ref)===void 0))throw new Error("planning-refs")}if(i.attempts!==void 0&&(!Array.isArray(i.attempts)||i.attempts.length>32))throw new Error("planning-attempts");for(const o of i.attempts??[]){if(!h(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=>!h(s)||sn(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=Oa(i);t.planning=n}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Et(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 J(e){if(typeof e!="string")return;const t=e.trim(),r=ee(e);return r===t?r:void 0}function Se(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 _(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Te(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 at(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 hn(e){if(!h(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),r=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),i=(u,v)=>Array.isArray(u)&&u.length<=v&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,v)=>{if(!(!h(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!r(u.requestHash)||!r(u.inputHash)||!r(u.stateHash)||!r(u.nonce)||!r(u.stageRevision)||!r(u.stageHash)||!r(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||v&&(!r(u.outputHash)||!r(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...v?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,v)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==v||!r(u.receiptId)||!r(u.graphHash)||!r(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:v,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,v)=>{if(!h(u)||u.kind!==v||!r(u.receiptId)||!i(u.evidenceIds,24)||v==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||v==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const I=a(u,!0);if(!I)return;const p=v==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,C=v==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!p||!C)))return{...I,kind:v,receiptId:u.receiptId,status:u.status,evidenceIds:u.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 l=i(e.questionIds,16);if(l&&(s.questionIds=l),(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 u=cr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!h(e.accounting)||u.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=u}h(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 f=a(e.evidenceExpectation,!1);f&&(s.evidenceExpectation=f);const y=o(e.completionEvidence,"architecture-stage-completion"),w=o(e.validationEvidence,"architecture-stage-validation");if(y&&(s.completionEvidence=y),w&&(s.validationEvidence=w),h(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 u=i(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ht(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=i(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(v=>{if(!h(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const I=o(v.completionEvidence,"architecture-stage-completion"),p=o(v.validationEvidence,"architecture-stage-validation");return I&&p?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:I,validationEvidence:p}:void 0});u.every(v=>v!==void 0)&&(s.acceptedStages=u)}if(h(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 u=i(e.accounting.receiptIds,32);u&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["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 _o(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,r=h(t)?t.checkpoint:void 0,i=h(t)?t:void 0,a=h(r)?r:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&i?.nextAction==="delegate",l=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",f=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&h(o[0])&&h(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)&&i?.nextAction==="resume",w=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(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)&&i?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",I=["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"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&h(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(a.questionIds,I)&&E(i?.questionIds,I)&&i?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,I)&&E(a.questionIds,[])&&E(a.pactAnswerReceipt,e.answerReceipt)&&E(i?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&i?.nextAction==="resume",O=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",V=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",S=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",R=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",Q=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",M=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",$=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(j=>h(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"&&h(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",N=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&i?.nextAction==="blocked",ae=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(j=>h(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"&&h(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",D=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",H=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(j=>h(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"&&h(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",Oe=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",dt=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(j=>h(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"&&h(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",X=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",k=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(j=>h(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"&&h(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",G=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",pt=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&i?.nextAction==="ask-user",Ne=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(a.reviewDecision,n.reviewDecision)&&i?.nextAction==="resume",we=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(a.reviewDecision,n.reviewDecision)&&i?.nextAction==="delegate",We=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&h(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(a.reviewDecision,n.reviewDecision)&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&Ht(a.terminalMemoryCheckpoint,n)!==null&&E(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&i?.nextAction==="complete",Fe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(a.reviewDecision,n.reviewDecision)&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&Ht(a.terminalMemoryCheckpoint,n)&&E(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&i?.nextAction==="complete",Z=i?xi(n,i,Ht(n.terminalMemoryCheckpoint,n)&&E(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(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||l||f||y||w||u||v||p||C||O||V||T||P||S||R||Q||M||$||N||ae||D||H||Oe||dt||X||k||G||pt||Ne||we||We||Fe)||!h(r.accounting)||r.accounting.charged!==!0||!E(hn(r),r))throw new Error("architecture-root-checkpoint-invalid");const ue=K(e.projectRoot,".neocortex"),oe=K(ue,"state.json"),vt=K(ue,"state.json.architecture.lock"),qe=Ft(vt,"wx",384);let Ye;try{const j=Lt(oe);if(!j.isFile()||j.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ce=He(oe,"utf8");if(Ue("sha256").update(ce).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const z=JSON.parse(ce),Le=h(z)&&h(z.archPlan)?z.archPlan:{};if(!h(z)||!h(z.epics)||!Object.hasOwn(z.epics,r.targetEpicId)||(e.initialBinding?Le.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(hn(Le.execution),n))||h(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(Fe||Z==="complete-replay"){const ye={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,or(n))};if(!E(n.terminalMemoryCheckpoint,xn(e.projectRoot,ye)))throw new Error("architecture-root-state-conflict");return}const se=nn(),Ct=$e("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Ke=Li(Ct)?Pn(Ct):Pn(e.projectRoot,Ct);if(Ni(Ke)!==Ke)throw new Error("architecture-root-backup-dir-invalid");const me=K(Ke,"neocortex-architecture");Wt(me,{recursive:!0,mode:448});const Y=Lt(me);if(!Y.isDirectory()||Y.isSymbolicLink()||Y.uid!==process.getuid?.()||(Y.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const vn=K(me,`state-backup-${se}.json`),x=Ft(vn,"wx",384);try{rn(x,ce),an(x)}finally{qt(x)}const wt=Ft(me,"r");try{an(wt)}finally{qt(wt)}const g={...z,archPlan:{...Le,execution:r}};Ye=K(ue,`state.json.architecture-tmp-${se}`);const lt=Ft(Ye,"wx",384);try{rn(lt,`${JSON.stringify(g,null,2)}
8
+ `),an(lt)}finally{qt(lt)}if((We||Z==="complete")&&!E(n.terminalMemoryCheckpoint,xn(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");dr(Ye,oe),Ye=void 0;const $t=Ft(ue,"r");try{an($t)}finally{qt($t)}}finally{if(Ye)try{Tn(Ye)}catch{}qt(qe),Tn(vt)}}function gn(e,t){if(!h(e))return;const r={};for(const i of t){const a=e[i];if(typeof a=="boolean")r[i]=a;else if(typeof a=="number"&&Number.isFinite(a))r[i]=a;else if(typeof a=="string"){const n=ee(a);n&&(r[i]=n)}}return Object.keys(r).length>0?r:void 0}function fn(e){return e==="epic"||e==="story"?e:void 0}function Fr(e){if(!h(e)||e.schemaVersion!==1)return;const t=J(e.ownerStoryId),r=J(e.sessionId),i=J(e.idempotencyKey),a=Te(e.acquiredAt),n=Te(e.expiresAt);if(!(!t||!r||!i||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:i,acquiredAt:a,expiresAt:n}}function qr(e){if(!h(e)||e.schemaVersion!==1)return;const t=J(e.storyId),r=J(e.epicId),i=Se(e.branch),a=_(e.baseSha),n=_(e.headSha),o=J(e.idempotencyKey),s=Te(e.recordedAt),l=Ee(e.commits).map(_).filter(V=>!!V).slice(0,256),f=Ee(e.receiptRefs).map(at).filter(V=>!!V).slice(0,256),y=e.dispatchId===void 0?void 0:J(e.dispatchId),w=e.bundleId===void 0?void 0:J(e.bundleId),u=e.bundleDigest===void 0?void 0:_(e.bundleDigest),v=e.graphRevision===void 0?void 0:_(e.graphRevision),I=e.claimRevision===void 0?void 0:J(e.claimRevision),p=Ro(e.qaReceipt),C=Ao(e.reviewReceipt),O=e.rootMemoryEffect===void 0?void 0:Ha(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!r||!t.startsWith(`${r}.`)||!i||!a||!n||a===n||!o||!s||l.length===0||f.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||f.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!w||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!I||e.rootMemoryEffect!==void 0&&(!O||O.storyId!==t||O.epicId!==r||O.executionBranch!==i||O.sourceHeadSha!==a||O.childClaimRevision!==I)||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||!zr(p,{storyId:t,epicId:r,baseSha:a,headSha:n,bundleDigest:u,graphRevision:v})||C&&(!zr(C,{storyId:t,epicId:r,baseSha:a,headSha:n,bundleDigest:u,graphRevision:v})||C.qaReceiptRef!==p?.receiptRef||C.receiptRef===p?.receiptRef)||!f.includes(String(p.receiptRef))||C&&(!f.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(p.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:i,baseSha:a,headSha:n,idempotencyKey:o,...y?{dispatchId:y}:{},...w?{bundleId:w}:{},...u?{bundleDigest:u}:{},...v?{graphRevision:v}:{},...I?{claimRevision:I}:{},...O?{rootMemoryEffect:structuredClone(O)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...p?{qaReceipt:p}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:l,receiptRefs:f}}function Ro(e){if(!h(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=J(e.storyId),r=J(e.epicId),i=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),s=_(e.sourceEvidenceDigest),l=Te(e.checkedAt),f=at(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?_(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?_(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?Ee(e.gateIds).map(J).filter(p=>!!p).slice(0,64):void 0;if(!(!t||!r||!i||!a||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!l||!f||e.evidenceVersion==="p205-execution-v2"&&(!y||w!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.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:y,command:w,manifestDigest:u,gateIds:I,resultDigest:v}:{},baseSha:i,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:l,receiptRef:f}}function Yr(e){if(!h(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=J(e.storyId),r=J(e.epicId),i=Se(e.branch),a=_(e.baseSha),n=_(e.headSha),o=_(e.aggregateHeadSha),s=_(e.commitBodyDigest),l=_(e.changedPathsDigest),f=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=_(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=_(e.manifestDigest),v=Ee(e.gateIds).map(J).filter(P=>!!P).slice(0,64),I=_(e.resultDigest),p=_(e.graphRevision),C=_(e.executionEvidenceDigest),O=_(e.sourceEvidenceDigest),V=Te(e.verifiedAt),T=Ee(e.reasonCodes).map(J).filter(P=>!!P).slice(0,16);if(!(!t||!r||!i||!a||a.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!l||l.length!==64||!f||!y||y.length!==64||!w||!u||u.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!I||I.length!==64||!p||p.length!==64||!C||C.length!==64||!O||O.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:i,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:l,claimVerification:f,effectiveClaimRevision:y,command:w,manifestDigest:u,gateIds:v,resultDigest:I,graphRevision:p,executionEvidenceDigest:C,sourceEvidenceDigest:O,verifiedAt:V,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function Jr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=J(e.storyId),i=J(e.epicId),a=Se(e.branch),n=_(e.baseSha),o=_(e.headSha),s=_(e.graphRevision),l=_(e.effectiveClaimRevision),f=_(e.sourceEvidenceDigest),y=Te(e.verifiedAt),w=Ee(e.reasonCodes).map(J).filter(u=>!!u);if(!(!r||!i||!a||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!l||l.length!==64||!f||f.length!==64||!y||!Array.isArray(e.reasonCodes)||w.length!==1||w[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:i,branch:a,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:l,sourceEvidenceDigest:f,verifiedAt:y,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Ao(e){if(!h(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=J(e.storyId),r=J(e.epicId),i=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),s=_(e.sourceEvidenceDigest),l=at(e.qaReceiptRef),f=Te(e.reviewedAt),y=at(e.receiptRef);if(!(!t||!r||!i||!a||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!l||!f||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:i,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:l,verdict:e.verdict,reviewedAt:f,receiptRef:y}}function zr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function Kr(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=Se(e.originBranch),r=_(e.originHeadSha),i=Se(e.executionBranch),a=Te(e.capturedAt);if(!(!t||!r||r.length<40||!i||!a||t===i))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:i,capturedFromCurrentCheckout:!0,capturedAt:a}}function Qr(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=_(e.executionHeadSha),r=_(e.graphRevision),i=Te(e.checkedAt),a=at(e.receiptRef),n=Ee(e.gateIds).map(J).filter(y=>!!y).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,l=o?_(e.manifestDigest):void 0,f=o?_(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!i||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!l||l.length!==64||!f||f.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:l,resultDigest:f}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:i,receiptRef:a,gateIds:n}}function Xr(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:J(e.epicId),executionBranch:Se(e.executionBranch),originBranch:Se(e.originBranch),graphRevision:_(e.graphRevision),originHeadSha:_(e.originHeadSha),lastAcceptedCheckpointHeadSha:_(e.lastAcceptedCheckpointHeadSha),executionHeadSha:_(e.executionHeadSha),acceptedCheckpointIds:Ee(e.acceptedCheckpointIds),acceptedCheckpointHeads:Ee(e.acceptedCheckpointHeads),reconciliationCommitShas:Ee(e.reconciliationCommitShas),commitRangeDigest:_(e.commitRangeDigest),changedPaths:Ee(e.changedPaths),changedPathsDigest:_(e.changedPathsDigest),allowedWriteSet:Ee(e.allowedWriteSet),allowedWriteSetDigest:_(e.allowedWriteSetDigest),aggregateReceiptRef:at(e.aggregateReceiptRef),aggregateManifestDigest:_(e.aggregateManifestDigest),aggregateResultDigest:_(e.aggregateResultDigest),producedAt:Te(e.producedAt),revalidatedAt:Te(e.revalidatedAt),publicSafe:!0};if(!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==La(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==xr(t.changedPaths)||t.allowedWriteSetDigest!==xr(t.allowedWriteSet))return;const r=t,i=_(e.inputDigest);if(!(!i||i.length!==64||i!==Na(r)))return{...r,inputDigest:i}}function Gn(e){if(!h(e)||e.schemaVersion!==1)return;const t=gn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=Ee(e.receiptRefs).map(at).filter(a=>!!a).slice(0,256),i=Ee(e.revertCommits).map(ee).filter(a=>!!a).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...i.length?{revertCommits:i}:{}}}function bo(e){if(!(!h(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(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=J(e.epicId),r=Se(e.executionBranch),i=Se(e.originBranch),a=_(e.baseSha),n=_(e.executionHeadSha),o=e.mergeSha===void 0?void 0:_(e.mergeSha),s=e.pushedSha===void 0?void 0:_(e.pushedSha),l=J(e.idempotencyKey),f=Te(e.attemptStartedAt),y=e.completedAt===void 0?void 0:Te(e.completedAt),w=Ee(e.localGateReceiptRefs).map(at).filter(p=>!!p).slice(0,256),u=Ee(e.reasonCodes).map(J).filter(p=>!!p).slice(0,64),v=To(e.candidateQa),I=xo(e.providerGuard);if(!(!t||!r||!i||!a||!n||!l||!f||w.length===0||u.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&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==o||I.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:i,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...Et(e.prNumber)?{prNumber:Et(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:l,attemptStartedAt:f,...v?{candidateQa:v}:{},...I?{providerGuard:I}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function xo(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),i=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),a=_(e.prHeadSha),n=_(e.originHeadSha),o=Te(e.checkedAt);if(!(!i||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function To(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Ba)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,_(e[o])])),i=Te(e.checkedAt),a=at(e.receiptRef),n=Ee(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(r).some(o=>!o)||!i||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:i,receiptRef:a,gateIds:n}}function Po(e){if(!h(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 ko(e){const t=gn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=gn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),i=gn(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)}:{},...Et(e.issue_number??e.issueNumber)?{issue_number:Et(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...i?{scopedCiEvidence:i}:{}}}class ot extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Oo=new Set(["yolo","yoloop","finalize-epic","audit"]);function ei(e){return typeof e=="string"&&Oo.has(e)}function Wn(e,t={}){const r=K(e,".neocortex","state.json");if(!Nt(r))throw new ot("git-lifecycle-state-missing");let i;try{i=JSON.parse(He(r,"utf8"))}catch{throw new ot("git-lifecycle-state-corrupt")}if(!h(i)||!h(i.epics)||!h(i.stories))throw new ot("git-lifecycle-state-shape-invalid");const a=Object.values(i.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Se(n.execution_branch)!==void 0));if(a)try{dn(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 ot(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function mn(e,t={}){const r=K(e,".neocortex","state.json");if(!Nt(r)){if(t.epicAware&&!t.projectless)throw new ot("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let i,a;try{const I=He(r,"utf-8");a=Ue("sha256").update(I).digest("hex");const p=JSON.parse(I),C=h(p.epics)?p.epics:{},O=Object.values(C).some(R=>h(R)&&(R.branch_mode==="epic"||Se(R.execution_branch)!==void 0)),V=dn(e,{required:!!(t.epicAware&&O&&!t.projectless)});i=Tr(p,V);const T=h(i.stories)?i.stories:{},P=h(i.epics)?i.epics:{},S=h(p.stories)?p.stories:{};for(const[R,Q]of Object.entries(T)){const M=h(Q)?Q:void 0;if(!M?.checkpoint)continue;const $=typeof M.epic_id=="string"?M.epic_id:R.split(".")[0],N=h(P[$])?P[$]:void 0,ae=Se(N?.execution_branch);if(!ae)continue;const D=Da(e,M.checkpoint,R,$,ae,t.p205Authorities?.[R],Pr(R,M,h(M.checkpoint)?M.checkpoint:void 0));if(D.kind==="integration-authorized")M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;else if(D.kind==="scheduling-only")M.scheduling_checkpoint_evidence=D.evidence,delete M.checkpoint,delete M.checkpoint_verification;else if(D.kind==="rejected"){M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;const H=h(S[R])?S[R]:void 0;if(delete M.checkpoint,V.stories[R]?.checkpoint!==void 0)for(const Oe of["status","last_step","steps_completed"])H&&Object.prototype.hasOwnProperty.call(H,Oe)?M[Oe]=structuredClone(H[Oe]):delete M[Oe];["done","completed","merged"].includes(String(M.status).toLowerCase())&&(M.status="blocked")}}}catch(I){if(t.epicAware&&!t.projectless){const p=I instanceof Error&&/^git-lifecycle-/.test(I.message)?I.message:"git-lifecycle-state-corrupt";throw new ot(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const I=yo(i);I.length>0&&Io(I)}catch{}const n=i.config??i.project??{},o=i.stories??{},s={};for(const[I,p]of Object.entries(o)){const C=h(p.review_request)&&p.review_request.kind==="git-pull-request"?bo(p.review_request):Gn(p.review_request);s[I]={id:p.id??I,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",...Wr(p.source)?{source:Wr(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...fn(p.branch_mode)?{branch_mode:fn(p.branch_mode)}:{},...qr(p.checkpoint)?{checkpoint:qr(p.checkpoint)}:{},...Yr(p.checkpoint_verification)?{checkpoint_verification:Yr(p.checkpoint_verification)}:{},...Jr(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Jr(p.scheduling_checkpoint_evidence)}:{},...C?{review_request:C}:{},...Gn(p.rollback_receipt)?{rollback_receipt:Gn(p.rollback_receipt)}:{},...Et(p.workflow_issue)?{workflow_issue:Et(p.workflow_issue)}:{},...ko(p),depends_on:Gr(p.depends_on),files_to_modify:Ee(p.files_to_modify),...wo(p),risk:typeof p.risk=="string"?p.risk:void 0,blast_radius:typeof p.blast_radius=="number"?p.blast_radius:void 0}}const l=i.epics??{},f={};for(const[I,p]of Object.entries(l)){const C=Eo(p.lifecycle_classification),O=Co(p.createEpicPlanning,I);let V,T,P,S;if(O&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningPhysical))try{pr(i,p.createEpicPlanningClaim.claimId,I,!0),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(V&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningResearchPhysical))try{lr(i,p.createEpicPlanningClaim.claimId,I),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&O&&p.status==="generated"&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningGenerationPhysical))try{if(Vi(e,p.createEpicPlanningClaim.claimId,I).stateSha256!==a)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&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string")try{const R=ur(e,p.createEpicPlanningClaim.claimId,I);if(R.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");S=JSON.parse(JSON.stringify(R))}catch{}f[I]={id:p.id??I,title:p.title,...O?{createEpicPlanning:O}:{},...V?{createEpicPlanningPhysical:V}:{},...T?{createEpicPlanningResearchPhysical:T}:{},...P?{createEpicPlanningGenerationPhysical:P}:{},...S?{createEpicPlanningMemoryPhysical:S}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:Gr(p.depends_on),...fn(p.branch_mode)?{branch_mode:fn(p.branch_mode)}:{},...Se(p.execution_branch)?{execution_branch:Se(p.execution_branch)}:{},...Se(p.origin_branch)?{origin_branch:Se(p.origin_branch)}:{},...Fr(p.branch_lease)?{branch_lease:Fr(p.branch_lease)}:{},...Kr(p.origin_binding)?{origin_binding:Kr(p.origin_binding)}:{},...Qr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Qr(p.aggregate_qa_receipt)}:{},...Xr(p.head_reconciliation_receipt)?{head_reconciliation_receipt:Xr(p.head_reconciliation_receipt)}:{},...Et(p.pr_number)?{pr_number:Et(p.pr_number)}:{},...ee(p.physicalMergeStatus)?{physicalMergeStatus:ee(p.physicalMergeStatus)}:{},..._(p.graph_revision)?{graph_revision:_(p.graph_revision)}:{},...Zr(p.terminal_git_receipt)?{terminal_git_receipt:Zr(p.terminal_git_receipt)}:{},...C?{lifecycle_classification:C}:{}}}const y=Po(i.current_session??i.currentSession),w=h(i.archPlan)?hn(i.archPlan.execution):void 0,u=i.epic_id_ledger,v=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(I=>typeof I=="string"&&/^P\d+$/.test(I)))].slice(0,2048):[];return{schema_version:typeof i.schema_version=="number"?i.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:f,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...y?{current_session:y}:{},...w?{archPlan:{execution:w}}:{}}}const Fn=[["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"]],qn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Yn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",ti="30dccfff07f9c969be11ae1d28e62a09731a0768";function No(e,t){try{const r=t.indexOf(ti);if(r<1||t[r-1]!==qn)return new Map;const i=$e("git",["show","--no-patch","--format=%P",ti],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=$e("git",["show","--no-patch","--format=%P",Yn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(i!==`${qn} ${Yn}`||a!==`${Fn.at(-1)[1]} ${qn}`)return new Map;const n=$e("git",["rev-list","--first-parent","--reverse",Yn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
+ `),o=new Map;let s=-1;for(const[l,[f,y]]of Fn.entries()){const w=n.indexOf(y);if(w<=s)return new Map;s=w,o.set(f,{headSha:y,position:l-Fn.length})}return o}catch{return new Map}}async function Lo(e,t,r){if(!ei(r))return{};if(r==="audit"||r==="yoloop")return{};if(Ir(t,r))return{};try{const i=JSON.parse(He(K(e,".neocortex","state.json"),"utf8")),a=dn(e,{required:!0}),n=Tr(i,a),o=h(n.stories)?n.stories:{},s=h(n.epics)?n.epics:{},l=$e("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),f=$e("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),y=$e("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
+ `).filter(Boolean),w=new Map(y.map((S,R)=>[S,R])),u=No(e,y),v=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],I=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(([S,R])=>{if(v&&S!==v)return[];const Q=h(R)?R:void 0,M=h(Q?.checkpoint)?Q.checkpoint:void 0;if(!M)return[];const $=typeof Q?.epic_id=="string"?Q.epic_id:S.split(".")[0];if(I&&$!==I)return[];const N=_(M?.headSha),ae=$==="P222"?u.get(S):void 0,D=w.get(N??"")??(ae&&ae.headSha===N?ae.position:void 0);if(!N||N.length<40||D===void 0)return p.add($),[];const H=h(s[$])?s[$]:void 0;if(H?.branch_mode!=="epic"||Se(H.execution_branch)!==f||Se(M.branch)!==f)return p.add($),[];const Oe=_(M.graphRevision);if(!Oe||Oe.length!==64)return p.add($),[];const dt=_(M.claimRevision),X=[...Pr(S,Q,M)].sort(),k=Ua(e,M,S,$,f,X);if(!k&&dt){if(X.length===0)return p.add($),[];const G=$e("git",["diff-tree","--no-commit-id","--name-only","-r","-z",N],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let pt=[];if(M.rootMemoryEffect!==void 0)try{pt=$a(e,M.rootMemoryEffect,{storyId:S,executionBranch:f,baseSha:String(M.baseSha),headRef:N,childPaths:X}).files.map(We=>We.path)}catch{return p.add($),[]}if(G.length===0||G.some(We=>!X.some(Fe=>Fe===We||Fe.endsWith("/")&&We.startsWith(Fe))&&!pt.includes(We)))return p.add($),[];const Ne=Ue("sha256").update(X.join("\0")).digest("hex"),we=Ue("sha256").update(JSON.stringify(X)).digest("hex");if(dt!==Ne&&dt!==we)return p.add($),[]}else if(!k)return p.add($),[];return Oe?.length===64?[{storyId:S,epicId:$,graphRevision:Oe,checkpointHead:N,position:D}]:[]}),O=new Set(p);for(const[S,R]of Object.entries(s)){const Q=h(R)?R:void 0,M=Array.isArray(Q?.stories)?Q.stories.filter(D=>typeof D=="string"):Object.keys(o).filter(D=>D.startsWith(`${S}.`)),$=C.filter(D=>D.epicId===S),N=M.filter(D=>$.some(H=>H.storyId===D)),ae=[...$].sort((D,H)=>D.position-H.position).map(D=>D.storyId);(JSON.stringify(N)!==JSON.stringify(ae)||new Set(ae).size!==ae.length)&&O.add(S)}const V={},T=[...new Set(C.filter(S=>!O.has(S.epicId)).map(S=>S.graphRevision))],P=T.length>0?await ja(e,{headSha:l,graphRevisions:T}):new Map;for(const S of C){if(O.has(S.epicId))continue;const R=P.get(S.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");V[S.storyId]=R}return V}catch(i){const a=i instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(i.message)?i.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
+ `),{}}}function Js(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 ni="neocortex:menu:cache";async function Do(e){try{const t=await e.get(ni);if(!t)return null;const r=JSON.parse(t);return r.version!==xt||Date.now()-r.cachedAt>Nr?null:r}catch{return null}}async function Mo(e,t,r){try{const i={instructions:t,metadata:r,cachedAt:Date.now(),version:xt};await e.set(ni,JSON.stringify(i),Nr),jo()}catch{}}function jo(){try{Nt(Or)&&Tn(Or)}catch{}}function ri(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>On(),()=>On({strictReadOnly:!0}))}async function ii(e,t,r){const i=r.mode==="strict";try{let a;if(i&&t)a=new kn({cacheDir:Ln,passphrase:t,strictReadOnly:!0});else if(i)a=new hr;else if(t){const y=K(pn,"cache");a=new kn({cacheDir:y,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
+ `),a=new hr;const n=_r(r,a,"auth-cache"),o=_r(r,a,"tier-cache"),s=new Ui({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:i});let l;if(i){const y=await s.inspectToken();if(y.status!=="authenticated")return y;l=y.token}else l=await s.getToken();if(!l)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const f=new $i({cacheProvider:o,licenseClient:s});return{status:"authenticated",token:l,client:s,tierClient:f}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let ai=!1;function Vo(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 oi=3,yn=50;function Bo(e){return new Promise(t=>setTimeout(t,e))}function Uo(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Jt(e,t,r,i,a={}){const n=Math.max(1,Math.min(a.maxAttempts??oi,oi)),o=a.sleep??Bo;let s=i,l=!1,f=!1,y=0;for(let w=1;w<=n;w+=1){const u=Math.max(Math.floor(Date.now()/1e3),y+1);y=u;const v=$o(t,r,s,{nowSeconds:u}),I=new AbortController,p=setTimeout(()=>I.abort(),Lr);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:v.headers,body:v.body,signal:I.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(C))return{response:C,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const O=await C.text().catch(()=>""),V=C.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return O?JSON.parse(O):{}}catch{return{}}})();if(C.status===401&&!l&&a.refreshToken&&(V.fallback_action==="refresh_token"||V.fallback_action==="re_authenticate")){l=!0;const T=await a.refreshToken();if(T&&w<n){s=T,a.onTokenChanged?.(T),await o(yn*w);continue}}if(C.status===401&&V.error_code==="SIGNATURE_EXPIRED"&&!f&&w<n){f=!0,await o(yn*w);continue}if(w<n&&Uo(C,V,a.allowReplayRetry===!0)){await o(yn*w);continue}return{response:C,text:O,parsed:V,networkFailure:!1}}catch{if(w<n){await o(yn*w);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(p)}}return{text:"",parsed:{},networkFailure:!0}}function $o(e,t,r,i={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=da({method:"POST",target:e,body:a,bearerToken:r,clientVersion:xt,nowSeconds:i.nowSeconds,nonceBytes:i.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${r}`}}}function ci(e){return Ue("sha256").update(e).digest("hex")}function Ho(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Go(e,t,r){return`args-${Ue("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function si(e,t,r,i,a={}){const n=await Jt(e,t,r,i,{...a,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 l=typeof s.error_code=="string"?s.error_code:`HTTP_${o.status}`,f=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${l}: ${f}`)}return s}async function Wo(e,t,r,i){const a=Buffer.from(t,"utf8"),n=Ho(),o=[];for(let I=0,p=0;I<a.byteLength;I+=n,p++){const C=a.subarray(I,Math.min(I+n,a.byteLength));o.push({index:p,sha256:ci(C),byteLength:C.byteLength})}const s=ci(a),l=Go(s,a.byteLength,o),f=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let y=r;const w={refreshToken:i,onTokenChanged(I){y=I}};for(const I of o){const p=I.index*n,C=a.subarray(p,p+I.byteLength);await si(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:C.toString("base64"),ttlSeconds:f,idempotencyKey:`${l}:${I.index}:${I.sha256}`},y,w)}const v=(await si(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:s,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:f,retry:{attempt:1,budget:3,idempotencyKey:l}},y,w)).argsRef;if(!v?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:v,chunks:o}}function Bt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Fo(...e){const t=new Set,r=[];for(const i of e)for(const a of i??[]){const n=ee(a);if(!(!n||t.has(n))&&(t.add(n),r.push(n),r.length>=16))return r}return r}function qo(e){const t=e.graphRetrieval;if(!h(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 Jn(e,t=Bt(e),r=[],i={}){const a=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,s=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:i.limitBytes??Mr,warningThresholdBytes:i.warningThresholdBytes??Dn,scope:{kind:s,...a?.projectionMode?{projectionMode:a.projectionMode}:{},commandId:a?.commandId??null,stateProjectionPolicy:a?.stateProjectionPolicy??null},includedStories:a?.includedStoryCount??n,omittedStories:a?.omittedStoryCount??0,includedEpics:a?.includedEpicCount??o,omittedEpics:a?.omittedEpicCount??0,graphRetrieval:qo(e.stateSnapshot),reasonCodes:Fo(r,a?.reasonCodes),publicSafe:!0}}function Yo(e){const t=h(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 Jo(e){return h(e)?{stableId:ee(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function di(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function zo(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const r=Yo(t);let i=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>r&&i.length>0;){const o=i.pop();a=[...a,Jo(o)].slice(-32),n={...t,items:i,skipped:a,warnings:di(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:di(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function pi(e,t={}){const r=t.limitBytes??Mr,i=t.warningThresholdBytes??Math.floor(r*jr),a=Bt(e);if(a<r)return{body:e,degraded:!1,telemetry:Jn(e,a,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:i})};let n={...e,stateSnapshot:Yi(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],s=Bt(n);s>=r&&(n={...n,stateSnapshot:zo(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],s=Bt(n));const l=Jn(n,s,o,{limitBytes:r,warningThresholdBytes:i});if(s>=r){const f=n.stateSnapshot.scope?.projectionMode;throw f==="yolo-story"||f==="yoloop-target"||f==="yoloop-session"||f==="yoloop-discovery"||f==="structural-required"?new $n(l):new Un(l)}return{body:n,degraded:!0,telemetry:l}}function li(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Ko(e){const t=Bt(e);if(t<Dn)return t;const r=Jn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${li(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 ui(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${li(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 Qo(e){const t=ea(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Xo(t),metadata:hi(t)};const r=e.bootstrapper??na;let i;try{i=await r({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{i={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[ta.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=hi(t,i);if(i.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:a};const n=a.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...a,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:a,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 Xo(e){return!e.reasonCodes.includes(Zi.SKIPPED_NON_CONTINUITY_COMMAND)}function hi(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:De([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function De(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function In(e,t,r){const i=Math.floor(e??t);return Number.isFinite(i)?Math.max(1,Math.min(r,i)):t}function En(e,t){const r=process.env[e];if(!r)return t;const i=Number(r);return Number.isFinite(i)?i:t}function q(e,t=Hr){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",i=Je(r,t),a=lo.test(i)?It:i;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function zn(e,t=Hr){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function Kn(e,t,r,i){const a=zn(e?.targetId??t,120),n=e?.selectorKind??(a?Xn(a):void 0),o=(e?.relatedJobIds??[]).map(s=>zn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...n?{targetKind:n}:{},...a?{targetId:a}:{},...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:De(i.length>0?i:[F.OK]),publicSafe:!0}}function ct(e,t,r,i,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":r&&i===0?"empty":"available":"unavailable",s=zn(t[t.length-1]?.eventId,120),l=a.length>0?a: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:i,...s?{latestEventId:s}:{},reasonCodes:De(l),publicSafe:!0}}function Ze(e,t,r,i,a=[],n){const o=i[i.length-1],s=r??o?.cursor,l=!!(s&&s!==t&&i.length>0),f=n??(l?"advanced":t||s?"unchanged":"not_started"),y=a.length>0?a:f==="advanced"?[F.WATCH_CURSOR_ADVANCED]:f==="unavailable"?[F.WATCH_EVIDENCE_UNAVAILABLE]:[F.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:f,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...s?{nextCursor:q(s,200)}:{},cursorAdvanced:l,...o?.eventId?{eventId:q(o.eventId,120)}:{},reasonCodes:De(y),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:De([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Zo(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",r=e.snapshotEvidence?.renderedSummaryCount??0,i=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",l=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=${i}`,`summaries=${r}`,`snapshot=${s}`,`generatedAt=${l}`,`cursor=${a}`,`current=${q(n,200)}`,`next=${q(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function tt(e,t,r,i=!1){if(i){const a={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(a)}
15
+ `:`[watch-status] status=${a.watchStatus} active=${a.active} summaries=${a.renderedSummaryCount} stop=${a.stopReason}
16
16
  `);return}if(t==="json"){r.write(JSON.stringify(e)+`
17
- `);return}r.write(zo(e)+`
18
- `)}function Ko(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:Ko(a,t,r),publicSafe:!0}}function Qo(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",r=e.goalId?` goal=${q(e.goalId,100)}`:"",a=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${r}${a} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function Xo(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 Zo(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})}
17
+ `);return}r.write(Zo(e)+`
18
+ `)}function ec(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 st(e,t,r,i,a=!1){return a?{status:e,summariesEmitted:t,polls:r,reasonCodes:[],watchStatus:i.watchStatus,stopReason:i.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:i.watchStatus,stopReason:i.stopReason??"not_stopped",summariesEmitted:t,polls:r,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:r,reasonCodes:i.reasonCodes,watchStatus:i.watchStatus,stopReason:i.stopReason,targetEvidence:i.targetEvidence,snapshotEvidence:i.snapshotEvidence,cursorEvidence:i.cursorEvidence,statusRecord:i,metadata:ec(i,t,r),publicSafe:!0}}function tc(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",r=e.goalId?` goal=${q(e.goalId,100)}`:"",i=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${r}${i} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function nc(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 rc(e,t,r,i=!1){if(i){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"){r.write(JSON.stringify(Xo(e))+`
21
- `);return}r.write(Qo(e)+`
22
- `)}function Qn(e){return ao.has(e.status)}function ec(e,t,r){if(t){const i=e.find(n=>n.jobId===t);return!!(i&&Qn(i))}return r<=0?!1:e.filter(i=>!Qn(i)).length===0}function tc(e,t,r,a){return r<a?!1:t?!e.some(i=>i.jobId===t&&!Qn(i)):e.length===0}function nc(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 rc(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 la(e,t){const r=t?zt(t):void 0,a=Ne([...e,Se.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),i=Kn(r,r?.targetId,rc(a),a),n=ot({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Ze(void 0,void 0,void 0,[],[F.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 ac(e,t,r,a,i=!1){const n=la(e,fa(t));return tt(n,r,a,i),ct("target-unresolved",0,0,n,i)}async function ic(e){if(e.signal?.aborted){const P=Kn(e.target??zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Se.CANCELLED]),S=ot(void 0,[],!1,0),_=Ze(e.initialCursor,e.initialCursor,e.initialCursor,[],[Se.CANCELLED],"unavailable"),Q=et({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:S,cursorEvidence:_,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=la([be.MISSING,Se.TARGET_UNRESOLVED]);return tt(P,e.format,a,e.protectedOutput),ct("target-unresolved",0,0,P,e.protectedOutput)}const i=In(e.limit??En("NEOCORTEX_INVOKE_WATCH_LIMIT",Sr),Sr,50),n=Math.max(50,In(e.pollIntervalMs??En("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",wr),wr,6e4)),o=In(e.maxIdlePolls??En("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",vr),vr,120),s=In(e.maxPolls??En("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Cr),Cr,86400),u=e.sleep??nc;let g=e.initialCursor,y=0,w=0,l=0;const v=Kn(t,r,"resolved",[F.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},p=Ze(e.initialCursor,g,g,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");tt(et({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:I,cursorEvidence:p,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,a,e.protectedOutput);let C;try{C=await ni({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=ot(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,g,g,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),_=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Se.STORE_UNAVAILABLE]});return tt(_,e.format,a,e.protectedOutput),ct("store-unavailable",y,l,_,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const P=g,S=C.collectProcessingOutputSummaryCursor({...g?{cursor:g}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:i}),_=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Q=_.jobs;if(S.summaries.length>0){for(const N of S.summaries)Zo(N,e.format,a,e.protectedOutput),y+=1;g=S.nextCursor??S.summaries[S.summaries.length-1]?.cursor??g,w=0}else g=S.nextCursor??g,w+=1;const M=ot(_,S.summaries,!0,S.summaries.length),$=Ze(e.initialCursor,P,g,S.summaries,S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(tt(et({watchStatus:S.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:M,cursorEvidence:$,stopReason:"not_stopped",reasonCodes:S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:_.generatedAt}),e.format,a,e.protectedOutput),!S.hasMore&&ec(Q,r,y)){const N=ot(_,S.summaries,!1,y,[Se.COMPLETED]),ie=Ze(e.initialCursor,P,g,S.summaries,[Se.COMPLETED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ie,stopReason:"not_stopped",reasonCodes:[Se.COMPLETED],generatedAt:_.generatedAt});return tt(D,e.format,a,e.protectedOutput),ct("completed",y,l,D,e.protectedOutput)}if(!S.hasMore&&tc(Q,r,w,o)){const N=ot(_,S.summaries,!1,y,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),ie=Ze(e.initialCursor,P,g,S.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ie,stopReason:"idle_limit_reached",reasonCodes:[Se.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:_.generatedAt});return tt(D,e.format,a,e.protectedOutput),ct("idle-timeout",y,l,D,e.protectedOutput)}S.hasMore||await u(n,e.signal)}}catch{const P=ot(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,g,g,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),_=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Se.STORE_UNAVAILABLE]});return tt(_,e.format,a,e.protectedOutput),ct("store-unavailable",y,l,_,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const P=ot(void 0,[],!1,y,[Se.CANCELLED]),S=Ze(e.initialCursor,g,g,[],[Se.CANCELLED],"unavailable"),_=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"cancelled",reasonCodes:[Se.CANCELLED]});return tt(_,e.format,a,e.protectedOutput),ct("cancelled",y,l,_,e.protectedOutput)}const O=ot(void 0,[],!1,y,[F.WATCH_STOP_MAX_POLLS_REACHED]),V=Ze(e.initialCursor,g,g,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:O,cursorEvidence:V,stopReason:"max_polls_reached",reasonCodes:[Se.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return tt(T,e.format,a,e.protectedOutput),ct("max-polls",y,l,T,e.protectedOutput)}function ze(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 Xn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function ha(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=ze(a[1]);i&&t.push(i)}return Ne(t)}function fa(e){return ha(e)[0]}function zt(e){const t=e?ze(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 Zn(e){return Ne(e.filter(t=>typeof t=="string").map(t=>ze(t)).filter(t=>!!t?.startsWith("job-J")))}function oc(e,t){const r=Zn(t).filter(a=>a!==e.targetId&&a!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function cc(e){if(!e)return;const t=h(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"?ze(e.targetId):typeof t?.targetId=="string"?ze(t.targetId):typeof e.targetJobId=="string"?ze(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=Zn([...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:ze(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ze(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ze(e.loopId??t?.loopId)??i.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function ga(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"}),sc=new Set(["create","start","resume"]),dc=new Set(["create","resume","run-once"]);function er(e,t,r,a,i){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...a?{operation:a}:{},active:e,...i?{watchToken:i}:{},reasonCodes:Ne(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:er(!1,i,r,a),publicSafe:!0}}function pc(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 ga(a)?a.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?xe(e,[Re.AMBIGUOUS],"jobs","watch"):fa(a)?{args:a,watch:!0,reasonCodes:[Re.ACTIVE],metadata:er(!0,[Re.ACTIVE],"jobs","watch"),publicSafe:!0}:xe(e,[Re.TARGET_INVALID],"jobs","watch"):xe(e,[Re.UNSUPPORTED],"jobs","watch")}function uc(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 lc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function hc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?sc:dc).has(r)?r:void 0}function fc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function gc(e){const{tokens:t,malformed:r}=uc(e),a=lc(t[0]),i=hc(a,t[1]);if(r)return xe(e,[Re.MALFORMED],a,i);const n=t.filter(l=>l.value==="--watch"&&!l.quoted),o=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(fc);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 y=`${e.slice(0,g.start)}${e.slice(g.end)}`.trim(),w={literal:"--watch",position:"final",start:g.start,end:g.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[Re.ACTIVE],metadata:er(!0,[Re.ACTIVE],a,i,w),publicSafe:!0}}function mc(e){return ga(e)?pc(e):gc(e)}function yc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&io.has(t)):[]}function Bt(e){return{disabled:!0,reasonCodes:Ne(e.length>0?e:[be.MISSING])}}function tr(e,t,r=[],a){const i=zt(t);if(i)return{source:e,target:oc(i,r),targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}}function Ic(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=Ne([...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 St(e,t,r,a){return{source:e,hasEvidence:t,candidates:Ic(r.filter(i=>!!i)),...a&&a.length>0?{disabledReasonCodes:Ne(a)}:{}}}function Ec(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Kt(e,t){const r=Ne(e.filter(a=>typeof a=="string").map(a=>ze(a)).filter(a=>!!a));if(t){const a=r.find(i=>Xn(i)===t);if(a)return a}return r[0]}function Sn(e,t){return Ne(e.filter(r=>typeof r=="string").map(r=>ze(r)).filter(r=>!!r)).find(r=>Xn(r)===t)}function Sc(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.jobs)?t.jobs:void 0,a=h(r?.watcher)?r.watcher:void 0,i=yc(a?.reasonCodes??r?.reasonCodes);if(!a)return St("watcher-metadata",i.length>0,[],i);if(a.active===!1||i.length>0)return St("watcher-metadata",!0,[],i.length>0?i:[be.MALFORMED]);if(a.serverHeldStream!==!1)return St("watcher-metadata",!0,[],[be.SERVER_HELD_STREAM]);const n=cc(a);if(!n)return St("watcher-metadata",!0,[],[be.MISSING]);const o=typeof a.initialCursor=="string"?a.initialCursor:void 0;return St("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ma(e,t){const r=h(e.loopJobPlan)?e.loopJobPlan:void 0,a=h(r?.metadata)?r.metadata:void 0,i=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?Kt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Kt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,a?.loopId,a?.jobId],"loop"))??Kt([e.jobId,e.targetJobId,i?.jobId,a?.jobId]);return tr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,i?.jobId,a?.jobId])}function vc(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.goal)?t.goal:void 0,a=h(t?.loop)?t.loop:void 0,i=[r?ma(r,"goal"):void 0,a?ma(a,"loop"):void 0],n=!!(r||a);return St("goal-loop-continuity-metadata",n,i,n&&i.every(o=>!o)?[be.MISSING]:void 0)}function Cc(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function ya(e,t){const r=h(t.metadata)?t.metadata:void 0,a=Sn([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),i=Sn([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),n=Kt([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(...Zn([n,t.jobId,t.targetJobId,r?.jobId])),e.set(o,s)}function wc(e){const t=h(e.metadata)?e.metadata:void 0;return!!(Sn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Sn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function _c(e){const t=h(e.metadata)?e.metadata:void 0;return!!Kt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Ia(e,t){const r=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];h(s)&&r.push(s)}const a=h(t.event)?t.event:void 0;h(a?.metadata)&&r.push(a.metadata),h(a?.processingOutputSummary)&&r.push(a.processingOutputSummary);const i=h(t.receipt)?t.receipt:void 0;h(i?.metadata)&&r.push(i.metadata);const n=r.some(_c);for(const o of r)ya(e,o);(!n||wc(t))&&ya(e,t)}function Rc(e){const t=Cc(e?.continuityStateUpdate),r=new Map;for(const i of t){Ia(r,i);const n=Array.isArray(i.operations)?i.operations.filter(h):[];for(const o of n)Ia(r,o)}const a=Array.from(r.values()).map(i=>tr("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return St("continuity-state-update-operation-log",t.length>0,a,t.length>0&&a.every(i=>!i)?[be.MISSING]:void 0)}function Ac(e){const t=ha(e);return St("explicit-args",t.length>0,t.map(r=>tr("explicit-args",r)))}function bc(e,t){const r=[Sc(e),vc(e),Rc(e),Ac(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&&!Ec(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 Ea(e,t,r,a={}){const i="/api/v1/invoke";let n,o;const s=await Jt(e,i,t,r,{...a,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:w=>{const l=w.headers.get("X-Neocortex-Compatibility");if(l!==null)try{if(l.length===0||l.length>8192)throw new Error("header-size");const v=JSON.parse(Buffer.from(l,"base64url").toString("utf8"));if(!_i(v))throw new Error("header-shape");if(n=v,v.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return a.admitResponseBeforeBodyRead?.(w)??!0}});if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(s.responseAdmissionRejected){const w=o==="malformed"?jt.RESULT_MALFORMED:n?.reasonCodes[0]??jt.OFFER_MALFORMED;return{ok:!1,status:s.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${w}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:w,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:u,text:g}=s;let y=s.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(g))return{ok:!1,status:u.status,error:`COMPATIBILITY_INCOMPATIBLE: ${jt.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=wi({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:jt.SERVER_NEGOTIATION_MISSING})}if(u.ok)try{y=g?JSON.parse(g):{}}catch{return{ok:!1,status:u.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!u.ok)return t.privateExecution?{ok:!1,status:u.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:u.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??g}`:`HTTP ${u.status}: ${g}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const w=y,l=u.headers.get("X-Client-Version-Warning");return l&&!ra&&(ra=!0,process.stderr.write(`
23
- [Neocortex] ${l}
24
-
25
- `)),{ok:!0,status:u.status,data:w,...n?{compatibility:n}:{}}}catch(w){return{ok:!1,status:0,error:(w instanceof Error?w.message:String(w)).includes("abort")?`Request timeout after ${Nr/1e3}s`:"Network error: invalid response"}}}async function xc(e,t,r){const a=await Jt(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 Tc(e,t,r){const a=await Jt(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!a.response?.ok&&a.parsed.status==="cancelled"}async function Sa(e,t,r,a={}){const i=await Jt(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:mt,registryChecksum:gt},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 Pc(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 Sa(r,a,{claimId:g.claimId,projectId:i,epicId:g.epicId,status:"materialized"},n)||(Xi(e,u),s+=1);return s}function kc(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:[],y=g.length===1&&typeof g[0]?.storyId=="string"?g[0].storyId:"",l=e.stories[y]?.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||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const I=(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(I)return{epicId:s,expectedNextStoryId:I,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.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 Oc(e){let t;try{if(t=e.inputEnvelope??cn(e.inputSource??"args",e.args),yi(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=br(t);let i=r,n=a;const o=ro(r);if(o.outcome!=="resolved"){const c=Ei(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=jn(e.projectRoot),u=o.selection.commandId,g=u==="yolo"&&!Ir(r,u)?Bi(r):null,y=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),w=Ba.find(c=>c.id===u),l=w?.subcommands.find(c=>c.id===o.selection.operationId),v=l?l.policy.strictReadOnly==="allow":w?.policy.strictReadOnly==="allow",I=u==="diagnose";let p;try{p=fi({invocationId:nn(),intent:e.strictReadOnly||I?{schemaVersion:1,policy:ui,registryVersion:mt,registryChecksum:gt}:void 0,registryVersion:mt,registryChecksum:gt,registryAllowsStrict:v,requestCanonicalBytes:JSON.stringify({command:u})})}catch(c){if(c instanceof Dt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of Ar)p.project(c);for(const c of li)p.project(c);p.seal()}const C=p.mode==="strict";if(u==="create-epic"||u==="idea-diagnose")try{const c=xi(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 Nn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const O=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"&&!y||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=oi({cwd:s,env:O,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=V.targetId,P=e.privateExecutionBeta?void 0:ii({cwd:s,env:O,targetFlag:e.platformTarget,nativeHostVersion:lo(V,O)},V);if(g)try{Hn(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 S=g?On({strictReadOnly:!0}):ta(p);const _=(e.serverUrl??S?.serverUrl??Ga).replace(/\/+$/,"");let Q;if(g){const c=await Ui(_);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${si}; 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=Pr({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}}S=ta(p)}if(u!=="migrate-project-id"&&p.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>eo(),()=>{}),u==="migrate-project-id"){const c=await Ti(_);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=bi(s)}catch(U){const Ie=U instanceof Nn?U.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ie,errorCode:Ie,exitCode:1}}d.push(Mt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const b=mn(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 B=await na(_,S?.licenseKey,p);if(B.status!=="authenticated"){const U=B.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 he;try{he=yr(e.args.trim(),b)}catch(U){const Ie=U instanceof Er?U.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:d},exitCode:1}}let de={args:r,projectRoot:s.replace(Yt(),"~"),stateSnapshot:he,platformTarget:T,...P?{nativeHostAttestation:P}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:a,idempotencyKey:m.document.operationId,registryVersion:mt,registryChecksum:gt,compatibility:Un()};try{de=sa(de).body}catch(U){if(U instanceof Bn||U instanceof $n)return{success:!1,error:U.message,errorCode:U.code,metadata:{invokePayload:U.telemetry,invocationDiagnostics:d},exitCode:1};throw U}const ne=await Rr("invoke-query",()=>Ea(_,de,B.token,{refreshToken:()=>B.client.forceRefresh()}));if(!ne.ok||!ne.data)return d.push(Mt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:Je(ne.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",Tt),errorCode:typeof ne.errorBody?.error_code=="string"?ne.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:ne.status===401?2:1};const fe=ne.data.metadata?.projectIdentityMigration;try{Ii(fe),d.push(Mt({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ri(s,fe),d.push(Mt({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ai(s,fe),d.push(Mt({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch(U){d.push(Mt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ie=U instanceof Nn?U.code:U instanceof Error?U.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:d},exitCode:1}}return p.complete(),{success:!0,instructions:ne.data.instructions,metadata:{...ne.data.metadata,...ne.compatibility?{compatibility:ne.compatibility}:{},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}
20
+ `);return}if(t==="json"){r.write(JSON.stringify(nc(e))+`
21
+ `);return}r.write(tc(e)+`
22
+ `)}function Qn(e){return so.has(e.status)}function ic(e,t,r){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&Qn(a))}return r<=0?!1:e.filter(a=>!Qn(a)).length===0}function ac(e,t,r,i){return r<i?!1:t?!e.some(a=>a.jobId===t&&!Qn(a)):e.length===0}function oc(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",a),r()}t?.addEventListener("abort",a,{once:!0})})}function cc(e){return e.includes(xe.MALFORMED)?"malformed":e.includes(xe.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(xe.MISSING)||e.includes(Ce.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function gi(e,t){const r=t?zt(t):void 0,i=De([...e,Ce.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),a=Kn(r,r?.targetId,cc(i),i),n=ct({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Ze(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return et({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:i,generatedAt:n.generatedAt})}function sc(e,t,r,i,a=!1){const n=gi(e,mi(t));return tt(n,r,i,a),st("target-unresolved",0,0,n,a)}async function dc(e){if(e.signal?.aborted){const P=Kn(e.target??zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Ce.CANCELLED]),S=ct(void 0,[],!1,0),R=Ze(e.initialCursor,e.initialCursor,e.initialCursor,[],[Ce.CANCELLED],"unavailable"),Q=et({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:S,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Ce.CANCELLED]});return st("cancelled",0,0,Q,e.protectedOutput)}const t=e.target??zt(e.targetJobId),r=e.targetJobId??t?.targetId,i=e.stdout??process.stdout;if(!t){const P=gi([xe.MISSING,Ce.TARGET_UNRESOLVED]);return tt(P,e.format,i,e.protectedOutput),st("target-unresolved",0,0,P,e.protectedOutput)}const a=In(e.limit??En("NEOCORTEX_INVOKE_WATCH_LIMIT",Sr),Sr,50),n=Math.max(50,In(e.pollIntervalMs??En("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",wr),wr,6e4)),o=In(e.maxIdlePolls??En("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",vr),vr,120),s=In(e.maxPolls??En("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Cr),Cr,86400),l=e.sleep??oc;let f=e.initialCursor,y=0,w=0,u=0;const v=Kn(t,r,"resolved",[F.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},p=Ze(e.initialCursor,f,f,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");tt(et({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:I,cursorEvidence:p,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,i,e.protectedOutput);let C;try{C=await ia({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=ct(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,f,f,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Ce.STORE_UNAVAILABLE]});return tt(R,e.format,i,e.protectedOutput),st("store-unavailable",y,u,R,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<s;){u+=1;const P=f,S=C.collectProcessingOutputSummaryCursor({...f?{cursor:f}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:a}),R=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Q=R.jobs;if(S.summaries.length>0){for(const N of S.summaries)rc(N,e.format,i,e.protectedOutput),y+=1;f=S.nextCursor??S.summaries[S.summaries.length-1]?.cursor??f,w=0}else f=S.nextCursor??f,w+=1;const M=ct(R,S.summaries,!0,S.summaries.length),$=Ze(e.initialCursor,P,f,S.summaries,S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(tt(et({watchStatus:S.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:M,cursorEvidence:$,stopReason:"not_stopped",reasonCodes:S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:R.generatedAt}),e.format,i,e.protectedOutput),!S.hasMore&&ic(Q,r,y)){const N=ct(R,S.summaries,!1,y,[Ce.COMPLETED]),ae=Ze(e.initialCursor,P,f,S.summaries,[Ce.COMPLETED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[Ce.COMPLETED],generatedAt:R.generatedAt});return tt(D,e.format,i,e.protectedOutput),st("completed",y,u,D,e.protectedOutput)}if(!S.hasMore&&ac(Q,r,w,o)){const N=ct(R,S.summaries,!1,y,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=Ze(e.initialCursor,P,f,S.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[Ce.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:R.generatedAt});return tt(D,e.format,i,e.protectedOutput),st("idle-timeout",y,u,D,e.protectedOutput)}S.hasMore||await l(n,e.signal)}}catch{const P=ct(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,f,f,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Ce.STORE_UNAVAILABLE]});return tt(R,e.format,i,e.protectedOutput),st("store-unavailable",y,u,R,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const P=ct(void 0,[],!1,y,[Ce.CANCELLED]),S=Ze(e.initialCursor,f,f,[],[Ce.CANCELLED],"unavailable"),R=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"cancelled",reasonCodes:[Ce.CANCELLED]});return tt(R,e.format,i,e.protectedOutput),st("cancelled",y,u,R,e.protectedOutput)}const O=ct(void 0,[],!1,y,[F.WATCH_STOP_MAX_POLLS_REACHED]),V=Ze(e.initialCursor,f,f,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:O,cursorEvidence:V,stopReason:"max_polls_reached",reasonCodes:[Ce.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return tt(T,e.format,i,e.protectedOutput),st("max-polls",y,u,T,e.protectedOutput)}function ze(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),i=t[2].toUpperCase();if(!(r==="job"&&i!=="J"||r==="goal"&&i!=="G"||r==="loop"&&i!=="L"))return`${r}-${i}${t[3]}`}function Xn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function fi(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let i;for(;(i=r.exec(e))!==null;){const a=ze(i[1]);a&&t.push(a)}return De(t)}function mi(e){return fi(e)[0]}function zt(e){const t=e?ze(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 Zn(e){return De(e.filter(t=>typeof t=="string").map(t=>ze(t)).filter(t=>!!t?.startsWith("job-J")))}function pc(e,t){const r=Zn(t).filter(i=>i!==e.targetId&&i!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function lc(e){if(!e)return;const t=h(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,i=typeof e.targetId=="string"?ze(e.targetId):typeof t?.targetId=="string"?ze(t.targetId):typeof e.targetJobId=="string"?ze(e.targetJobId):void 0,a=zt(i);if(!a||r&&r!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=Zn([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==a.targetId&&s!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:ze(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ze(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ze(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function yi(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),i=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&i==="watch"}const Ae=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"}),uc=new Set(["create","start","resume"]),hc=new Set(["create","resume","run-once"]);function er(e,t,r,i,a){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...i?{operation:i}:{},active:e,...a?{watchToken:a}:{},reasonCodes:De(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Pe(e,t=[],r,i){const a=t.length>0?t:[Ae.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:er(!1,a,r,i),publicSafe:!0}}function gc(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(n=>n==="--watch").length;if(r===0)return Pe(e,[],"jobs","watch");if(r!==1)return Pe(e,[Ae.AMBIGUOUS],"jobs","watch");const i=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return yi(i)?i.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Pe(e,[Ae.AMBIGUOUS],"jobs","watch"):mi(i)?{args:i,watch:!0,reasonCodes:[Ae.ACTIVE],metadata:er(!0,[Ae.ACTIVE],"jobs","watch"),publicSafe:!0}:Pe(e,[Ae.TARGET_INVALID],"jobs","watch"):Pe(e,[Ae.UNSUPPORTED],"jobs","watch")}function fc(e){const t=[];let r=!1,i=0;for(;i<e.length;){for(;i<e.length&&/\s/.test(e[i]);)i+=1;if(i>=e.length)break;const a=i;let n="",o=!1,s=null;for(;i<e.length;){const l=e[i];if(s){if(l===s){o=!0,s=null,i+=1;continue}if(l==="\\"&&i+1<e.length){n+=e[i+1],i+=2;continue}n+=l,i+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){o=!0,s=l,i+=1;continue}n+=l,i+=1}s&&(r=!0),t.push({value:n,start:a,end:i,quoted:o})}return{tokens:t,malformed:r}}function mc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function yc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?uc:hc).has(r)?r:void 0}function Ic(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Ec(e){const{tokens:t,malformed:r}=fc(e),i=mc(t[0]),a=yc(i,t[1]);if(r)return Pe(e,[Ae.MALFORMED],i,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),s=t.filter(Ic);if(!(n.length>0||o.length>0||s.length>0))return Pe(e,[],i,a);if(n.length>1)return Pe(e,[Ae.DUPLICATE],i,a);if(n.length===1&&(o.length>0||s.length>0))return Pe(e,[Ae.AMBIGUOUS],i,a);if(o.length>0)return Pe(e,[Ae.QUOTED],i,a);if(s.length>0)return Pe(e,[Ae.MALFORMED],i,a);const f=n[0];if(!f)return Pe(e,[],i,a);if(t[t.length-1]!==f)return Pe(e,[Ae.NON_FINAL],i,a);if(!i||!a)return Pe(e,[Ae.UNRESOLVED],i,a);const y=`${e.slice(0,f.start)}${e.slice(f.end)}`.trim(),w={literal:"--watch",position:"final",start:f.start,end:f.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[Ae.ACTIVE],metadata:er(!0,[Ae.ACTIVE],i,a,w),publicSafe:!0}}function Sc(e){return yi(e)?gc(e):Ec(e)}function vc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&po.has(t)):[]}function Ut(e){return{disabled:!0,reasonCodes:De(e.length>0?e:[xe.MISSING])}}function tr(e,t,r=[],i){const a=zt(t);if(a)return{source:e,target:pc(a,r),targetJobId:a.targetId,...i?{initialCursor:i}:{},serverHeldStream:!1}}function Cc(e){const t=new Map;for(const r of e){const i=`${r.target.selectorKind}:${r.target.targetId}`,a=t.get(i);if(!a){t.set(i,r);continue}const n=De([...a.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(i,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??r.initialCursor})}return Array.from(t.values())}function St(e,t,r,i){return{source:e,hasEvidence:t,candidates:Cc(r.filter(a=>!!a)),...i&&i.length>0?{disabledReasonCodes:De(i)}:{}}}function wc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Kt(e,t){const r=De(e.filter(i=>typeof i=="string").map(i=>ze(i)).filter(i=>!!i));if(t){const i=r.find(a=>Xn(a)===t);if(i)return i}return r[0]}function Sn(e,t){return De(e.filter(r=>typeof r=="string").map(r=>ze(r)).filter(r=>!!r)).find(r=>Xn(r)===t)}function _c(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.jobs)?t.jobs:void 0,i=h(r?.watcher)?r.watcher:void 0,a=vc(i?.reasonCodes??r?.reasonCodes);if(!i)return St("watcher-metadata",a.length>0,[],a);if(i.active===!1||a.length>0)return St("watcher-metadata",!0,[],a.length>0?a:[xe.MALFORMED]);if(i.serverHeldStream!==!1)return St("watcher-metadata",!0,[],[xe.SERVER_HELD_STREAM]);const n=lc(i);if(!n)return St("watcher-metadata",!0,[],[xe.MISSING]);const o=typeof i.initialCursor=="string"?i.initialCursor:void 0;return St("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Ii(e,t){const r=h(e.loopJobPlan)?e.loopJobPlan:void 0,i=h(r?.metadata)?r.metadata:void 0,a=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?Kt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):Kt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,i?.loopId,i?.jobId],"loop"))??Kt([e.jobId,e.targetJobId,a?.jobId,i?.jobId]);return tr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,i?.jobId])}function Rc(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.goal)?t.goal:void 0,i=h(t?.loop)?t.loop:void 0,a=[r?Ii(r,"goal"):void 0,i?Ii(i,"loop"):void 0],n=!!(r||i);return St("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[xe.MISSING]:void 0)}function Ac(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ei(e,t){const r=h(t.metadata)?t.metadata:void 0,i=Sn([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),a=Sn([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),n=Kt([t.jobId,t.targetJobId,r?.jobId],"job"),o=i??a??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...Zn([n,t.jobId,t.targetJobId,r?.jobId])),e.set(o,s)}function bc(e){const t=h(e.metadata)?e.metadata:void 0;return!!(Sn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Sn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function xc(e){const t=h(e.metadata)?e.metadata:void 0;return!!Kt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Si(e,t){const r=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];h(s)&&r.push(s)}const i=h(t.event)?t.event:void 0;h(i?.metadata)&&r.push(i.metadata),h(i?.processingOutputSummary)&&r.push(i.processingOutputSummary);const a=h(t.receipt)?t.receipt:void 0;h(a?.metadata)&&r.push(a.metadata);const n=r.some(xc);for(const o of r)Ei(e,o);(!n||bc(t))&&Ei(e,t)}function Tc(e){const t=Ac(e?.continuityStateUpdate),r=new Map;for(const a of t){Si(r,a);const n=Array.isArray(a.operations)?a.operations.filter(h):[];for(const o of n)Si(r,o)}const i=Array.from(r.values()).map(a=>tr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return St("continuity-state-update-operation-log",t.length>0,i,t.length>0&&i.every(a=>!a)?[xe.MISSING]:void 0)}function Pc(e){const t=fi(e);return St("explicit-args",t.length>0,t.map(r=>tr("explicit-args",r)))}function kc(e,t){const r=[_c(e),Rc(e),Tc(e),Pc(t)];for(let i=0;i<r.length;i+=1){const a=r[i];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Ut(a.disabledReasonCodes);if(a.candidates.length!==1)return Ut([a.candidates.length>1?xe.AMBIGUOUS:xe.MISSING]);const n=a.candidates[0];for(const o of r.slice(i+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Ut(o.disabledReasonCodes);if(o.candidates.length>1)return Ut([xe.AMBIGUOUS]);const s=o.candidates[0];if(s&&!wc(n,s))return Ut([xe.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Ut([xe.MISSING])}async function vi(e,t,r,i={}){const a="/api/v1/invoke";let n,o;const s=await Jt(e,a,t,r,{...i,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:w=>{const u=w.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const v=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Aa(v))throw new Error("header-shape");if(n=v,v.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return i.admitResponseBeforeBodyRead?.(w)??!0}});if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(s.responseAdmissionRejected){const w=o==="malformed"?jt.RESULT_MALFORMED:n?.reasonCodes[0]??jt.OFFER_MALFORMED;return{ok:!1,status:s.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${w}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:w,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:l,text:f}=s;let y=s.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(f))return{ok:!1,status:l.status,error:`COMPATIBILITY_INCOMPATIBLE: ${jt.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Ra({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:jt.SERVER_NEGOTIATION_MISSING})}if(l.ok)try{y=f?JSON.parse(f):{}}catch{return{ok:!1,status:l.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!l.ok)return t.privateExecution?{ok:!1,status:l.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:l.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??f}`:`HTTP ${l.status}: ${f}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const w=y,u=l.headers.get("X-Client-Version-Warning");return u&&!ai&&(ai=!0,process.stderr.write(`
23
+ [Neocortex] ${u}
24
+
25
+ `)),{ok:!0,status:l.status,data:w,...n?{compatibility:n}:{}}}catch(w){return{ok:!1,status:0,error:(w instanceof Error?w.message:String(w)).includes("abort")?`Request timeout after ${Lr/1e3}s`:"Network error: invalid response"}}}async function Oc(e,t,r){const i=await Jt(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(i.networkFailure||!i.response||!i.response.ok)throw new Error("private-execution-delivery-unavailable");return i.parsed}async function Nc(e,t,r){const i=await Jt(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!i.response?.ok&&i.parsed.status==="cancelled"}async function Ci(e,t,r,i={}){const a=await Jt(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:yt,registryChecksum:mt},t,i);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===r.status&&(!r.planningCheckpoint||a.parsed.memoryReceiptId===r.planningCheckpoint.memoryReceiptId)}async function Lc(e,t,r,i,a,n={}){if(!a)return 0;const o=Vt(e);let s=0;for(const[l,f]of Object.entries(o.operations))f.planningProtocol==="root-staged-v1"||!f.claimId||!f.epicId||!t.epics?.[f.epicId]||!await Ci(r,i,{claimId:f.claimId,projectId:a,epicId:f.epicId,status:"materialized"},n)||(no(e,l),s+=1);return s}function Dc(e,t){const r=t.state.pendingContinuationAuthorities,i=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!i)return;const a=r[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof i.epicId=="string"?i.epicId:"",l=e.epics[s],f=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],y=f.length===1&&typeof f[0]?.storyId=="string"?f[0].storyId:"",u=e.stories[y]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const I=(Array.isArray(l.stories)?l.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(I)return{epicId:s,expectedNextStoryId:I,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:u.storyId,epicId:u.epicId,branch:u.branch,baseSha:u.baseSha,headSha:u.headSha,receiptRefs:[...u.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Mc(e){let t;try{if(t=e.inputEnvelope??cn(e.inputSource??"args",e.args),Ea(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,i=br(t);let a=r,n=i;const o=co(r);if(o.outcome!=="resolved"){const c=va(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=jn(e.projectRoot),l=o.selection.commandId,f=l==="yolo"&&!Ir(r,l)?Wa(r):null,y=l==="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),w=Hi.find(c=>c.id===l),u=w?.subcommands.find(c=>c.id===o.selection.operationId),v=u?u.policy.strictReadOnly==="allow":w?.policy.strictReadOnly==="allow",I=l==="diagnose";let p;try{p=ma({invocationId:nn(),intent:e.strictReadOnly||I?{schemaVersion:1,policy:ha,registryVersion:yt,registryChecksum:mt}:void 0,registryVersion:yt,registryChecksum:mt,registryAllowsStrict:v,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Dt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of Ar)p.project(c);for(const c of ga)p.project(c);p.seal()}const C=p.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=Pa(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 Nn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const O=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!y||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=sa({cwd:s,env:O,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=V.targetId,P=e.privateExecutionBeta?void 0:ca({cwd:s,env:O,targetFlag:e.platformTarget,nativeHostVersion:mo(V,O)},V);if(f)try{Wn(s,{allowMissingRuntime:!0})}catch(c){const d=c instanceof ot?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 S=f?On({strictReadOnly:!0}):ri(p);const R=(e.serverUrl??S?.serverUrl??Wi).replace(/\/+$/,"");let Q;if(f){const c=await Ga(R);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${pa}; 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=kr({projectRoot:s,storyId:f,epicId:f.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}}S=ri(p)}if(l!=="migrate-project-id"&&p.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>io(),()=>{}),l==="migrate-project-id"){const c=await ka(R);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=Ta(s)}catch(B){const Ie=B instanceof Nn?B.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ie,errorCode:Ie,exitCode:1}}d.push(Mt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const b=mn(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 U=await ii(R,S?.licenseKey,p);if(U.status!=="authenticated"){const B=U.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 he;try{he=yr(e.args.trim(),b)}catch(B){const Ie=B instanceof Er?B.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:d},exitCode:1}}let de={args:r,projectRoot:s.replace(Yt(),"~"),stateSnapshot:he,platformTarget:T,...P?{nativeHostAttestation:P}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:i,idempotencyKey:m.document.operationId,registryVersion:yt,registryChecksum:mt,compatibility:Bn()};try{de=pi(de).body}catch(B){if(B instanceof Un||B instanceof $n)return{success:!1,error:B.message,errorCode:B.code,metadata:{invokePayload:B.telemetry,invocationDiagnostics:d},exitCode:1};throw B}const ne=await Rr("invoke-query",()=>vi(R,de,U.token,{refreshToken:()=>U.client.forceRefresh()}));if(!ne.ok||!ne.data)return d.push(Mt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:Je(ne.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",Tt),errorCode:typeof ne.errorBody?.error_code=="string"?ne.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:ne.status===401?2:1};const ge=ne.data.metadata?.projectIdentityMigration;try{Sa(ge),d.push(Mt({phase:"seed",outcome:ge.status,floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId})),ba(s,ge),d.push(Mt({phase:"remote-acknowledged",outcome:ge.status,floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId})),xa(s,ge),d.push(Mt({phase:"finalize",outcome:"finalized",floor:ge.acceptedLegacyFloor,licenseId:"local-client",projectId:ge.projectId}))}catch(B){d.push(Mt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ie=B instanceof Nn?B.code:B instanceof Error?B.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:d},exitCode:1}}return p.complete(),{success:!0,instructions:ne.data.instructions,metadata:{...ne.data.metadata,...ne.compatibility?{compatibility:ne.compatibility}:{},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}
28
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(",")}
29
29
  `))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
30
- `),{success:!1,error:c,exitCode:1}}const M=Xr(u);if(M)try{Hn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Oi(s),async()=>{}),Hn(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"},()=>Ya(s,{args:e.args,canonicalCommandId:u}),()=>{})}catch(c){if(c instanceof Ja)return process.stderr.write(`${c.message}
30
+ `),{success:!1,error:c,exitCode:1}}const M=ei(l);if(M)try{Wn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Ma(s),async()=>{}),Wn(s))}catch(c){const d=c instanceof ot?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(l!=="migrate-state")try{p.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>zi(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof Ki)return process.stderr.write(`${c.message}
32
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.
33
- `),{success:!1,error:d,exitCode:1}}let $;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"||y))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");$=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 Po(s,e.args,u);N=mn(s,{epicAware:M,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.
33
+ `),{success:!1,error:d,exitCode:1}}let $;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||y))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");$=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 Lo(s,e.args,l);N=mn(s,{epicAware:M,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const d=c instanceof ot?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
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
35
  `),warn:m=>process.stderr.write(`${m}
36
- `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},i=d.args,n=br(cn(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=kc(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.
36
+ `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},a=d.args,n=br(cn(t.source,a)))}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=Dc(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
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:!I});d&&(N.continuity=d)}catch(c){if(c instanceof Dt)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
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
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
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(so(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.
42
+ `)}try{if(ho(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
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 ie=S?.licenseKey?new kn({cacheDir:Ln,passphrase:S.licenseKey,strictReadOnly:C}):null,D=i.trim();if(!D&&ie){const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>ko(ie),async()=>null);if(c)return p.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const G=await na(_,S?.licenseKey,p);if(G.status!=="authenticated"){const c=G.status==="refresh-required",d=!c&&S&&!S.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=mr(),b=fr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);b&&process.stderr.write(gr(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"},()=>Pc(s,N,_,G.token,Pe,{refreshToken:()=>G.client.forceRefresh()}),async()=>0)}catch{}const st=Nc(D);if(st&&!I)try{const c=await G.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 Yo({args:D,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}
44
+ `)}const ae=S?.licenseKey?new kn({cacheDir:Ln,passphrase:S.licenseKey,strictReadOnly:C}):null,D=a.trim();if(!D&&ae){const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Do(ae),async()=>null);if(c)return p.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const H=await ii(R,S?.licenseKey,p);if(H.status!=="authenticated"){const c=H.status==="refresh-required",d=!c&&S&&!S.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=mr(),b=gr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);b&&process.stderr.write(fr(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 Oe=N.config.project_id;try{await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Lc(s,N,R,H.token,Oe,{refreshToken:()=>H.client.forceRefresh()}),async()=>0)}catch{}const dt=jc(D);if(dt&&!I)try{const c=await H.tierClient.preFlightCheck(dt);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 Qo({args:D,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
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??ti;N.runnerOperationalStatus=await c(X.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:p})}catch{}let k;try{const c=qa(D,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}}k=c?.snapshot??yr(D,N),on(D)==="migrate-state"&&(k={...k,migrationAuthority:za(s)})}catch(c){if(c instanceof Ka)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Er){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 B=b.store.listRecentNativeAgentDispatches(20);B.length>0&&(k.nativeAgentDispatches=B)}finally{b.store.close()}}}catch{}const W=on(D);let dt=!1;if(W==="arch-plan"&&!C&&k.archPlan?.execution===void 0){const c=xa(i);if(c)try{if(!Object.hasOwn(N.epics,c)||!Object.hasOwn(k.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=Wt(s,c);k={...k,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((W==="arch-plan"||W?.startsWith("arch-")||W==="generate-pacts"||W==="update-memory")&&k.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=k.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Wt(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 ke=Pe;if((W==="create-epic"||W==="idea-diagnose")&&!ke){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"},()=>W==="create-epic"||W==="idea-diagnose"?Qi(s,D,W):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const He=ve?.key??(W==="yolo"?Zi(s,D,ke,k):void 0);if(e.privateExecutionBeta&&W==="create-epic"&&ve){const c=Vt(s).operations[ve.fingerprint],d=c?.epicId?N.epics[c.epicId]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(k={...k,epics:{...k.epics,[c.epicId]:d},stories:{...k.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 Fe=C?{schemaVersion:1,invocationId:p.invocationId,intent:p.intent,clientProjection:hi(Ar.map(c=>({...c,count:1})))}:void 0;let Z,le,oe;if(e.privateExecutionBeta&&W==="idea-research")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(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=z(s,".neocortex/state.json"),B=Lt(b);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const he=Be(b),de=JSON.parse(he.toString("utf8")),ne=pr(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,U=h(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==m.receiptId||!E(U,m))throw new Error("planning-research-predecessor-drift");const Ie=[".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 ge 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[ge];for(const ge of Ie){const De=Lt(z(s,ge));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Qe=Ue("git",["show",`HEAD:${ge}`],{cwd:s,env:Le,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Be(z(s,ge)).equals(Qe))throw new Error("planning-research-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ve("sha256").update(he).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&W==="generate-epic")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(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=z(s,".neocortex/state.json"),B=Lt(b);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const he=Be(b),de=JSON.parse(he.toString("utf8")),ne=ur(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,U=h(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==m.receiptId||!E(U,m))throw new Error("planning-generation-predecessor-drift");const Ie=[".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 ge 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[ge];for(const ge of Ie){const De=Lt(z(s,ge));if(!De.isFile()||De.isSymbolicLink()||De.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Qe=Ue("git",["show",`HEAD:${ge}`],{cwd:s,env:Le,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Be(z(s,ge)).equals(Qe))throw new Error("planning-generation-source-uncommitted")}oe={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,researchReceiptId:ne.researchReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:ne.physicalAcceptanceReceiptId,sourceStateSha256:Ve("sha256").update(he).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 vt=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(W==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="ask-user")try{if(qe=sr(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 Ye;if(W==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="delegate"&&k.archPlan.execution.childStatus==="succeeded")try{if(Ye=sr(s),!Ye||!E(k.archPlan.execution.pactAnswerReceipt,Ye))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let j,ce,J;if(e.privateExecutionBeta&&W==="generate-pacts")try{const c=i.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(ce=ba(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!ce||!E(d.pactAnswerReceipt,ce.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Ta(s,ce.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");j=m.writeSet,J={schemaVersion:1,targetEpicId:c,graphRevision:ce.receipt.graphRevision,answersSha256:ce.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 Oe,se;if(e.privateExecutionBeta&&W==="arch-ux-design")try{const c=i.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=k.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");Oe=m(s,c),se={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Oe.adapterId,authoritySha256:Oe.authoritySha256,pathsSha256:Oe.pathsSha256,screenCount:Oe.screenCount,pathCount:Oe.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ct,Ke,me;if(e.privateExecutionBeta&&W==="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");Ct=m.choices,Ke=m.plan,me=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(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},...J?{pactExecutionInput:J}:{},...se?{uxExecutionInput:se}:{},...me?{propertyTestExecutionInput:me}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:ke,inputEvidence:n,idempotencyKey:He,registryVersion:mt,registryChecksum:gt,compatibility:Un(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}};const vn=Ut(Y);if(!C&&e.inputSource&&e.inputSource!=="args"&&vn>=Dn)try{Y={argsRef:(await pi(p,"secondary-mutation",()=>Bo(_,i,G.token,()=>G.client.forceRefresh()),async()=>{throw new Dt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:ke,inputEvidence:n,idempotencyKey:He,registryVersion:mt,registryChecksum:gt,compatibility:Un(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}}}catch(c){return c instanceof Dt?{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(W==="yolo"&&k.scope?.projectionMode==="yolo-story"){const c=k.scope?.targetStoryId,d=k.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=$i(Q);if(/\sbranchless-preparation\s*$/.test(i))Y={...Y,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:b,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");await B({projectRoot:s,storyId:c,epicId:d});const he=b({projectRoot:s,defaultBranch:k.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d});Y={...Y,yoloSpecEnvelope:m,yoloChangeEvidence:he}}}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=sa(Y);if(W==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};Y=c.body,c.degraded?pa(Y,c.telemetry):qo(Y)}catch(c){if(c instanceof Bn||c instanceof $n)return pa(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(W==="yolo"&&Y.yoloSpecEnvelope)try{const c=Pr({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:k.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=W==="arch-plan"?Y.stateSnapshot.archPlan?.execution:void 0;let wt;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=Be(z(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=h(d.archPlan)?d.archPlan.execution:void 0;if(dt?m!==void 0||!h(d.epics)||!Object.hasOwn(d.epics,String(x.targetEpicId))||x.graphSource!=="committed-epic-v1"||x.graphRevision!==Wt(s,String(x.targetEpicId)):!E(hn(m),x))throw new Error("architecture-root-state-binding-invalid");if(wt=Ve("sha256").update(c).digest("hex"),qe&&qe.stateSha256!==wt)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,or(x))}:x;if(!Gt(x.terminalMemoryCheckpoint,x)||!E(x.terminalMemoryCheckpoint,xn(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 Rr("invoke-query",()=>Ea(_,Y,G.token,{refreshToken:()=>G.client.forceRefresh()})),pt;if(C&&f.ok)try{if(I){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 Dt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;gi(p,c),I&&Si(f.data?.metadata.strictDiagnose,r,f.data?.instructions??""),pt=c.security}catch(c){const d=c instanceof Dt?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(`
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??ra;N.runnerOperationalStatus=await c(X.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:p})}catch{}let k;try{const c=Ji(D,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}}k=c?.snapshot??yr(D,N),on(D)==="migrate-state"&&(k={...k,migrationAuthority:Qi(s)})}catch(c){if(c instanceof Xi)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Er){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 U=b.store.listRecentNativeAgentDispatches(20);U.length>0&&(k.nativeAgentDispatches=U)}finally{b.store.close()}}}catch{}const G=on(D);let pt=!1;if(G==="arch-plan"&&!C&&k.archPlan?.execution===void 0){const c=Pi(a);if(c)try{if(!Object.hasOwn(N.epics,c)||!Object.hasOwn(k.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=Gt(s,c);k={...k,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},pt=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((G==="arch-plan"||G?.startsWith("arch-")||G==="generate-pacts"||G==="update-memory")&&k.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=k.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=Oe;if((G==="create-epic"||G==="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 we;try{we=p.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>G==="create-epic"||G==="idea-diagnose"?to(s,D,G):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const We=we?.key??(G==="yolo"?ro(s,D,Ne,k):void 0);if(e.privateExecutionBeta&&G==="create-epic"&&we){const c=Vt(s).operations[we.fingerprint],d=c?.epicId?N.epics[c.epicId]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(k={...k,epics:{...k.epics,[c.epicId]:d},stories:{...k.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 Fe=C?{schemaVersion:1,invocationId:p.invocationId,intent:p.intent,clientProjection:fa(Ar.map(c=>({...c,count:1})))}:void 0;let Z,ue,oe;if(e.privateExecutionBeta&&G==="idea-research")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(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=K(s,".neocortex/state.json"),U=Lt(b);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const he=He(b),de=JSON.parse(he.toString("utf8")),ne=pr(de,m.claimId,c),ge=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,B=h(ge?.createEpicPlanningPhysical)?ge.createEpicPlanningPhysical:void 0;if(B?.receiptId!==m.receiptId||!E(B,m))throw new Error("planning-research-predecessor-drift");const Ie=[".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`],Me={...process.env};for(const fe 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 Me[fe];for(const fe of Ie){const je=Lt(K(s,fe));if(!je.isFile()||je.isSymbolicLink()||je.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Qe=$e("git",["show",`HEAD:${fe}`],{cwd:s,env:Me,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!He(K(s,fe)).equals(Qe))throw new Error("planning-research-source-uncommitted")}ue={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ue("sha256").update(he).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&G==="generate-epic")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(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=K(s,".neocortex/state.json"),U=Lt(b);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const he=He(b),de=JSON.parse(he.toString("utf8")),ne=lr(de,m.claimId,c),ge=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,B=h(ge?.createEpicPlanningResearchPhysical)?ge.createEpicPlanningResearchPhysical:void 0;if(B?.receiptId!==m.receiptId||!E(B,m))throw new Error("planning-generation-predecessor-drift");const Ie=[".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`],Me={...process.env};for(const fe 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 Me[fe];for(const fe of Ie){const je=Lt(K(s,fe));if(!je.isFile()||je.isSymbolicLink()||je.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Qe=$e("git",["show",`HEAD:${fe}`],{cwd:s,env:Me,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!He(K(s,fe)).equals(Qe))throw new Error("planning-generation-source-uncommitted")}oe={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,researchReceiptId:ne.researchReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:ne.physicalAcceptanceReceiptId,sourceStateSha256:Ue("sha256").update(he).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 vt=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(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="ask-user")try{if(qe=sr(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 Ye;if(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="delegate"&&k.archPlan.execution.childStatus==="succeeded")try{if(Ye=sr(s),!Ye||!E(k.archPlan.execution.pactAnswerReceipt,Ye))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let j,ce,z;if(e.privateExecutionBeta&&G==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(ce=Ti(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!ce||!E(d.pactAnswerReceipt,ce.receipt))throw new Error("private-execution-pact-admission-unverified");const m=ki(s,ce.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");j=m.writeSet,z={schemaVersion:1,targetEpicId:c,graphRevision:ce.receipt.graphRevision,answersSha256:ce.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 Le,se;if(e.privateExecutionBeta&&G==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=k.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");Le=m(s,c),se={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Le.adapterId,authoritySha256:Le.authoritySha256,pathsSha256:Le.pathsSha256,screenCount:Le.screenCount,pathCount:Le.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ct,Ke,me;if(e.privateExecutionBeta&&G==="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");Ct=m.choices,Ke=m.plan,me=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Y={args:a,projectRoot:s.replace(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},...z?{pactExecutionInput:z}:{},...se?{uxExecutionInput:se}:{},...me?{propertyTestExecutionInput:me}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:yt,registryChecksum:mt,compatibility:Bn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}};const vn=Bt(Y);if(!C&&e.inputSource&&e.inputSource!=="args"&&vn>=Dn)try{Y={argsRef:(await ua(p,"secondary-mutation",()=>Wo(R,a,H.token,()=>H.client.forceRefresh()),async()=>{throw new Dt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:yt,registryChecksum:mt,compatibility:Bn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}}}catch(c){return c instanceof Dt?{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(G==="yolo"&&k.scope?.projectionMode==="yolo-story"){const c=k.scope?.targetStoryId,d=k.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=Fa(Q);if(/\sbranchless-preparation\s*$/.test(a))Y={...Y,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:b,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");await U({projectRoot:s,storyId:c,epicId:d});const he=b({projectRoot:s,defaultBranch:k.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d});Y={...Y,yoloSpecEnvelope:m,yoloChangeEvidence:he}}}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=pi(Y);if(G==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};Y=c.body,c.degraded?ui(Y,c.telemetry):Ko(Y)}catch(c){if(c instanceof Un||c instanceof $n)return ui(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(G==="yolo"&&Y.yoloSpecEnvelope)try{const c=kr({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:k.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=G==="arch-plan"?Y.stateSnapshot.archPlan?.execution:void 0;let wt;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=He(K(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=h(d.archPlan)?d.archPlan.execution:void 0;if(pt?m!==void 0||!h(d.epics)||!Object.hasOwn(d.epics,String(x.targetEpicId))||x.graphSource!=="committed-epic-v1"||x.graphRevision!==Gt(s,String(x.targetEpicId)):!E(hn(m),x))throw new Error("architecture-root-state-binding-invalid");if(wt=Ue("sha256").update(c).digest("hex"),qe&&qe.stateSha256!==wt)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,or(x))}:x;if(!Ht(x.terminalMemoryCheckpoint,x)||!E(x.terminalMemoryCheckpoint,xn(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 g=await Rr("invoke-query",()=>vi(R,Y,H.token,{refreshToken:()=>H.client.forceRefresh()})),lt;if(C&&g.ok)try{if(I){const d=g.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(b=>d[b]!==void 0))throw new Dt("readonly-response-conflict")}const c=g.data?.metadata.strictReadOnly;ya(p,c),I&&Ca(g.data?.metadata.strictDiagnose,r,g.data?.instructions??""),lt=c.security}catch(c){const d=c instanceof Dt?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",m=c?.min_version??"unknown";return process.stderr.write(`
52
52
  `),process.stderr.write(`==================================================
53
53
  `),process.stderr.write(` UPGRADE REQUIRED
54
54
  `),process.stderr.write(`==================================================
@@ -63,12 +63,12 @@ ${t}
63
63
  `),process.stderr.write(` After updating, re-run your command.
64
64
  `),process.stderr.write(`==================================================
65
65
 
66
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${xt} 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=Lo(f),m=to(d);if(m)return process.stderr.write(`[Neocortex] ${m.error}
67
- `),m;try{if(d){const b=mr(),B=fr(d,b);B&&process.stderr.write(gr(B,b))}}catch{}return{success:!1,error:Je(f.error??"Unknown error from server",Tt),...d?{errorCode:d}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const $t=no(f.data);if($t)return p.complete(pt),$t;let ye;try{ye=e.privateExecutionBeta&&W==="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 Qt=ye?.planningProtocol==="root-staged-v1"&&typeof ye.claimId=="string"&&typeof ye.epicId=="string"&&La(f.data,{claimId:ye.claimId,epicId:ye.epicId,...h(N.epics[ye.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:N.epics[ye.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!Qt&&!Na(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(wt&&x&&f.data.metadata?.mode==="arch-plan"&&h(f.data.metadata.archPlan)&&h(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:wt,requestExecution:x,initialBinding:dt,answerReceipt:qe,pactRecordedReceipt:Ye,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.
68
- `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!D&&f.data.metadata?.mode==="menu"&&ie&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Oo(ie,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"},()=>G.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}
69
- `),{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 (${Je(d,Tt)}).`;return process.stderr.write(`${m}
70
- `),{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"},()=>Li(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.
71
- `),{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(`
66
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${xt} is below minimum ${m}. Run: ${d}`,exitCode:3}}if(!g.ok||!g.data){const c=g.status===401?2:(g.status===429||g.status>=500,1),d=Vo(g),m=ao(d);if(m)return process.stderr.write(`[Neocortex] ${m.error}
67
+ `),m;try{if(d){const b=mr(),U=gr(d,b);U&&process.stderr.write(fr(U,b))}}catch{}return{success:!1,error:Je(g.error??"Unknown error from server",Tt),...d?{errorCode:d}:{},...g.compatibility?{metadata:{compatibility:g.compatibility}}:{},exitCode:c}}const $t=oo(g.data);if($t)return p.complete(lt),$t;let ye;try{ye=e.privateExecutionBeta&&G==="create-epic"&&we?Vt(s).operations[we.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Qt=ye?.planningProtocol==="root-staged-v1"&&typeof ye.claimId=="string"&&typeof ye.epicId=="string"&&Mi(g.data,{claimId:ye.claimId,epicId:ye.epicId,...h(N.epics[ye.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:N.epics[ye.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!Qt&&!Di(g.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(wt&&x&&g.data.metadata?.mode==="arch-plan"&&h(g.data.metadata.archPlan)&&h(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 p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>_o({projectRoot:s,sourceStateSha256:wt,requestExecution:x,initialBinding:pt,answerReceipt:qe,pactRecordedReceipt:Ye,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.
68
+ `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!D&&g.data.metadata?.mode==="menu"&&ae&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Mo(ae,g.data.instructions,g.data.metadata),async()=>{}).catch(()=>{}),g.data.metadata&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>H.tierClient.updateQuotaFromResponse(g.data.metadata),async()=>{}).catch(()=>{}),g.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(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}
69
+ `),{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),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Je(d,Tt)}).`;return process.stderr.write(`${m}
70
+ `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(g.data.metadata?.gitLifecycleGraphAuthority)try{await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Va(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.
71
+ `),{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(`
72
72
  `),process.stderr.write(`==================================================
73
73
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
74
74
  `),process.stderr.write(`==================================================
@@ -83,55 +83,55 @@ ${t}
83
83
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
84
84
  `),process.stderr.write(`==================================================
85
85
 
86
- `),{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:"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(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(g.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.
87
87
  `),{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.
88
- `),{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.
88
+ `),{success:!1,error:b,errorCode:b,exitCode:1}}}}if(g.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(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.
89
89
  `),{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.
90
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(d,Tt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await G.client.forceRefresh()?(await G.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
90
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(d,Tt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(g.data.metadata?.tier_changed){const c=g.data.metadata.current_tier;try{await H.client.forceRefresh()?(await H.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
91
91
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
92
92
  `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
93
- `)}}let te,nr=!1;if(e.privateExecutionBeta&&!Qt)try{if(!Z||!f.data.metadata?.privateExecution||!ke||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"),B=f.data.metadata.mode==="yolo",he=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",de=f.data.metadata.mode==="create-epic",ne=h(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=h(ne?.binding)?ne.binding:void 0,U=de&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(de&&!U)throw new Error("private-execution-planning-root-protocol-required");const Ie=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||U,Le=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",ge=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",De=de||Ie;if(Le&&!le||ge&&!oe)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"||y&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ee=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,ut=Ee!==void 0,wn=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",nt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",lt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",ht=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",_n=y?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",rr=y?"tech-debt-registry-v1":_n==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",We=k.archPlan?.execution,Zt=We?.targetEpicId,en=We?.graphRevision;if(ut&&(We?.currentStageCommand!==Ee||typeof Zt!="string"||!/^P[1-9][0-9]{0,11}$/.test(Zt)||typeof en!="string"||!/^[a-f0-9]{64}$/.test(en)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!J||!j||!ce||We?.currentStageCommand!=="generate-pacts"||We.continuationState!=="delegate"||We.targetEpicId!==J.targetEpicId||We.graphRevision!==J.graphRevision||!E(We.pactAnswerReceipt,ce.receipt)))throw new Error("private-execution-pact-admission-unverified");if(lt&&(!se||!Oe||We?.currentStageCommand!=="arch-ux-design"||We.continuationState!=="delegate"||We.targetEpicId!==se.targetEpicId||We.graphRevision!==se.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(ht&&(!me||!Ct||!Ke||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let ar;if(nt){const{planPactToolchainManifest:ae,preparePactToolchainCandidate:ue}=await import("../private-execution/pact-toolchain.js");try{ae(s,ce.answers.generateProvider),ar=ue(s,ce.answers.generateProvider)}catch(H){if(H.message!=="pact-toolchain-manifest-unsupported")throw H}}let _t,pe,Rn;const re=f.data.metadata.gitLifecycleGraphAuthority,Rt=f.data.metadata.privateExecutionRootAction;let Xe;if(B){if(!re||typeof re.storyId!="string"||typeof re.graphRevision!="string"||typeof re.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Xe=re.storyId,Rt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:R}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Ae}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:ft}=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:ke,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:re.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion}),at=await G.client.getToken();if(!at)throw new Error("private-execution-auth-unavailable");if(!await Tc(_,{leaseId:we.leaseId,...we.binding},at))throw new Error("private-execution-setup-lease-cancel-unverified");const Ot=je(s),tn=await Ae({projectRoot:s,storyId:Rt.storyId});if(!tn.ok)throw new Error("private-execution-root-setup-denied");await Ce(s,tn.value,Ot);const{ensurePrivateYoloIsolatedSession:At}=await import("../private-execution/isolated-session.js");await At(s,Rt.storyId,re.graphRevision,e.privateExecutionWorkspaceParent);const bt=await ft({projectRoot:s,storyId:Rt.storyId});if(!bt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${bt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:bt.value,publicSafe:!0};const An=un(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return p.complete(pt),{success:!0,instructions:`# Setup do branch validado
93
+ `)}}let te,nr=!1;if(e.privateExecutionBeta&&!Qt)try{if(!Z||!g.data.metadata?.privateExecution||!Ne||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:m,runPrivateCodexStep:b}=await import("../private-execution/codex-executor.js"),U=g.data.metadata.mode==="yolo",he=g.data.metadata.mode==="ui-ux-review"&&g.data.metadata.resolvedTrigger==="ui-ux-review",de=g.data.metadata.mode==="create-epic",ne=h(g.data.metadata.privateExecution)?g.data.metadata.privateExecution:void 0,ge=h(ne?.binding)?ne.binding:void 0,B=de&&g.data.metadata.resolvedTrigger==="create-epic"&&ge?.writeSetId==="idea-diagnosis-v1"&&g.data.metadata.stepId==="step-acd455ed";if(de&&!B)throw new Error("private-execution-planning-root-protocol-required");const Ie=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-diagnose"||B,Me=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-research",fe=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-epic",je=de||Ie;if(Me&&!ue||fe&&!oe)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"||y&&g.data.metadata.mode==="tech-debt"&&g.data.metadata.resolvedTrigger==="tech-debt",ve=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,ut=ve!==void 0,wn=ve==="arch-prd"?"arch-prd-docs-v1":ve==="update-memory"?"arch-memory-canonical-v1":ve==="arch-review"?"arch-review-doc-v1":ve==="arch-infrastructure"?"arch-infrastructure-doc-v1":ve==="arch-testing"?"arch-testing-doc-v1":ve==="arch-performance"?"arch-performance-doc-v1":ve==="arch-design-system"?"arch-design-system-doc-v1":ve==="arch-security"?"arch-security-doc-v1":ve==="arch-database"?"arch-database-doc-v1":ve==="arch-api-integrations"?"arch-api-integrations-doc-v1":ve==="arch-api-contracts"?"arch-api-contracts-docs-v1":ve==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",nt=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-pacts",ht=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="arch-ux-design",gt=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="property-test",_n=y?"tech-debt":g.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",rr=y?"tech-debt-registry-v1":_n==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ge=k.archPlan?.execution,Zt=Ge?.targetEpicId,en=Ge?.graphRevision;if(ut&&(Ge?.currentStageCommand!==ve||typeof Zt!="string"||!/^P[1-9][0-9]{0,11}$/.test(Zt)||typeof en!="string"||!/^[a-f0-9]{64}$/.test(en)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!z||!j||!ce||Ge?.currentStageCommand!=="generate-pacts"||Ge.continuationState!=="delegate"||Ge.targetEpicId!==z.targetEpicId||Ge.graphRevision!==z.graphRevision||!E(Ge.pactAnswerReceipt,ce.receipt)))throw new Error("private-execution-pact-admission-unverified");if(ht&&(!se||!Le||Ge?.currentStageCommand!=="arch-ux-design"||Ge.continuationState!=="delegate"||Ge.targetEpicId!==se.targetEpicId||Ge.graphRevision!==se.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(gt&&(!me||!Ct||!Ke||g.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let ir;if(nt){const{planPactToolchainManifest:ie,preparePactToolchainCandidate:le}=await import("../private-execution/pact-toolchain.js");try{ie(s,ce.answers.generateProvider),ir=le(s,ce.answers.generateProvider)}catch(W){if(W.message!=="pact-toolchain-manifest-unsupported")throw W}}let _t,pe,Rn;const re=g.data.metadata.gitLifecycleGraphAuthority,Rt=g.data.metadata.privateExecutionRootAction;let Xe;if(U){if(!re||typeof re.storyId!="string"||typeof re.graphRevision!="string"||typeof re.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Xe=re.storyId,Rt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:A}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:be}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:ft}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Be,recordPrivateYoloCleanBaseline:_e}=await import("../private-execution/clean-baseline.js"),Re=A(g.data.metadata.privateExecution,{projectId:Ne,commandId:"yolo",stepId:g.data.metadata.stepId,graphRevision:re.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion}),it=await H.client.getToken();if(!it)throw new Error("private-execution-auth-unavailable");if(!await Nc(R,{leaseId:Re.leaseId,...Re.binding},it))throw new Error("private-execution-setup-lease-cancel-unverified");const Ot=Be(s),tn=await be({projectRoot:s,storyId:Rt.storyId});if(!tn.ok)throw new Error("private-execution-root-setup-denied");await _e(s,tn.value,Ot);const{ensurePrivateYoloIsolatedSession:At}=await import("../private-execution/isolated-session.js");await At(s,Rt.storyId,re.graphRevision,e.privateExecutionWorkspaceParent);const bt=await ft({projectRoot:s,storyId:Rt.storyId});if(!bt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${bt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:bt.value,publicSafe:!0};const An=ln(g.data.instructions,{...g.data.metadata,...g.compatibility?{compatibility:g.compatibility}:{}});return p.complete(lt),{success:!0,instructions:`# Setup do branch validado
94
94
 
95
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...An.metadata,privateExecutionReceipt:te},exitCode:0}}let ae;try{ae=Ue("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(ae!==re.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ue=dn(s,{required:!0}),H=typeof re.epicId=="string"?ue.epics[re.epicId]:void 0,L=h(H?.branch_lease)?H.branch_lease:void 0;if(!H||H.graph_revision!==re.graphRevision||!L||L.ownerStoryId!==re.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"||de&&f.data.metadata.resolvedTrigger==="create-epic"||he||Ie||Le||ge||Qe||ut||nt||lt||ht){if(!De&&!Le&&!ge&&!Qe&&!he&&!ut&&!nt&&!lt&&!ht&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(B){const{ensurePrivateYoloIsolatedSession:ae,reconcilePrivateYoloIsolatedSession:ue}=await import("../private-execution/isolated-session.js");if(Rt?.action==="checkpoint-epic-story")await ue(s,Xe,re.graphRevision);else{const H=await ae(s,Xe,re.graphRevision,e.privateExecutionWorkspaceParent),L=await m(H.workspace.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}}if(Date.now()-Z.observedAtMs>2e4){const ae=await m(Z.projectRoot);if(ae.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=ae}const ir=await G.client.getToken();if(!ir)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"},()=>Br(s,ve.fingerprint,Me.claimId,Me.epicId,U?"root-staged-v1":void 0),()=>{}),nr=!0;const{preparePrivateYoloIsolatedWorkspace:ae,PRIVATE_EPIC_PENDING_SIDECAR:ue}=await import("../private-execution/isolated-workspace.js"),H=e.privateExecutionWorkspaceParent??z(Yt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Ht(H,{recursive:!0,mode:448}),_t=ae(s,H,!0),Rn=Ve("sha256").update(Be(z(s,ue))).digest("hex");const L=await m(_t.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}else if(!B&&!he){const{preparePrivateYoloIsolatedWorkspace:ae}=await import("../private-execution/isolated-workspace.js"),ue=e.privateExecutionWorkspaceParent??z(Yt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Ht(ue,{recursive:!0,mode:448}),pe=ae(s,ue,Le||ge),Qe||ut||nt||lt||ht){if(!$)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:L}=await import("../private-execution/isolated-workspace.js");L(pe,$)}const H=await m(pe.workspacePath);if(H.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=H}const rt=await c(f.data.metadata.privateExecution,{projectId:ke,commandId:B?"yolo":de?"create-epic":ut?Ee:nt?"generate-pacts":lt?"arch-ux-design":ht?"property-test":Qe?_n:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...B?{graphRevision:re.graphRevision}:{...De?{claimId:Me.claimId,epicId:Me.epicId,...Ie?{writeSetId:"idea-diagnosis-v1"}:{}}:Le?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:ge?{claimId:oe.claimId,epicId:oe.epicId,diagnosisReceiptId:oe.diagnosisReceiptId,researchReceiptId:oe.researchReceiptId,intakeRevision:oe.intakeRevision,physicalAcceptanceReceiptId:oe.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Qe?{writeSetId:rr}:he?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ut?{targetEpicId:Zt,graphRevision:en,writeSetId:wn}:nt?{targetEpicId:J.targetEpicId,graphRevision:J.graphRevision,answersSha256:J.answersSha256,specSha256:J.specSha256,pathsSha256:J.pathsSha256,endpointCount:J.endpointCount,pathCount:J.pathCount}:lt?{targetEpicId:se.targetEpicId,graphRevision:se.graphRevision,adapterId:se.adapterId,authoritySha256:se.authoritySha256,pathsSha256:se.pathsSha256,screenCount:se.screenCount,pathCount:se.pathCount}:ht?{prdPath:me.prdPath,prdSha256:me.prdSha256,planSha256:me.planSha256,pathsSha256:me.pathsSha256,aggregateCount:me.aggregateCount,invariantCount:me.invariantCount,pathCount:me.pathCount,language:me.language,numRuns:me.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:d(k)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion},ae=>xc(_,{...ae},ir));if(he){const{parsePrivateExecutionDescriptor:ae}=await import("../private-execution/delivery.js"),ue=ae(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:H}=await import("../private-execution/private-report-store.js");te={schemaVersion:1,outcome:"report-stored",report:await H({projectRoot:s,material:rt,format:ue.binding.format,sha256:ue.materialSha256}),publicSafe:!0}}else if(Rt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ae}=await import("../private-execution/root-checkpoint.js");te={...await ae(s,Rt)}}else{const ae=Ie?`${rt}
95
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...An.metadata,privateExecutionReceipt:te},exitCode:0}}let ie;try{ie=$e("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!==re.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const le=dn(s,{required:!0}),W=typeof re.epicId=="string"?le.epics[re.epicId]:void 0,L=h(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==re.graphRevision||!L||L.ownerStoryId!==re.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(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"||de&&g.data.metadata.resolvedTrigger==="create-epic"||he||Ie||Me||fe||Qe||ut||nt||ht||gt){if(!je&&!Me&&!fe&&!Qe&&!he&&!ut&&!nt&&!ht&&!gt&&typeof g.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(U){const{ensurePrivateYoloIsolatedSession:ie,reconcilePrivateYoloIsolatedSession:le}=await import("../private-execution/isolated-session.js");if(Rt?.action==="checkpoint-epic-story")await le(s,Xe,re.graphRevision);else{const W=await ie(s,Xe,re.graphRevision,e.privateExecutionWorkspaceParent),L=await m(W.workspace.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}}if(Date.now()-Z.observedAtMs>2e4){const ie=await m(Z.projectRoot);if(ie.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=ie}const ar=await H.client.getToken();if(!ar)throw new Error("private-execution-auth-unavailable");const Ve=je?g.data.metadata.epicClaim:void 0;if(je&&(!Ve||typeof Ve.claimId!="string"||typeof Ve.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(je){if(!we)throw new Error("private-execution-epic-claim-admission-unverified");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$r(s,we.fingerprint,Ve.claimId,Ve.epicId,B?"root-staged-v1":void 0),()=>{}),nr=!0;const{preparePrivateYoloIsolatedWorkspace:ie,PRIVATE_EPIC_PENDING_SIDECAR:le}=await import("../private-execution/isolated-workspace.js"),W=e.privateExecutionWorkspaceParent??K(Yt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Wt(W,{recursive:!0,mode:448}),_t=ie(s,W,!0),Rn=Ue("sha256").update(He(K(s,le))).digest("hex");const L=await m(_t.workspacePath);if(L.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=L}else if(!U&&!he){const{preparePrivateYoloIsolatedWorkspace:ie}=await import("../private-execution/isolated-workspace.js"),le=e.privateExecutionWorkspaceParent??K(Yt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Wt(le,{recursive:!0,mode:448}),pe=ie(s,le,Me||fe),Qe||ut||nt||ht||gt){if(!$)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:L}=await import("../private-execution/isolated-workspace.js");L(pe,$)}const W=await m(pe.workspacePath);if(W.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=W}const rt=await c(g.data.metadata.privateExecution,{projectId:Ne,commandId:U?"yolo":de?"create-epic":ut?ve:nt?"generate-pacts":ht?"arch-ux-design":gt?"property-test":Qe?_n:g.data.metadata.mode==="pipeline"?"exec":g.data.metadata.resolvedTrigger,stepId:g.data.metadata.stepId,...U?{graphRevision:re.graphRevision}:{...je?{claimId:Ve.claimId,epicId:Ve.epicId,...Ie?{writeSetId:"idea-diagnosis-v1"}:{}}:Me?{claimId:ue.claimId,epicId:ue.epicId,diagnosisReceiptId:ue.diagnosisReceiptId,intakeRevision:ue.intakeRevision,physicalAcceptanceReceiptId:ue.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:fe?{claimId:oe.claimId,epicId:oe.epicId,diagnosisReceiptId:oe.diagnosisReceiptId,researchReceiptId:oe.researchReceiptId,intakeRevision:oe.intakeRevision,physicalAcceptanceReceiptId:oe.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Qe?{writeSetId:rr}:he?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ut?{targetEpicId:Zt,graphRevision:en,writeSetId:wn}:nt?{targetEpicId:z.targetEpicId,graphRevision:z.graphRevision,answersSha256:z.answersSha256,specSha256:z.specSha256,pathsSha256:z.pathsSha256,endpointCount:z.endpointCount,pathCount:z.pathCount}:ht?{targetEpicId:se.targetEpicId,graphRevision:se.graphRevision,adapterId:se.adapterId,authoritySha256:se.authoritySha256,pathsSha256:se.pathsSha256,screenCount:se.screenCount,pathCount:se.pathCount}:gt?{prdPath:me.prdPath,prdSha256:me.prdSha256,planSha256:me.planSha256,pathsSha256:me.pathsSha256,aggregateCount:me.aggregateCount,invariantCount:me.invariantCount,pathCount:me.pathCount,language:me.language,numRuns:me.numRuns}:{storyId:g.data.metadata.storyId},stateSnapshotSha256:d(k)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion},ie=>Oc(R,{...ie},ar));if(he){const{parsePrivateExecutionDescriptor:ie}=await import("../private-execution/delivery.js"),le=ie(g.data.metadata.privateExecution);if(le.schemaVersion!==11||le.binding.commandId!=="ui-ux-review"||le.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:W}=await import("../private-execution/private-report-store.js");te={schemaVersion:1,outcome:"report-stored",report:await W({projectRoot:s,material:rt,format:le.binding.format,sha256:le.materialSha256}),publicSafe:!0}}else if(Rt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ie}=await import("../private-execution/root-checkpoint.js");te={...await ie(s,Rt)}}else{const ie=Ie?`${rt}
96
96
 
97
97
  Private P01 handoff (local only):
98
- 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.
99
- `:Le?`${rt}
98
+ The durable reserved epic ID is ${Ve.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Ve.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.
99
+ `:Me?`${rt}
100
100
 
101
101
  Private P02 handoff (local only):
102
- 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.
103
- `:ge?`${rt}
102
+ The admitted epic is ${ue.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${ue.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.
103
+ `:fe?`${rt}
104
104
 
105
105
  Private P03 handoff (local only):
106
106
  The admitted epic is ${oe.epicId}. Generate exactly docs/epics/epic-${oe.epicId}.md, 1 to 24 contiguous docs/stories/${oe.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.
107
- `:ut?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,Ee,wn,cr(k.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
107
+ `:ut?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,ve,wn,cr(k.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
108
108
 
109
109
  Private A03.5 handoff (local only):
110
110
  ${JSON.stringify({consumer:ce.answers.consumer,provider:ce.answers.provider,matchersAggressive:ce.answers.matchersAggressive,generateProvider:ce.answers.generateProvider,brokerConfigured:ce.answers.brokerUrl!==null,allowedPaths:j.paths})}
111
111
  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.
112
- `:lt?`${rt}
112
+ `:ht?`${rt}
113
113
 
114
114
  Private A08 handoff (local only):
115
- ${JSON.stringify({targetEpicId:se.targetEpicId,graphRevision:se.graphRevision,adapterId:se.adapterId,approvedScreens:Oe.screens,allowedPaths:Oe.paths})}
115
+ ${JSON.stringify({targetEpicId:se.targetEpicId,graphRevision:se.graphRevision,adapterId:se.adapterId,approvedScreens:Le.screens,allowedPaths:Le.paths})}
116
116
  Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
117
- `:ht?`${rt}
117
+ `:gt?`${rt}
118
118
 
119
119
  Private property-test handoff (local only):
120
120
  ${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}))})}
121
121
  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.
122
- `:rt;let ue=ae;if(B){const{readPrivateYoloFrozenWriteSet:L}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:R}=await import("../private-execution/frozen-handoff.js"),Ae=await L(s,Xe,re.executionBranch,re.graphRevision);ue=R(ae,Ae);const{resumePrivateYoloIsolatedSession:ft}=await import("../private-execution/isolated-session.js"),je=await ft(s,Xe,re.graphRevision),Ce=mn(s,{epicAware:!0}).stories[Xe],we=k.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=Ue("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ue+=`
122
+ `:rt;let le=ie;if(U){const{readPrivateYoloFrozenWriteSet:L}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:A}=await import("../private-execution/frozen-handoff.js"),be=await L(s,Xe,re.executionBranch,re.graphRevision);le=A(ie,be);const{resumePrivateYoloIsolatedSession:ft}=await import("../private-execution/isolated-session.js"),Be=await ft(s,Xe,re.graphRevision),_e=mn(s,{epicAware:!0}).stories[Xe],Re=k.stories[Xe];if(!_e||!Re||_e.status!==Re.status||JSON.stringify(_e.steps_completed)!==JSON.stringify(Re.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const it=$e("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();le+=`
123
123
  Root physical dispatch observations (data, not phase completion):
124
- `+JSON.stringify({storyId:Xe,graphRevision:re.graphRevision,sourceHeadSha:at,privateSnapshotSha:je.snapshotSha,effectiveStatus:Ce.status,hostKind:"codex-cli",hostVersion:Z.hostVersion})+`
124
+ `+JSON.stringify({storyId:Xe,graphRevision:re.graphRevision,sourceHeadSha:it,privateSnapshotSha:Be.snapshotSha,effectiveStatus:_e.status,hostKind:"codex-cli",hostVersion:Z.hostVersion})+`
125
125
  Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
126
- `}const H=await b(ue,Z,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...B?{expectedExecutionBranch:re.executionBranch}:_t?{expectedExecutionBranch:_t.executionBranch}:pe?{expectedExecutionBranch:pe.executionBranch}:{}});if(B){const{admitPrivateYoloIsolatedSessionStep:L}=await import("../private-execution/isolated-session.js"),R=await L(s,Xe,re.graphRevision);let Ae;if(f.data.metadata.stepId===Da){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:tn}=await import("./mutation-qa.js"),At=tn(at,Ot);if(At.headSha!==R.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let bt="not-run";if(At.outcome==="ready"){const{runAndRecordMutationQa:bn}=await import("./mutation-qa-checkpoint.js");if(bt=bn(at,Ot,At.planSha256).result.outcome,bt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:An}=await import("./mutation-qa-gate.js");if(Ce=An(at,Ot,At.planSha256),Ce.followUpDebtRequired){const{recordMutationQaFollowUpDebt:bn}=await import("./mutation-qa-checkpoint.js");we=bn(at,Ot,At.planSha256,Ce.status,bt,s)}const{resumePrivateYoloIsolatedSession:Ra}=await import("../private-execution/isolated-session.js");if((await Ra(s,Xe,re.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 ft={schemaVersion:1,outcome:R.admission.outcome,sequence:R.session.sequence,snapshotSha:R.session.snapshotSha,patchSha256:R.admission.patchSha256,changedPathCount:R.admission.changedPaths.length};te={...H,isolation:ft,...Ae?{mutationQa:Ae}:{}}}else if(_t){const{admitPrivateEpicClaimWorkspace:L,admitPrivateIdeaDiagnosisWorkspace:R}=await import("../private-execution/isolated-admission.js"),Ae=Ie?R(_t,Me.claimId,Me.epicId,ve.fingerprint,Rn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):L(_t,Me.claimId,Me.epicId,ve.fingerprint,Rn);te={...H,isolation:{schemaVersion:1,outcome:Ae.outcome,baseSha:Ae.baseSha,patchSha256:Ae.patchSha256,changedPathCount:Ae.changedPaths.length}}}else if(pe&&Le){const{admitPrivateIdeaResearchWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,le.claimId,le.epicId,le.diagnosisReceiptId,le.intakeRevision,le.sourceStateSha256);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(pe&&ge){const{admitPrivateGenerateEpicWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,oe.claimId,oe.epicId,oe.diagnosisReceiptId,oe.researchReceiptId,oe.intakeRevision,oe.sourceStateSha256);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(pe&&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"),ft=ce.answers.generateProvider,je=L(pe,J.targetEpicId,J.graphRevision,ce.receipt,j,ar),Ce=R(s,ft),we=Ae(s,j,ft);te={...H,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(pe&&lt){const{admitPrivateUxWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,se.targetEpicId,se.graphRevision,Oe);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(pe&&ht){const{admitPrivatePropertyTestWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,Ct,Ke);te={...H,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(pe&&ut){const{admitPrivateArchitectureStageWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,Ee,wn,Zt,en);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(pe&&Qe){const{admitPrivateProjectStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,_n,rr);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else if(pe){const{admitPrivateStateBoundStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),R=L(pe,f.data.metadata.storyId);te={...H,isolation:{schemaVersion:1,outcome:R.outcome,baseSha:R.baseSha,patchSha256:R.patchSha256,changedPathCount:R.changedPaths.length}}}else te={...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 Cn;if(Qt&&h(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!ye?.claimId||!ye.epicId||!ke)throw new Error("missing-reservation");const c=lr(s,ye.claimId,ye.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=mn(s,{verifyPlanningGeneration:!0}),m=d.epics[ye.epicId];if(!h(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const b={config:{project_id:ke},epics:{[ye.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(he=>[he,d.stories[he]])),epic_id_ledger:d.epic_id_ledger};if(!await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Sa(_,G.token,{claimId:ye.claimId,projectId:ke,epicId:ye.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:b}},{refreshToken:()=>G.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Cn={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 Xt=un(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),kt=te?.isolation,_a=Xt.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&&!nr&&!Qt&&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"},()=>Br(s,ve.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return p.complete(pt),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
126
+ `}const W=await b(le,Z,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...U?{expectedExecutionBranch:re.executionBranch}:_t?{expectedExecutionBranch:_t.executionBranch}:pe?{expectedExecutionBranch:pe.executionBranch}:{}});if(U){const{admitPrivateYoloIsolatedSessionStep:L}=await import("../private-execution/isolated-session.js"),A=await L(s,Xe,re.graphRevision);let be;if(g.data.metadata.stepId===ji){const Be=g.data.metadata.mutationQaFeature;if(!Be)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Be.enabled)be={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let _e,Re;try{const it=A.session.workspace.workspacePath,Ot=`sha:${A.session.workspace.baseSha}`,{planMutationQa:tn}=await import("./mutation-qa.js"),At=tn(it,Ot);if(At.headSha!==A.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let bt="not-run";if(At.outcome==="ready"){const{runAndRecordMutationQa:bn}=await import("./mutation-qa-checkpoint.js");if(bt=bn(it,Ot,At.planSha256).result.outcome,bt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:An}=await import("./mutation-qa-gate.js");if(_e=An(it,Ot,At.planSha256),_e.followUpDebtRequired){const{recordMutationQaFollowUpDebt:bn}=await import("./mutation-qa-checkpoint.js");Re=bn(it,Ot,At.planSha256,_e.status,bt,s)}const{resumePrivateYoloIsolatedSession:bi}=await import("../private-execution/isolated-session.js");if((await bi(s,Xe,re.graphRevision)).snapshotSha!==A.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(_e.blocksLocalQa||!_e.safeToContinueLocalQa&&!Re)throw new Error(`private-execution-mutation-qa-${_e.status}`);be={..._e,...Re?{followUpDebt:{status:"recorded",owner:Re.owner,severity:Re.severity,reasonCode:Re.reasonCode,planSha256:Re.planSha256,publicSafe:!0}}:{}}}}const ft={schemaVersion:1,outcome:A.admission.outcome,sequence:A.session.sequence,snapshotSha:A.session.snapshotSha,patchSha256:A.admission.patchSha256,changedPathCount:A.admission.changedPaths.length};te={...W,isolation:ft,...be?{mutationQa:be}:{}}}else if(_t){const{admitPrivateEpicClaimWorkspace:L,admitPrivateIdeaDiagnosisWorkspace:A}=await import("../private-execution/isolated-admission.js"),be=Ie?A(_t,Ve.claimId,Ve.epicId,we.fingerprint,Rn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):L(_t,Ve.claimId,Ve.epicId,we.fingerprint,Rn);te={...W,isolation:{schemaVersion:1,outcome:be.outcome,baseSha:be.baseSha,patchSha256:be.patchSha256,changedPathCount:be.changedPaths.length}}}else if(pe&&Me){const{admitPrivateIdeaResearchWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,ue.claimId,ue.epicId,ue.diagnosisReceiptId,ue.intakeRevision,ue.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(pe&&fe){const{admitPrivateGenerateEpicWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,oe.claimId,oe.epicId,oe.diagnosisReceiptId,oe.researchReceiptId,oe.intakeRevision,oe.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(pe&&nt){const{admitPrivatePactWorkspace:L}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:A}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:be}=await import("../private-execution/pact-consumer-runtime.js"),ft=ce.answers.generateProvider,Be=L(pe,z.targetEpicId,z.graphRevision,ce.receipt,j,ir),_e=A(s,ft),Re=be(s,j,ft);te={...W,isolation:{schemaVersion:1,outcome:Be.outcome,baseSha:Be.baseSha,patchSha256:Be.patchSha256,changedPathCount:Be.changedPaths.length,consumerBindingCandidateCount:Be.consumerBindingCandidateCount,consumerScaffoldCount:Be.consumerScaffoldCount,toolchain:_e,consumerRuntime:Re}}}else if(pe&&ht){const{admitPrivateUxWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,se.targetEpicId,se.graphRevision,Le);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(pe&&gt){const{admitPrivatePropertyTestWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,Ct,Ke);te={...W,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(pe&&ut){const{admitPrivateArchitectureStageWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,ve,wn,Zt,en);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(pe&&Qe){const{admitPrivateProjectStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,_n,rr);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else if(pe){const{admitPrivateStateBoundStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),A=L(pe,g.data.metadata.storyId);te={...W,isolation:{schemaVersion:1,outcome:A.outcome,baseSha:A.baseSha,patchSha256:A.patchSha256,changedPathCount:A.changedPaths.length}}}else te={...W}}}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 Cn;if(Qt&&h(g.data.metadata.planningRootContinuation)&&g.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!ye?.claimId||!ye.epicId||!Ne)throw new Error("missing-reservation");const c=ur(s,ye.claimId,ye.epicId);if(g.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=mn(s,{verifyPlanningGeneration:!0}),m=d.epics[ye.epicId];if(!h(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const b={config:{project_id:Ne},epics:{[ye.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(he=>[he,d.stories[he]])),epic_id_ledger:d.epic_id_ledger};if(!await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ci(R,H.token,{claimId:ye.claimId,projectId:Ne,epicId:ye.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:b}},{refreshToken:()=>H.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Cn={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 Xt=ln(g.data.instructions,{...g.data.metadata,...g.compatibility?{compatibility:g.compatibility}:{}}),kt=te?.isolation,Ai=Xt.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(we&&!nr&&!Qt&&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");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$r(s,we.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return p.complete(lt),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
127
127
 
128
128
  O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:te.outcome==="setup-accepted"?`# Setup do branch validado
129
129
 
130
130
  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
131
131
 
132
- Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:_a?"# 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
132
+ Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Ai?"# 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
133
133
 
134
- O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Xt.instructions,metadata:te?{...Xt.metadata,privateExecutionReceipt:te}:{...Xt.metadata,...Cn?{planningMaterialization:Cn}:{}},exitCode:0}}function Nc(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":on(t):null}const va="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Lc=`
134
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Xt.instructions,metadata:te?{...Xt.metadata,privateExecutionReceipt:te}:{...Xt.metadata,...Cn?{planningMaterialization:Cn}:{}},exitCode:0}}function jc(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":on(t):null}const wi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Vc=`
135
135
  neocortex-client invoke - Send orchestration request to server
136
136
 
137
137
  Usage:
@@ -202,12 +202,12 @@ Safety:
202
202
  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.
203
203
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
204
204
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
205
- `.trim();function Dc(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Te(e,t,r,a){return new ln("INVOCATION_MALFORMED_INPUT",t,e,r,a)}function Pt(e){return Te("missing-input-value",`${e} requires a value. ${va}`)}function Mc(e){try{if(!Pa(e).isFile())throw Te("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Be(e)}catch(t){throw t instanceof ln?t:Te("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function jc(){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 Be(0)}catch(e){throw e instanceof ln?e:Te("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Vc(e,t={}){let r,a=!1,i,n,o="plain",s=!1,u,g,y=!1,w=!1,l;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const S=e[++T];if(S===void 0)throw Pt("--args");if(r!==void 0)throw Te("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");r=S;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 S=e[++T];if(S===void 0)throw Pt("--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=S;break}case"--project-root":{const S=e[++T];if(S===void 0)throw Pt("--project-root");n=S;break}case"--format":{const S=e[++T];if(S===void 0)throw Pt("--format");if(S!=="json"&&S!=="plain")throw Te("unexpected-cli-token","--format accepts only json or plain.");o=S;break}case"--watch":s=!0;break;case"--server-url":{const S=e[++T];if(S===void 0)throw Pt("--server-url");u=S;break}case"--platform-target":{const S=e[++T];if(S===void 0)throw Pt("--platform-target");g=S;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":w=!0;break;case"--private-execution-model":{const S=e[++T];if(S===void 0)throw Pt("--private-execution-model");if(l!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(S))throw Te("unexpected-cli-token","Invalid or duplicate private execution model.");l=S;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(l!==void 0&&(!w||y))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",va);if(v.length>1)throw Te("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const I=v[0],p=I==="args"?r:I==="stdin"?(t.readStdin??jc)():(t.readArgsFile??Mc)(i);let C;try{C=cn(I,p)}catch(T){throw T instanceof vi?Te("invalid-utf8",T.message,I):T}const O=I==="args"?mc(C.rawArgs):xe(C.rawArgs),V=O.args===C.rawArgs?C:cn(I,O.args);return{args:O.args,inputSource:I,inputEnvelope:V,projectRoot:n,format:o,watch:s||O.watch,commandLevelWatch:O.metadata,serverUrl:u,platformTarget:g,strictReadOnly:y,privateExecutionBeta:w,...l===void 0?{}:{privateExecutionModel:l}}}function Ca(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function wa(e,t,r=process.stdout,a=process.stderr){if(t.format==="json"){const o=un(e.instructions,e.metadata),s=Ca(o.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:s,publicSafe:!0})+`
205
+ `.trim();function Bc(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function ke(e,t,r,i){return new un("INVOCATION_MALFORMED_INPUT",t,e,r,i)}function Pt(e){return ke("missing-input-value",`${e} requires a value. ${wi}`)}function Uc(e){try{if(!Oi(e).isFile())throw ke("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return He(e)}catch(t){throw t instanceof un?t:ke("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function $c(){try{if(process.stdin.isTTY)throw ke("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return He(0)}catch(e){throw e instanceof un?e:ke("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Hc(e,t={}){let r,i=!1,a,n,o="plain",s=!1,l,f,y=!1,w=!1,u;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const S=e[++T];if(S===void 0)throw Pt("--args");if(r!==void 0)throw ke("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");r=S;break}case"--stdin":if(i)throw ke("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");i=!0;break;case"--args-file":{const S=e[++T];if(S===void 0)throw Pt("--args-file");if(a!==void 0)throw ke("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=S;break}case"--project-root":{const S=e[++T];if(S===void 0)throw Pt("--project-root");n=S;break}case"--format":{const S=e[++T];if(S===void 0)throw Pt("--format");if(S!=="json"&&S!=="plain")throw ke("unexpected-cli-token","--format accepts only json or plain.");o=S;break}case"--watch":s=!0;break;case"--server-url":{const S=e[++T];if(S===void 0)throw Pt("--server-url");l=S;break}case"--platform-target":{const S=e[++T];if(S===void 0)throw Pt("--platform-target");f=S;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":w=!0;break;case"--private-execution-model":{const S=e[++T];if(S===void 0)throw Pt("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(S))throw ke("unexpected-cli-token","Invalid or duplicate private execution model.");u=S;break}default:if(r!==void 0&&P&&(!P.startsWith("-")||P==="-")){r+=` ${P}`;break}throw ke("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(u!==void 0&&(!w||y))throw ke("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const v=[r!==void 0?"args":void 0,i?"stdin":void 0,a!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(v.length===0)throw ke("missing-input-value",wi);if(v.length>1)throw ke("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const I=v[0],p=I==="args"?r:I==="stdin"?(t.readStdin??$c)():(t.readArgsFile??Uc)(a);let C;try{C=cn(I,p)}catch(T){throw T instanceof wa?ke("invalid-utf8",T.message,I):T}const O=I==="args"?Sc(C.rawArgs):Pe(C.rawArgs),V=O.args===C.rawArgs?C:cn(I,O.args);return{args:O.args,inputSource:I,inputEnvelope:V,projectRoot:n,format:o,watch:s||O.watch,commandLevelWatch:O.metadata,serverUrl:l,platformTarget:f,strictReadOnly:y,privateExecutionBeta:w,...u===void 0?{}:{privateExecutionModel:u}}}function _i(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Ri(e,t,r=process.stdout,i=process.stderr){if(t.format==="json"){const o=ln(e.instructions,e.metadata),s=_i(o.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:s,publicSafe:!0})+`
206
206
  `);return}r.write(JSON.stringify({instructions:o.instructions,metadata:s})+`
207
- `);return}const i=un(e.instructions,e.metadata),n=Ca(i.metadata,t.commandLevelWatch);r.write(i.instructions+`
208
- `),n&&a.write(JSON.stringify(n)+`
209
- `)}async function Hs(e=process.stdout,t=process.stderr){const r=i=>new Promise(n=>{let o=!1;const s=y=>{o||(o=!0,clearTimeout(g),setImmediate(()=>i.removeListener("error",u)),n(y))},u=()=>s(!1),g=setTimeout(()=>s(!1),1e4);i.once("error",u);try{i.write("",y=>s(!y))}catch{s(!1)}});return(await Promise.all([r(e),r(t)])).every(Boolean)}function Uc(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Fs(e){if(Dc(e))return process.stdout.write(`${Lc}
210
- `),0;let t;try{t=Vc(e)}catch(a){if(a instanceof ln)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})+`
211
- `),1;throw a}if(ri(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."})+`
212
- `),1):(await ai({args:t.args,projectRoot:jn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await Oc({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&&r.errorCode==="YOLOOP_RELEASE_BLOCKED"&&r.instructions&&r.metadata)return wa(r,t),r.exitCode;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:Je(r.error??"",Tt),...typeof i?.reason=="string"?{reason:Je(i.reason,80)}:{},...typeof i?.source=="string"?{source:Je(i.source,20)}:{},...Number.isSafeInteger(i?.byteLength)?{byte_length:i.byteLength}:{},...typeof i?.remediation=="string"?{remediation:Je(i.remediation,Tt)}:{}})+`
213
- `),r.exitCode}if(wa(r,t),t.watch){const a=new AbortController,i=Uc(a);try{const n=bc(r.metadata,t.args);n.disabled?ac(n.reasonCodes??[Se.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await ic({projectRoot:jn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:a.signal})}finally{i()}}return 0}export{Lc as INVOKE_HELP_TEXT,Dr as INVOKE_PAYLOAD_LIMIT_BYTES,Dn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,ln as InvokeCliInputError,Bn as InvokePayloadTooLargeError,$n as InvokeStructuralContextTooLargeError,it as StateSnapshotIntegrityError,Gs as __resetSchemaDriftWarnedForTests,Pc as acknowledgeMaterializedPendingEpicClaims,ro as admitClientInvocation,Hn as assertEpicAwareStateShapeBeforeRepair,To as boundedP222PremergeCheckpointPositions,Un as buildInvokeCompatibilityOffer,jo as buildSignedInvokeAttempt,Xi as clearPendingEpicIdempotencyKey,Po as collectInvokeP205Authorities,mn as collectStateSnapshot,Ut as computeInvokeRequestBodySizeBytes,Ws as createFullStateSnapshotScope,Jn as createInvokePayloadTelemetry,Zi as deriveYoloLogicalIdempotencyKey,ho as detectStateSchemaDrift,Nc as extractPreFlightTrigger,Hs as flushInvokeCliOutput,Qi as getOrCreatePendingEpicIdempotencyKey,sa as guardInvokeRequestBodySize,Oc as invoke,Fs as invokeCliHandler,Xr as isEpicAwareCommandId,qo as maybeEmitInvokePayloadSizeWarning,Yo as maybeRunInvokeRunnerAutoBootstrap,Vc as parseInvokeCliOptions,oa as postMaterializationJson,to as projectRegistryDriftInvokeFailure,no as projectReleaseBlockedInvokeResult,Br as recordPendingEpicReservation,mc as resolveInvokeCommandLevelWatch,jn as resolveInvokeProjectRoot,Lo as resolveInvokeTransportErrorCode,bc as resolveInvokeWatchTarget,un as sanitizeInvokeCliOutput,Sa as sendEpicClaimAcknowledgement,Ea as sendInvokeRequest,Tc as sendPrivateExecutionCancelRequest,xc as sendPrivateExecutionConsumeRequest,so as shouldCollectProjectEvidenceForInvoke,ic as watchContinuityProcessingSummaries,wa as writeInvokeCliSuccessOutput};
207
+ `);return}const a=ln(e.instructions,e.metadata),n=_i(a.metadata,t.commandLevelWatch);r.write(a.instructions+`
208
+ `),n&&i.write(JSON.stringify(n)+`
209
+ `)}async function zs(e=process.stdout,t=process.stderr){const r=a=>new Promise(n=>{let o=!1;const s=y=>{o||(o=!0,clearTimeout(f),setImmediate(()=>a.removeListener("error",l)),n(y))},l=()=>s(!1),f=setTimeout(()=>s(!1),1e4);a.once("error",l);try{a.write("",y=>s(!y))}catch{s(!1)}});return(await Promise.all([r(e),r(t)])).every(Boolean)}function Gc(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Ks(e){if(Bc(e))return process.stdout.write(`${Vc}
210
+ `),0;let t;try{t=Hc(e)}catch(i){if(i instanceof un)return process.stderr.write(JSON.stringify({error_code:i.code,reason:i.reason,source:i.source,byte_length:i.byteLength,message:i.message,remediation:i.message})+`
211
+ `),1;throw i}if(aa(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."})+`
212
+ `),1):(await oa({args:t.args,projectRoot:jn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await Mc({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&&r.errorCode==="YOLOOP_RELEASE_BLOCKED"&&r.instructions&&r.metadata)return Ri(r,t),r.exitCode;if(!r.success){const i=r.metadata?.invocationInput,a=i&&typeof i=="object"&&!Array.isArray(i)?i:void 0;return process.stderr.write(JSON.stringify({error_code:r.errorCode??(r.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Je(r.error??"",Tt),...typeof a?.reason=="string"?{reason:Je(a.reason,80)}:{},...typeof a?.source=="string"?{source:Je(a.source,20)}:{},...Number.isSafeInteger(a?.byteLength)?{byte_length:a.byteLength}:{},...typeof a?.remediation=="string"?{remediation:Je(a.remediation,Tt)}:{}})+`
213
+ `),r.exitCode}if(Ri(r,t),t.watch){const i=new AbortController,a=Gc(i);try{const n=kc(r.metadata,t.args);n.disabled?sc(n.reasonCodes??[Ce.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await dc({projectRoot:jn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:i.signal})}finally{a()}}return 0}export{Vc as INVOKE_HELP_TEXT,Mr as INVOKE_PAYLOAD_LIMIT_BYTES,Dn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,un as InvokeCliInputError,Un as InvokePayloadTooLargeError,$n as InvokeStructuralContextTooLargeError,ot as StateSnapshotIntegrityError,Ys as __resetSchemaDriftWarnedForTests,Lc as acknowledgeMaterializedPendingEpicClaims,co as admitClientInvocation,Wn as assertEpicAwareStateShapeBeforeRepair,No as boundedP222PremergeCheckpointPositions,Bn as buildInvokeCompatibilityOffer,$o as buildSignedInvokeAttempt,no as clearPendingEpicIdempotencyKey,Lo as collectInvokeP205Authorities,mn as collectStateSnapshot,Bt as computeInvokeRequestBodySizeBytes,Js as createFullStateSnapshotScope,Jn as createInvokePayloadTelemetry,ro as deriveYoloLogicalIdempotencyKey,yo as detectStateSchemaDrift,jc as extractPreFlightTrigger,zs as flushInvokeCliOutput,to as getOrCreatePendingEpicIdempotencyKey,pi as guardInvokeRequestBodySize,Mc as invoke,Ks as invokeCliHandler,ei as isEpicAwareCommandId,Ko as maybeEmitInvokePayloadSizeWarning,Qo as maybeRunInvokeRunnerAutoBootstrap,Hc as parseInvokeCliOptions,si as postMaterializationJson,ao as projectRegistryDriftInvokeFailure,oo as projectReleaseBlockedInvokeResult,$r as recordPendingEpicReservation,Sc as resolveInvokeCommandLevelWatch,jn as resolveInvokeProjectRoot,Vo as resolveInvokeTransportErrorCode,kc as resolveInvokeWatchTarget,ln as sanitizeInvokeCliOutput,Ci as sendEpicClaimAcknowledgement,vi as sendInvokeRequest,Nc as sendPrivateExecutionCancelRequest,Oc as sendPrivateExecutionConsumeRequest,ho as shouldCollectProjectEvidenceForInvoke,dc as watchContinuityProcessingSummaries,Ri as writeInvokeCliSuccessOutput};