@ornexus/neocortex 4.61.6 → 4.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +28 -5
  5. package/package.json +6 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/agent/update-description.d.ts +8 -1
  9. package/packages/client/dist/agent/update-description.js +2 -1
  10. package/packages/client/dist/commands/invoke.d.ts +24 -0
  11. package/packages/client/dist/commands/invoke.js +73 -73
  12. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  13. package/packages/client/dist/commands/refresh-memory.js +5 -3
  14. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  15. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +110 -10
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  18. package/packages/client/dist/git/git-lifecycle-store.d.ts +96 -2
  19. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  20. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  21. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  22. package/packages/client/dist/git/release-gate-env.d.ts +23 -0
  23. package/packages/client/dist/git/release-gate-env.js +1 -0
  24. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  25. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  26. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  27. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  28. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  29. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  30. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  31. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  32. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  33. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  34. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  35. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  36. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  37. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  38. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  39. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  40. package/packages/client/dist/runner/headless/child-env.js +1 -0
  41. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  42. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +31 -0
  43. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  44. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  45. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  46. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  47. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  48. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  49. package/packages/client/dist/runner/headless/types.js +2 -2
  50. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  51. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  52. package/packages/client/dist/state/state-json-repair.js +4 -3
  53. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  54. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  55. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  56. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  57. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  58. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  59. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  60. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  61. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  62. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  63. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  64. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  65. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  66. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  67. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  68. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +62 -1
  69. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  71. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  72. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  73. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  74. package/packages/shared/dist/compatibility/index.js +6 -0
  75. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  76. package/packages/shared/dist/project-manifest-projection.js +202 -0
  77. package/packages/shared/dist/project-validation-commands.js +14 -6
  78. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  79. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  80. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  81. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  82. package/packages/shared/dist/yoloop/epic-terminal-git.js +98 -6
  83. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  84. package/targets-stubs/antigravity/gemini.md +1 -1
  85. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  86. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  87. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  88. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  89. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  90. package/targets-stubs/claude-code/neocortex.md +5 -5
  91. package/targets-stubs/codex/AGENTS.md +1 -1
  92. package/targets-stubs/codex/install-codex.sh +12 -4
  93. package/targets-stubs/cursor/agent.md +2 -2
  94. package/targets-stubs/gemini-cli/agent.md +2 -2
  95. package/targets-stubs/lib/managed-config-merge.js +459 -5
  96. package/targets-stubs/lib/managed-profile.sh +54 -7
  97. package/targets-stubs/opencode/neocortex-root.md +1 -1
  98. package/targets-stubs/vscode/install-vscode.sh +21 -0
  99. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,59 +1,59 @@
1
- import{classifyNonUiArchitectureTransition as Yi,architectureMemoryPredecessorCount as mr}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as yr}from"./shared-architecture-non-ui.js";import{createHash as Pe,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Ir,loadPactPrivateAnswers as Fi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Gt,deriveArchitectureTerminalMemoryReceipt as On}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as qi}from"./architecture-root-binding.js";import{derivePactWriteSet as zi}from"../private-execution/pact-write-set.js";import{execFileSync as We}from"node:child_process";import{existsSync as Mt,readFileSync as Ge,renameSync as Er,unlinkSync as Nn,writeFileSync as pn,mkdirSync as Ft,statSync as Ji,openSync as qt,closeSync as zt,fsyncSync as ln,realpathSync as Ki,lstatSync as jt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as Q,isAbsolute as Qi,resolve as Ln}from"node:path";import{homedir as Jt}from"node:os";import{probeYoloopHostCapacity as Xi}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as Zi,isPrivatePlanningRootPublicEnvelope as ea,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ta}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Sr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as vr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Cr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as na}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as ra}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as ia,buildCrossEpicContinuationPayloadHash as aa,classifyCrossEpicContinuationReconciliation as oa,epicOperationalHash as It,readEpicOperationalState as _r}from"../git/epic-operational-state.js";import{LicenseClient as ca}from"../license/license-client.js";import{EncryptedCache as Dn}from"../cache/encrypted-cache.js";import{NoOpCache as Rr}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as sa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as at,COMMAND_REGISTRY_VERSION as ot,GENERATED_CLIENT_COMMANDS as da}from"../generated/command-registry.generated.js";import{loadSecureConfig as Mn}from"../config/secure-config.js";import{neocortexProfileDirectory as pa}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as la}from"../constants.js";import{detectFirstRunLocale as ua,renderFirstRunMessage as ha}from"../i18n/first-run.js";import{humanizeError as wr,formatHumanizedError as Ar,detectErrorLocale as br}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as ga,projectStateSnapshotForInvoke as xr,projectStateSnapshotResultV2ForInvoke as fa}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Tr,maybeRepairStateJsonBeforeInvoke as ma,StateRepairHardStopError as ya}from"../state/state-json-repair.js";import{StructuralDagError as Pr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Ia,StateMigrationApplyError as Ea}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Sa,classifyRunnerBootstrapPolicyFromArgs as va}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ca,ensureRunnerSchedulerBootstrap as _a,observeRunnerOperationalStatus as Ra}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as kr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Or,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Lr,openContinuityClientStateStore as wa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Aa,runLocalJobsConsoleCommand as ba}from"../runner/local-console.js";import{detectNativeHostAttestation as xa,detectPlatform as Ta}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Pa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ka}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Oa}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Dr,executeInvokeQueryTransport as jn,executeSecondaryNetworkMutation as Na}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as La,STRICT_READ_ONLY_CLIENT_PROJECTION as Mr,STRICT_READ_ONLY_SERVER_PROJECTION as Da,StrictReadOnlyError as Vt,canonicalizeInvokeEffects as Ma,createInvokeEffectContext as ja,verifyStrictReadOnlyReceipt as Va}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ba,assertInvokeInputEnvelopeV2 as Ua,assertProjectIdentityMigrationReceiptV1 as $a,buildProjectIdentityPublicDiagnostic as Bt,createInvocationAdmissionReceipt as Ha,projectInvokeInputEvidenceV1 as Vn,recoverExplicitInvocation as Wa,verifyStrictDiagnoseReceiptV1 as Ga}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Kt,InvokeInputDecodeError as Ya}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as Ut,createCompatibilityOffer as Fa,createLegacyCompatibilityResult as qa,isCompatibilityResultV1 as za}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ja,finalizeProjectIdentityMigration as Ka,prepareProjectIdentityMigration as Qa,ProjectIdentityMigrationError as Bn,readProjectIdentityMigrationPhase as Xa}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Za}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as eo}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as to,epicHeadReconciliationPathsDigest as jr,epicHeadReconciliationRangeDigest as no}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Vr,classifyGitLifecycleStoryCheckpointProjectionSync as ro,ensureRuntimeEpic as io,ensureGitLifecycleRuntimeInitialized as ao,executeP205TransientAuthorities as oo,persistGitLifecycleGraphAuthority as co,P205_COMPLETE_COMMAND as Qt,gitLifecycleStoryWriteSet as Br,appendStoryWorktreeEvidence as so,isStoryWorktreeEvidenceContainer as po,mutateGitLifecycleRuntime as Ur,projectP205TransientExecutionEvidence as lo,readGitLifecycleRuntimeSync as gn,verifyLegacyCheckpointMigrationCandidateSync as uo}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as ho}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as go}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as fo}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as $r,extractTargetedYoloStoryId as mo,refreshPrecollectedYoloSpecEnvelope as Hr}from"../yolo/spec-envelope-collector.js";const fn=pa(),Un=Q(fn,"cache"),Wr=Q(Un,"menu-cache.json"),Gr=1440*60*1e3,Yr=3e4,Fr=256*1024,qr=Fr,zr=.8,Et="[REDACTED]",yo=1e5,kt=2e3,Io=200,Eo=200,So=12,vo=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Co=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,_o=/(?: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,$n=Math.floor(Fr*zr),Jr=Q(fn,".first-run-shown"),Ro="pending-epic-claims.json",Kr=64;function Qr(e){return Q(e,".neocortex",Ro)}function $t(e){const t=Qr(e);if(!Mt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Ge(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Kr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(r.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 i}function Hn(e,t){const i=Qr(e);Ft(Q(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${dn()}.tmp`;pn(r,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),Er(r,i)}function wo(e,t){return Pe("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Ao(e,t,i="create-epic"){const r=wo(t,i),a=$t(e),n=a.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(a.operations).length>=Kr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=dn(),d={...a.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Hn(e,{schemaVersion:1,operations:d}),{key:o,fingerprint:r}}function bo(e,t){const i=$t(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],Hn(e,{schemaVersion:1,operations:r})}function xo(e,t,i,r){const a=r.scope?.targetStoryId??r.current_session?.active_story_id??null,n=r.scope?.targetEpicId??r.current_session?.active_epic_id??null,o=a?r.stories[a]:void 0,d=Array.isArray(o?.steps_completed)?o.steps_completed.filter(y=>typeof y=="string"):[],s=i??Pe("sha256").update(`nx-yolo-project-path-v1\0${Ln(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,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:d});return`yolo-${Pe("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function Xr(e,t,i,r,a){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(r)||a!==void 0&&a!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=$t(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==i||o.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Hn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:i,epicId:r,...a?{planningProtocol:a}:{}}}})}function To(){try{if(Mt(Jr))return;const e=ua(),t=ha(e);process.stderr.write(t);try{Ft(fn,{recursive:!0}),pn(Jr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Wn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Po(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 ko(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=Oa(t.releaseBlocked);return!r||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:r},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function Zr(e){return Ba(e,{registryVersion:ot,registryChecksum:at})}function Oo(e){return Wa(e,{registryVersion:ot,registryChecksum:at})}const No=new Set(["completed","aborted","cancelled"]),Lo=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=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"}),ke=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"}),ei=240,Do=/(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 Mo(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Et).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Et).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Et).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Et).replace(Co,Et).replace(_o,Et)}function ze(e,t){const i=Mo(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Gn(e,t=0,i=new WeakSet){if(t>So)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return ze(e,kt);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(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,Io).map(a=>Gn(a,t+1,i));const r={};for(const[a,n]of Object.entries(e).slice(0,Eo)){if(vo.test(a)){r[a]=Et;continue}const o=Gn(n,t+1,i);o!==void 0&&(r[a]=o)}return r}finally{i.delete(e)}}}function mn(e,t){return{instructions:ze(e??"",yo),metadata:t?Gn(t):void 0}}function jo(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,i=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,r=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,a=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,n=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,o=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!r||!a||!n||o===void 0||t.publicSafe!==!0))return{reason:i,base_source:r,repair:a,recollection_count:o,fallback_action:n,public_safe:!0}}class yn extends Error{reason;source;byteLength;code;constructor(t,i,r,a,n){super(i),this.reason=r,this.source=a,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function Vo(e){const t=un(e);return(t==="arch-plan"||t==="ui-ux-review")&&Bo(e,"--project-evidence")}function Bo(e,t){let i=null,r=-1,a=!1,n=!1;for(let o=0;o<=e.length;o+=1){const d=e[o];if(o===e.length||!i&&/\s/.test(d??"")){if(r>=0&&!a&&e.slice(r,o)===t)return!0;r=-1,a=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(d==="\\"){n=!0;continue}(d==='"'||d==="'")&&(a=!0,i=i===d?null:i??d)}return!1}const Uo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function $o(e,t){if(e.targetId!=="codex")return null;const i=t.CODEX_VERSION?.trim();if(i&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(i))return i;try{return We("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Uo)?.[1]??null}catch{return null}}function Yn(){return Fa({clientVersion:Pt,registryVersion:ot,registryChecksum:at})}class Fn 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 qn 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 zn=!1;function Ho(e){const t=[];if(!e||typeof e!="object")return t;const i=e,r=i.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(i.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),i.epics&&typeof i.epics=="object"&&!Array.isArray(i.epics))for(const[n,o]of Object.entries(i.epics)){const d=o;if(d&&d.stories!==void 0&&!Array.isArray(d.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const a=i.epics&&typeof i.epics=="object"&&Object.keys(i.epics).length>0||i.stories&&typeof i.stories=="object"&&!Array.isArray(i.stories)&&Object.keys(i.stories).length>0||Array.isArray(i.stories)||r&&r.current!==void 0;return i.schema_version===void 0?a&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):i.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(i.schema_version)} (expected: 1)`}),t}function Wo(e){if(!(zn||e.length===0)){zn=!0;try{const t=e.map(i=>` - ${i.message}`).join(`
1
+ import{classifyNonUiArchitectureTransition as qi,architectureMemoryPredecessorCount as Ir}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Er}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Sr,loadPactPrivateAnswers as zi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Ln}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Ji}from"./architecture-root-binding.js";import{derivePactWriteSet as Ki}from"../private-execution/pact-write-set.js";import{execFileSync as Ge}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as vr,unlinkSync as Dn,writeFileSync as pn,mkdirSync as qt,statSync as Qi,openSync as zt,closeSync as Jt,fsyncSync as ln,realpathSync as Xi,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as z,isAbsolute as Zi,resolve as Mn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as ea}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as ta,isPrivatePlanningRootPublicEnvelope as na,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ra}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Cr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as _r}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Rr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as ia}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as aa}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as oa,buildCrossEpicContinuationPayloadHash as ca,classifyCrossEpicContinuationReconciliation as sa,epicOperationalHash as vt,readEpicOperationalState as wr}from"../git/epic-operational-state.js";import{LicenseClient as da}from"../license/license-client.js";import{EncryptedCache as jn}from"../cache/encrypted-cache.js";import{NoOpCache as Ar}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as pa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as la}from"../generated/command-registry.generated.js";import{loadSecureConfig as Vn}from"../config/secure-config.js";import{neocortexProfileDirectory as ua}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as ha}from"../constants.js";import{detectFirstRunLocale as ga,renderFirstRunMessage as fa}from"../i18n/first-run.js";import{humanizeError as br,formatHumanizedError as xr,detectErrorLocale as Tr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as ma,projectStateSnapshotForInvoke as Pr,projectStateSnapshotResultV2ForInvoke as ya}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as kr,maybeRepairStateJsonBeforeInvoke as Ia,readStoryWorktreeRepairOverlay as Ea,StateRepairHardStopError as Sa}from"../state/state-json-repair.js";import{StructuralDagError as Or}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as va,StateMigrationApplyError as Ca}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as _a,classifyRunnerBootstrapPolicyFromArgs as Ra}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as wa,ensureRunnerSchedulerBootstrap as Aa,observeRunnerOperationalStatus as ba}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Mr,openContinuityClientStateStore as xa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Ta,runLocalJobsConsoleCommand as Pa}from"../runner/local-console.js";import{detectNativeHostAttestation as ka,detectPlatform as Oa}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Na}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as La}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Da}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as jr,executeInvokeQueryTransport as Bn,executeSecondaryNetworkMutation as Ma}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as ja,STRICT_READ_ONLY_CLIENT_PROJECTION as Vr,STRICT_READ_ONLY_SERVER_PROJECTION as Va,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as Ba,createInvokeEffectContext as Ua,verifyStrictReadOnlyReceipt as $a}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ha,assertInvokeInputEnvelopeV2 as Wa,assertProjectIdentityMigrationReceiptV1 as Ga,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as Fa,projectInvokeInputEvidenceV1 as Un,recoverExplicitInvocation as Ya,verifyStrictDiagnoseReceiptV1 as qa}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as za}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as Ja,createLegacyCompatibilityResult as Ka,isCompatibilityResultV1 as Qa}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Xa,finalizeProjectIdentityMigration as Za,prepareProjectIdentityMigration as eo,ProjectIdentityMigrationError as $n,readProjectIdentityMigrationPhase as to}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as no}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as ro}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as io,epicHeadReconciliationPathsDigest as gn,epicHeadReconciliationRangeDigest as ao}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Br,classifyGitLifecycleStoryCheckpointProjectionSync as oo,ensureRuntimeEpic as co,ensureGitLifecycleRuntimeInitialized as so,executeP205TransientAuthorities as po,isP226GateReasonCode as lo,persistGitLifecycleGraphAuthority as uo,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as Ur,gitLifecycleStoryClaimCandidates as ho,gitLifecycleWriteSetCovers as go,appendStoryWorktreeEvidence as fo,isStoryWorktreeEvidenceContainer as mo,mutateGitLifecycleRuntime as $r,projectP205TransientExecutionEvidence as yo,readGitLifecycleRuntimeSync as fn,verifyLegacyCheckpointMigrationCandidateSync as Io}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Eo}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as So}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as vo}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as Co}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Hr,extractTargetedYoloStoryId as _o,refreshPrecollectedYoloSpecEnvelope as Wr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as Ro}from"../errors/frontmatter-diagnostics.js";function Gr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||Ro.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const mn=ua(),Hn=z(mn,"cache"),Fr=z(Hn,"menu-cache.json"),Yr=1440*60*1e3,qr=3e4,zr=256*1024,Jr=zr,Kr=.8,Ct="[REDACTED]",wo=1e5,kt=2e3,Ao=200,bo=200,xo=12,To=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Po=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,ko=/(?: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,Wn=Math.floor(zr*Kr),Qr=z(mn,".first-run-shown"),Oo="pending-epic-claims.json",Xr=64;function Zr(e){return z(e,".neocortex",Oo)}function Ht(e){const t=Zr(e);if(!jt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Fe(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=i;if(n.schemaVersion!==1||!n.operations||typeof n.operations!="object"||Array.isArray(n.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(n.operations).length>Xr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,r]of Object.entries(n.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=r;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 i}function Gn(e,t){const i=Zr(e);qt(z(e,".neocortex"),{recursive:!0,mode:448});const n=`${i}.${process.pid}.${dn()}.tmp`;pn(n,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),vr(n,i)}function No(e,t){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Lo(e,t,i="create-epic"){const n=No(t,i),a=Ht(e),r=a.operations[n];if(r)return{key:r.idempotencyKey,fingerprint:n};if(Object.keys(a.operations).length>=Xr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=dn(),d={...a.operations,[n]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Gn(e,{schemaVersion:1,operations:d}),{key:o,fingerprint:n}}function Do(e,t){const i=Ht(e);if(!i.operations[t])return;const n={...i.operations};delete n[t],Gn(e,{schemaVersion:1,operations:n})}function Mo(e,t,i,n){const a=n.scope?.targetStoryId??n.current_session?.active_story_id??null,r=n.scope?.targetEpicId??n.current_session?.active_epic_id??null,o=a?n.stories[a]:void 0,d=Array.isArray(o?.steps_completed)?o.steps_completed.filter(y=>typeof y=="string"):[],s=i??Ne("sha256").update(`nx-yolo-project-path-v1\0${Mn(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,args:t,storyId:a,epicId:r,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:d});return`yolo-${Ne("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function ei(e,t,i,n,a){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(n)||a!==void 0&&a!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=Ht(e),o=r.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==i||o.epicId!==n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Gn(e,{schemaVersion:1,operations:{...r.operations,[t]:{...o,claimId:i,epicId:n,...a?{planningProtocol:a}:{}}}})}function jo(){try{if(jt(Qr))return;const e=ga(),t=fa(e);process.stderr.write(t);try{qt(mn,{recursive:!0}),pn(Qr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Fn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Vo(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 Bo(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const n=Da(t.releaseBlocked);return!n||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:n},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function ti(e){return Ha(e,{registryVersion:dt,registryChecksum:st})}function Uo(e){return Ya(e,{registryVersion:dt,registryChecksum:st})}const $o=new Set(["completed","aborted","cancelled"]),Ho=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=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"}),Le=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"}),G=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"}),ni=240,Wo=/(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 Go(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Ct).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Ct).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Ct).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ct).replace(Po,Ct).replace(ko,Ct)}function Je(e,t){const i=Go(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Yn(e,t=0,i=new WeakSet){if(t>xo)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Je(e,kt);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(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,Ao).map(a=>Yn(a,t+1,i));const n={};for(const[a,r]of Object.entries(e).slice(0,bo)){if(To.test(a)){n[a]=Ct;continue}const o=Yn(r,t+1,i);o!==void 0&&(n[a]=o)}return n}finally{i.delete(e)}}}function yn(e,t){return{instructions:Je(e??"",wo),metadata:t?Yn(t):void 0}}function Fo(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,i=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,n=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,a=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,r=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,o=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!n||!a||!r||o===void 0||t.publicSafe!==!0))return{reason:i,base_source:n,repair:a,recollection_count:o,fallback_action:r,public_safe:!0}}class In extends Error{reason;source;byteLength;code;constructor(t,i,n,a,r){super(i),this.reason=n,this.source=a,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function Yo(e){const t=un(e);return(t==="arch-plan"||t==="ui-ux-review")&&qo(e,"--project-evidence")}function qo(e,t){let i=null,n=-1,a=!1,r=!1;for(let o=0;o<=e.length;o+=1){const d=e[o];if(o===e.length||!i&&/\s/.test(d??"")){if(n>=0&&!a&&e.slice(n,o)===t)return!0;n=-1,a=!1,r=!1;continue}if(n<0&&(n=o),r){r=!1;continue}if(d==="\\"){r=!0;continue}(d==='"'||d==="'")&&(a=!0,i=i===d?null:i??d)}return!1}const zo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Jo(e,t){if(e.targetId!=="codex")return null;const i=t.CODEX_VERSION?.trim();if(i&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(i))return i;try{return Ge("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(zo)?.[1]??null}catch{return null}}function qn(){return Ja({clientVersion:Pt,registryVersion:dt,registryChecksum:st})}class zn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Jn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Kn=!1;function Ko(e){const t=[];if(!e||typeof e!="object")return t;const i=e,n=i.planning;if(n&&(n.current!==void 0||Array.isArray(n.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(i.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),i.epics&&typeof i.epics=="object"&&!Array.isArray(i.epics))for(const[r,o]of Object.entries(i.epics)){const d=o;if(d&&d.stories!==void 0&&!Array.isArray(d.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const a=i.epics&&typeof i.epics=="object"&&Object.keys(i.epics).length>0||i.stories&&typeof i.stories=="object"&&!Array.isArray(i.stories)&&Object.keys(i.stories).length>0||Array.isArray(i.stories)||n&&n.current!==void 0;return i.schema_version===void 0?a&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):i.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(i.schema_version)} (expected: 1)`}),t}function Qo(e){if(!(Kn||e.length===0)){Kn=!0;try{const t=e.map(i=>` - ${i.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 kd(){zn=!1}function ti(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 Yo=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"]),Fo=/(?:[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 qo(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(Fo.test(i))return{};const a=(o,d)=>{if(Object.keys(o).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!g(e.intake))return{};if(Object.keys(e.intake).some(o=>!Yo.has(o)))return{};for(const[o,d]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!g(l))return{};if(a(l,s),Object.values(l).some(y=>typeof y!="string"||y.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(o==="rawIntent"?ra:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!g(o))return{};if(a(o,n),Object.values(o).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[o];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ni(e){return e==="create-epic"||e==="discovered"?e:void 0}function Se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function zo(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const a=e[r];if(!Array.isArray(a)||a.length>128||a.some(n=>hn(n)===void 0)){i=!0;continue}t[r]=a.map(n=>hn(n))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const d=r[o];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!g(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(d=>!g(d)||hn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=eo(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function St(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function te(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(),i=te(e);return i===t?i:void 0}function ve(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(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Oe(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 ct(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 In(e){if(!g(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,C)=>Array.isArray(u)&&u.length<=C&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,C)=>{if(!(!g(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||C&&(!i(u.outputHash)||!i(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,...C?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,C)=>{if(!(!g(u)||u.schemaVersion!=="1.1"||u.kind!==C||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:C,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,C)=>{if(!g(u)||u.kind!==C||!i(u.receiptId)||!r(u.evidenceIds,24)||C==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||C==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const h=C==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,I=C==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(C==="architecture-stage-validation"&&(!h||!I)))return{...E,kind:C,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...h&&I?{isolated:h,regression:I}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=yr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!g(e.accounting)||u.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}g(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&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const y=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(y&&(d.completionEvidence=y),S&&(d.validationEvidence=S),g(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&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Gt(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(g(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(C=>{if(!g(C)||!t(C.targetEpicId)||!t(C.stageCommand))return;const E=o(C.completionEvidence,"architecture-stage-completion"),h=o(C.validationEvidence,"architecture-stage-validation");return E&&h?{targetEpicId:C.targetEpicId,stageCommand:C.stageCommand,completionEvidence:E,validationEvidence:h}:void 0});u.every(C=>C!==void 0)&&(d.acceptedStages=u)}if(g(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=r(e.accounting.receiptIds,32);u&&(d.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(d).length<=96e3?d:void 0}function Jo(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=g(t)?t.checkpoint:void 0,r=g(t)?t:void 0,a=g(i)?i:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],d=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&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&g(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,n.completionEvidence)&&v(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&v(o[0],n.acceptedStages[0])&&v(o[1].completionEvidence,n.completionEvidence)&&v(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,n.acceptedStages)&&r?.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&&g(o[0])&&g(o[1])&&g(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&&v(o.slice(0,2),n.acceptedStages)&&v(o[2].completionEvidence,n.completionEvidence)&&v(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",C=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&g(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&v(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,n.completionEvidence)&&v(o[3].validationEvidence,n.validationEvidence)&&v(a.questionIds,E)&&v(r?.questionIds,E)&&r?.nextAction==="ask-user",I=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,n.acceptedStages)&&v(n.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",b=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&v(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&v(o.slice(0,4),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(o[4])&&v(o[4].completionEvidence,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,n.acceptedStages)&&r?.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&&v(o.slice(0,5),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(o[5])&&v(o[5].completionEvidence,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",_=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&&v(o.slice(0,6),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&g(o[6])&&v(o[6].completionEvidence,n.completionEvidence)&&v(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",M=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&&v(o.slice(0,7),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&g(o[7])&&v(o[7].completionEvidence,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",N=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",z=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&&v(o.slice(0,8),n.acceptedStages)&&o.map(B=>g(B)?B.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"&&g(o[8])&&v(o[8].completionEvidence,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,n.acceptedStages)&&r?.nextAction==="blocked",j=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&&v(o.slice(0,9),n.acceptedStages)&&o.map(B=>g(B)?B.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"&&g(o[9])&&v(o[9].completionEvidence,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",ee=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&&v(o.slice(0,10),n.acceptedStages)&&o.map(B=>g(B)?B.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"&&g(o[10])&&v(o[10].completionEvidence,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",W=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",lt=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&&v(o.slice(0,11),n.acceptedStages)&&o.map(B=>g(B)?B.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"&&g(o[11])&&v(o[11].completionEvidence,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Fe=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",he=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&&v(o.slice(0,12),n.acceptedStages)&&o.map(B=>g(B)?B.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"&&g(o[12])&&v(o[12].completionEvidence,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",O=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",H=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&&v(o,n.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",Ct=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&v(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&v(o.slice(0,13),n.acceptedStages)&&g(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,n.completionEvidence)&&v(o[13].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",De=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",se=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&&v(o.slice(0,14),n.acceptedStages)&&g(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,n.completionEvidence)&&v(o[14].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Gt(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",tt=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Gt(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",ut=r?Yi(n,r,Gt(n.terminalMemoryCheckpoint,n)&&v(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(ut||d||s||l||y||S||u||C||h||I||b||L||T||P||_||w||M||N||z||Z||j||V||ee||W||lt||Fe||he||O||H||Ct||De||se||tt)||!g(i.accounting)||i.accounting.charged!==!0||!v(In(i),i))throw new Error("architecture-root-checkpoint-invalid");const X=Q(e.projectRoot,".neocortex"),ye=Q(X,"state.json"),le=Q(X,"state.json.architecture.lock"),Nt=qt(le,"wx",384);let Re;try{const B=jt(ye);if(!B.isFile()||B.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const je=Ge(ye,"utf8");if(Pe("sha256").update(je).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const J=JSON.parse(je),ge=g(J)&&g(J.archPlan)?J.archPlan:{};if(!g(J)||!g(J.epics)||!Object.hasOwn(J.epics,i.targetEpicId)||(e.initialBinding?ge.execution!==void 0||n.graphSource!=="committed-epic-v1":!v(In(ge.execution),n))||g(J.scope)&&J.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(tt||ut==="complete-replay"){const f={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,mr(n))};if(!v(n.terminalMemoryCheckpoint,On(e.projectRoot,f)))throw new Error("architecture-root-state-conflict");return}const Ve=dn(),ne=We("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),_t=Qi(ne)?Ln(ne):Ln(e.projectRoot,ne);if(Ki(_t)!==_t)throw new Error("architecture-root-backup-dir-invalid");const qe=Q(_t,"neocortex-architecture");Ft(qe,{recursive:!0,mode:448});const Ie=jt(qe);if(!Ie.isDirectory()||Ie.isSymbolicLink()||Ie.uid!==process.getuid?.()||(Ie.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ht=Q(qe,`state-backup-${Ve}.json`),G=qt(ht,"wx",384);try{pn(G,je),ln(G)}finally{zt(G)}const tn=qt(qe,"r");try{ln(tn)}finally{zt(tn)}const Rt={...J,archPlan:{...ge,execution:i}};Re=Q(X,`state.json.architecture-tmp-${Ve}`);const k=qt(Re,"wx",384);try{pn(k,`${JSON.stringify(Rt,null,2)}
8
- `),ln(k)}finally{zt(k)}if((se||ut==="complete")&&!v(n.terminalMemoryCheckpoint,On(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Er(Re,ye),Re=void 0;const wt=qt(X,"r");try{ln(wt)}finally{zt(wt)}}finally{if(Re)try{Nn(Re)}catch{}zt(Nt),Nn(le)}}function En(e,t){if(!g(e))return;const i={};for(const r of t){const a=e[r];if(typeof a=="boolean")i[r]=a;else if(typeof a=="number"&&Number.isFinite(a))i[r]=a;else if(typeof a=="string"){const n=te(a);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function Sn(e){return e==="epic"||e==="story"?e:void 0}function ri(e){if(!g(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),i=K(e.sessionId),r=K(e.idempotencyKey),a=Oe(e.acquiredAt),n=Oe(e.expiresAt);if(!(!t||!i||!r||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:a,expiresAt:n}}function ii(e){if(!g(e)||e.schemaVersion!==1)return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=R(e.baseSha),n=R(e.headSha),o=K(e.idempotencyKey),d=Oe(e.recordedAt),s=Se(e.commits).map(R).filter(L=>!!L).slice(0,256),l=Se(e.receiptRefs).map(ct).filter(L=>!!L).slice(0,256),y=e.dispatchId===void 0?void 0:K(e.dispatchId),S=e.bundleId===void 0?void 0:K(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),C=e.graphRevision===void 0?void 0:R(e.graphRevision),E=e.claimRevision===void 0?void 0:K(e.claimRevision),h=Ko(e.qaReceipt),I=Qo(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:go(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!a||!n||a===n||!o||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!C||C.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==r||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!I||e.reviewVerdict==="pending"&&I||h.verdict!==e.qaVerdict||I&&I.verdict!==e.reviewVerdict||!ci(h,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I&&(!ci(I,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I.qaReceiptRef!==h?.receiptRef||I.receiptRef===h?.receiptRef)||!l.includes(String(h.receiptRef))||I&&(!l.includes(String(I.receiptRef))||Date.parse(String(I.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,idempotencyKey:o,...y?{dispatchId:y}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...C?{graphRevision:C}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...I?{reviewReceipt:I}:{},recordedAt:d,commits:s,receiptRefs:l}}function Ko(e){if(!g(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),i=K(e.epicId),r=R(e.baseSha),a=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=Oe(e.checkedAt),l=ct(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,C=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?Se(e.gateIds).map(K).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!y||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!C||C.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:S,manifestDigest:u,gateIds:E,resultDigest:C}:{},baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ai(e){if(!g(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),i=K(e.epicId),r=ve(e.branch),a=R(e.baseSha),n=R(e.headSha),o=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=R(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=R(e.manifestDigest),C=Se(e.gateIds).map(K).filter(P=>!!P).slice(0,64),E=R(e.resultDigest),h=R(e.graphRevision),I=R(e.executionEvidenceDigest),b=R(e.sourceEvidenceDigest),L=Oe(e.verifiedAt),T=Se(e.reasonCodes).map(K).filter(P=>!!P).slice(0,16);if(!(!t||!i||!r||!a||a.length<40||!n||n.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||!y||y.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||C.length!==e.gateIds.length||!E||E.length!==64||!h||h.length!==64||!I||I.length!==64||!b||b.length!==64||!L||T.length===0||e.verdict==="verified"&&(C.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:y,command:S,manifestDigest:u,gateIds:C,resultDigest:E,graphRevision:h,executionEvidenceDigest:I,sourceEvidenceDigest:b,verifiedAt:L,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function oi(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!g(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 i=K(e.storyId),r=K(e.epicId),a=ve(e.branch),n=R(e.baseSha),o=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),y=Oe(e.verifiedAt),S=Se(e.reasonCodes).map(K).filter(u=>!!u);if(!(!i||!r||!a||!n||n.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!y||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:a,baseSha:n,headSha:o,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:y,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function Qo(e){if(!g(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),i=K(e.epicId),r=R(e.baseSha),a=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=ct(e.qaReceiptRef),l=Oe(e.reviewedAt),y=ct(e.receiptRef);if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:y}}function ci(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function si(e){if(!g(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=ve(e.originBranch),i=R(e.originHeadSha),r=ve(e.executionBranch),a=Oe(e.capturedAt);if(!(!t||!i||i.length<40||!r||!a||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}}function di(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(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",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?R(e.manifestDigest):void 0,l=o?R(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!d&&!o||o&&(!s||s.length!==64||!l||l.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:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:a,gateIds:n}}function pi(e){if(!g(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:K(e.epicId),executionBranch:ve(e.executionBranch),originBranch:ve(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:Se(e.acceptedCheckpointIds),acceptedCheckpointHeads:Se(e.acceptedCheckpointHeads),reconciliationCommitShas:Se(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:Se(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:Se(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:ct(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:Oe(e.producedAt),revalidatedAt:Oe(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!==no(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==jr(t.changedPaths)||t.allowedWriteSetDigest!==jr(t.allowedWriteSet))return;const i=t,r=R(e.inputDigest);if(!(!r||r.length!==64||r!==to(i)))return{...i,inputDigest:r}}function Jn(e){if(!g(e)||e.schemaVersion!==1)return;const t=En(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=Se(e.receiptRefs).map(ct).filter(a=>!!a).slice(0,256),r=Se(e.revertCommits).map(te).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function Xo(e){if(!(!g(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 li(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=K(e.epicId),i=ve(e.executionBranch),r=ve(e.originBranch),a=R(e.baseSha),n=R(e.executionHeadSha),o=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=K(e.idempotencyKey),l=Oe(e.attemptStartedAt),y=e.completedAt===void 0?void 0:Oe(e.completedAt),S=Se(e.localGateReceiptRefs).map(ct).filter(h=>!!h).slice(0,256),u=Se(e.reasonCodes).map(K).filter(h=>!!h).slice(0,64),C=ec(e.candidateQa),E=Zo(e.providerGuard);if(!(!t||!i||!r||!a||!n||!s||!l||S.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&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...d?{pushedSha:d}:{},strategy:e.strategy,...St(e.prNumber)?{prNumber:St(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...C?{candidateQa:C}:{},...E?{providerGuard:E}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function Zo(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=R(e.prHeadSha),n=R(e.originHeadSha),o=Oe(e.checkedAt);if(!(!r||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function ec(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Qt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,R(e[o])])),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!r||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:a,gateIds:n}}function tc(e){if(!g(e))return;const t={...te(e.active_epic_id??e.activeEpicId)?{active_epic_id:te(e.active_epic_id??e.activeEpicId)}:{},...te(e.active_story_id??e.activeStoryId)?{active_story_id:te(e.active_story_id??e.activeStoryId)}:{},...te(e.active_step_id??e.activeStepId)?{active_step_id:te(e.active_step_id??e.activeStepId)}:{},...te(e.session_id??e.sessionId)?{session_id:te(e.session_id??e.sessionId)}:{},...te(e.started_at??e.startedAt)?{started_at:te(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function nc(e){const t=En(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=En(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=En(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}:{},...te(e.physicalMergeStatus)?{physicalMergeStatus:te(e.physicalMergeStatus)}:{},...te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...te(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:te(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...St(e.issue_number??e.issueNumber)?{issue_number:St(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class st extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const rc=new Set(["yolo","yoloop","finalize-epic","audit"]);function ui(e){return typeof e=="string"&&rc.has(e)}function Kn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i))throw new st("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ge(i,"utf8"))}catch{throw new st("git-lifecycle-state-corrupt")}if(!g(r)||!g(r.epics)||!g(r.stories))throw new st("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>g(n)&&(n.branch_mode==="epic"||ve(n.execution_branch)!==void 0));if(a)try{gn(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 st(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function vn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i)){if(t.epicAware&&!t.projectless)throw new st("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,a;try{const E=Ge(i,"utf-8");a=Pe("sha256").update(E).digest("hex");const h=JSON.parse(E),I=g(h.epics)?h.epics:{},b=Object.values(I).some(w=>g(w)&&(w.branch_mode==="epic"||ve(w.execution_branch)!==void 0)),L=gn(e,{required:!!(t.epicAware&&b&&!t.projectless)});r=Vr(h,L);const T=g(r.stories)?r.stories:{},P=g(r.epics)?r.epics:{},_=g(h.stories)?h.stories:{};for(const[w,M]of Object.entries(T)){const N=g(M)?M:void 0;if(!N?.checkpoint)continue;const z=typeof N.epic_id=="string"?N.epic_id:w.split(".")[0],Z=g(P[z])?P[z]:void 0,j=ve(Z?.execution_branch);if(!j)continue;const V=ro(e,N.checkpoint,w,z,j,t.p205Authorities?.[w],Br(w,N,g(N.checkpoint)?N.checkpoint:void 0));if(V.kind==="integration-authorized")N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")N.scheduling_checkpoint_evidence=V.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(V.kind==="rejected"){N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;const ee=g(_[w])?_[w]:void 0;if(delete N.checkpoint,L.stories[w]?.checkpoint!==void 0)for(const W of["status","last_step","steps_completed"])ee&&Object.prototype.hasOwnProperty.call(ee,W)?N[W]=structuredClone(ee[W]):delete N[W];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const h=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new st(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Ho(r);E.length>0&&Wo(E)}catch{}const n=r.config??r.project??{},o=r.stories??{},d={};for(const[E,h]of Object.entries(o)){const I=g(h.review_request)&&h.review_request.kind==="git-pull-request"?Xo(h.review_request):Jn(h.review_request);d[E]={id:h.id??E,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...ni(h.source)?{source:ni(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...Sn(h.branch_mode)?{branch_mode:Sn(h.branch_mode)}:{},...ii(h.checkpoint)?{checkpoint:ii(h.checkpoint)}:{},...ai(h.checkpoint_verification)?{checkpoint_verification:ai(h.checkpoint_verification)}:{},...oi(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:oi(h.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Jn(h.rollback_receipt)?{rollback_receipt:Jn(h.rollback_receipt)}:{},...St(h.workflow_issue)?{workflow_issue:St(h.workflow_issue)}:{},...nc(h),depends_on:ti(h.depends_on),files_to_modify:Se(h.files_to_modify),...zo(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const s=r.epics??{},l={};for(const[E,h]of Object.entries(s)){const I=Go(h.lifecycle_classification),b=qo(h.createEpicPlanning,E),L=b.checkpoint;let T,P,_,w;if(L&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Sr(r,h.createEpicPlanningClaim.claimId,E,!0),T=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(T&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningResearchPhysical))try{vr(r,h.createEpicPlanningClaim.claimId,E),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&L&&h.status==="generated"&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningGenerationPhysical))try{if(na(e,h.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),T=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(_&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const M=Cr(e,h.createEpicPlanningClaim.claimId,E);if(M.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(M))}catch{}l[E]={id:h.id??E,title:h.title,...L?{createEpicPlanning:L}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...T?{createEpicPlanningPhysical:T}:{},...P?{createEpicPlanningResearchPhysical:P}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:ti(h.depends_on),...Sn(h.branch_mode)?{branch_mode:Sn(h.branch_mode)}:{},...ve(h.execution_branch)?{execution_branch:ve(h.execution_branch)}:{},...ve(h.origin_branch)?{origin_branch:ve(h.origin_branch)}:{},...ri(h.branch_lease)?{branch_lease:ri(h.branch_lease)}:{},...si(h.origin_binding)?{origin_binding:si(h.origin_binding)}:{},...di(h.aggregate_qa_receipt)?{aggregate_qa_receipt:di(h.aggregate_qa_receipt)}:{},...pi(h.head_reconciliation_receipt)?{head_reconciliation_receipt:pi(h.head_reconciliation_receipt)}:{},...po(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...St(h.pr_number)?{pr_number:St(h.pr_number)}:{},...te(h.physicalMergeStatus)?{physicalMergeStatus:te(h.physicalMergeStatus)}:{},...R(h.graph_revision)?{graph_revision:R(h.graph_revision)}:{},...li(h.terminal_git_receipt)?{terminal_git_receipt:li(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=tc(r.current_session??r.currentSession),S=g(r.archPlan)?In(r.archPlan.execution):void 0,u=r.epic_id_ledger,C=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:d,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...y?{current_session:y}:{},...S?{archPlan:{execution:S}}:{}}}const Qn=[["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"]],Xn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Zn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",hi="30dccfff07f9c969be11ae1d28e62a09731a0768";function ic(e,t){try{const i=t.indexOf(hi);if(i<1||t[i-1]!==Xn)return new Map;const r=We("git",["show","--no-patch","--format=%P",hi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=We("git",["show","--no-patch","--format=%P",Zn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Xn} ${Zn}`||a!==`${Qn.at(-1)[1]} ${Xn}`)return new Map;const n=We("git",["rev-list","--first-parent","--reverse",Zn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
- `),o=new Map;let d=-1;for(const[s,[l,y]]of Qn.entries()){const S=n.indexOf(y);if(S<=d)return new Map;d=S,o.set(l,{headSha:y,position:s-Qn.length})}return o}catch{return new Map}}async function ac(e,t,i){if(!ui(i))return{};if(i==="audit"||i==="yoloop")return{};if(Tr(t,i))return{};try{const r=JSON.parse(Ge(Q(e,".neocortex","state.json"),"utf8")),a=gn(e,{required:!0}),n=Vr(r,a),o=g(n.stories)?n.stories:{},d=g(n.epics)?n.epics:{},s=We("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=We("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),y=We("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
- `).filter(Boolean),S=new Map(y.map((_,w)=>[_,w])),u=ic(e,y),C=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],E=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,I=Object.entries(o).flatMap(([_,w])=>{if(C&&_!==C)return[];const M=g(w)?w:void 0,N=g(M?.checkpoint)?M.checkpoint:void 0;if(!N)return[];const z=typeof M?.epic_id=="string"?M.epic_id:_.split(".")[0];if(E&&z!==E)return[];const Z=R(N?.headSha),j=z==="P222"?u.get(_):void 0,V=S.get(Z??"")??(j&&j.headSha===Z?j.position:void 0);if(!Z||Z.length<40||V===void 0)return h.add(z),[];const ee=g(d[z])?d[z]:void 0;if(ee?.branch_mode!=="epic"||ve(ee.execution_branch)!==l||ve(N.branch)!==l)return h.add(z),[];const W=R(N.graphRevision);if(!W||W.length!==64)return h.add(z),[];const lt=R(N.claimRevision),Fe=[...Br(_,M,N)].sort(),he=uo(e,N,_,z,l,Fe);if(!he&&lt){if(Fe.length===0)return h.add(z),[];const O=We("git",["diff-tree","--no-commit-id","--name-only","-r","-z",Z],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let H=[];if(N.rootMemoryEffect!==void 0)try{H=ho(e,N.rootMemoryEffect,{storyId:_,executionBranch:l,baseSha:String(N.baseSha),headRef:Z,childPaths:Fe}).files.map(se=>se.path)}catch{return h.add(z),[]}if(O.length===0||O.some(se=>!Fe.some(tt=>tt===se||tt.endsWith("/")&&se.startsWith(tt))&&!H.includes(se)))return h.add(z),[];const Ct=Pe("sha256").update(Fe.join("\0")).digest("hex"),De=Pe("sha256").update(JSON.stringify(Fe)).digest("hex");if(lt!==Ct&&lt!==De)return h.add(z),[]}else if(!he)return h.add(z),[];return W?.length===64?[{storyId:_,epicId:z,graphRevision:W,checkpointHead:Z,position:V}]:[]}),b=new Set(h);for(const[_,w]of Object.entries(d)){const M=g(w)?w:void 0,N=Array.isArray(M?.stories)?M.stories.filter(V=>typeof V=="string"):Object.keys(o).filter(V=>V.startsWith(`${_}.`)),z=I.filter(V=>V.epicId===_),Z=N.filter(V=>z.some(ee=>ee.storyId===V)),j=[...z].sort((V,ee)=>V.position-ee.position).map(V=>V.storyId);(JSON.stringify(Z)!==JSON.stringify(j)||new Set(j).size!==j.length)&&b.add(_)}const L={},T=[...new Set(I.filter(_=>!b.has(_.epicId)).map(_=>_.graphRevision))],P=T.length>0?await oo(e,{headSha:s,graphRevisions:T}):new Map;for(const _ of I){if(b.has(_.epicId))continue;const w=P.get(_.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");L[_.storyId]=w}return await oc({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:d,candidates:I,authorities:L}),L}catch(r){const a=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
- `),{}}}async function oc(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],i=g(t)?t:void 0,r=g(i?.aggregate_qa_receipt)?i.aggregate_qa_receipt:void 0,a=R(i?.graph_revision);if(!r||!a||a.length!==64||r.schemaVersion!==1||r.evidenceVersion!=="p205-execution-v2"||r.producer!=="local-yolo-tdd"||r.contract!=="P205-CI-02"||r.command!==Qt||r.verdict!=="passed"||r.executionHeadSha!==e.currentHead||r.graphRevision!==a||!Array.isArray(r.gateIds)||r.gateIds.length===0||!r.gateIds.every(S=>typeof S=="string")||typeof r.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.manifestDigest)||typeof r.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.resultDigest)||typeof r.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(r.receiptRef))return;const n=r.gateIds,o=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Qt,e.currentHead,a,r.manifestDigest,n.join(","),r.resultDigest].join("\0")).digest("hex")}`;if(r.receiptRef!==o)return;const d=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===a&&e.authorities[S.storyId]),s=d?lo(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==r.manifestDigest||!cc(s.gateIds,n))return;const l=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Qt,e.currentHead,a,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,y=r.receiptRef;await Ur(e.projectRoot,S=>{const u=io(S,e.targetEpicId),C=g(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!C||C.executionHeadSha!==e.currentHead||C.graphRevision!==a||C.receiptRef!==y||(u.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Qt,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:a,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function cc(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,a)=>r===i[a])}function Od(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 gi="neocortex:menu:cache";async function sc(e){try{const t=await e.get(gi);if(!t)return null;const i=JSON.parse(t);return i.version!==Pt||Date.now()-i.cachedAt>Gr?null:i}catch{return null}}async function dc(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(gi,JSON.stringify(r),Gr),pc()}catch{}}function pc(){try{Mt(Wr)&&Nn(Wr)}catch{}}function fi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Mn(),()=>Mn({strictReadOnly:!0}))}async function mi(e,t,i){const r=i.mode==="strict";try{let a;if(r&&t)a=new Dn({cacheDir:Un,passphrase:t,strictReadOnly:!0});else if(r)a=new Rr;else if(t){const y=Q(fn,"cache");a=new Dn({cacheDir:y,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
- `),a=new Rr;const n=Dr(i,a,"auth-cache"),o=Dr(i,a,"tier-cache"),d=new ca({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let s;if(r){const y=await d.inspectToken();if(y.status!=="authenticated")return y;s=y.token}else s=await d.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new sa({cacheProvider:o,licenseClient:d});return{status:"authenticated",token:s,client:d,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let yi=!1;function lc(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 Ii=3,Cn=50;function uc(e){return new Promise(t=>setTimeout(t,e))}function hc(e,t,i){return e.status>=500&&e.status<=599?!0:i&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Xt(e,t,i,r,a={}){const n=Math.max(1,Math.min(a.maxAttempts??Ii,Ii)),o=a.sleep??uc;let d=r,s=!1,l=!1,y=0;for(let S=1;S<=n;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),y+1);y=u;const C=gc(t,i,d,{nowSeconds:u}),E=new AbortController,h=setTimeout(()=>E.abort(),Yr);try{const I=await fetch(`${e}${t}`,{method:"POST",headers:C.headers,body:C.body,signal:E.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(I))return{response:I,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const b=await I.text().catch(()=>""),L=I.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return b?JSON.parse(b):{}}catch{return{}}})();if(I.status===401&&!s&&a.refreshToken&&(L.fallback_action==="refresh_token"||L.fallback_action==="re_authenticate")){s=!0;const T=await a.refreshToken();if(T&&S<n){d=T,a.onTokenChanged?.(T),await o(Cn*S);continue}}if(I.status===401&&L.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await o(Cn*S);continue}if(S<n&&hc(I,L,a.allowReplayRetry===!0)){await o(Cn*S);continue}return{response:I,text:b,parsed:L,networkFailure:!1}}catch{if(S<n){await o(Cn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function gc(e,t,i,r={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=Pa({method:"POST",target:e,body:a,bearerToken:i,clientVersion:Pt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${i}`}}}function Ei(e){return Pe("sha256").update(e).digest("hex")}function fc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function mc(e,t,i){return`args-${Pe("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function Si(e,t,i,r,a={}){const n=await Xt(e,t,i,r,{...a,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:d}=n;if(!o.ok){const s=typeof d.error_code=="string"?d.error_code:`HTTP_${o.status}`,l=typeof d.message=="string"?d.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return d}async function yc(e,t,i,r){const a=Buffer.from(t,"utf8"),n=fc(),o=[];for(let E=0,h=0;E<a.byteLength;E+=n,h++){const I=a.subarray(E,Math.min(E+n,a.byteLength));o.push({index:h,sha256:Ei(I),byteLength:I.byteLength})}const d=Ei(a),s=mc(d,a.byteLength,o),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let y=i;const S={refreshToken:r,onTokenChanged(E){y=E}};for(const E of o){const h=E.index*n,I=a.subarray(h,h+E.byteLength);await Si(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:E.index,sha256:E.sha256,byteLength:E.byteLength,contentBase64:I.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${E.index}:${E.sha256}`},y,S)}const C=(await Si(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:d,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},y,S)).argsRef;if(!C?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:C,chunks:o}}function Ht(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ic(...e){const t=new Set,i=[];for(const r of e)for(const a of r??[]){const n=te(a);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function Ec(e){const t=e.graphRetrieval;if(!g(t))return{accepted:!1,itemCount:0};const i=Array.isArray(t.items)?t.items.length:0;return{accepted:i>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:i}}function er(e,t=Ht(e),i=[],r={}){const a=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,d=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??qr,warningThresholdBytes:r.warningThresholdBytes??$n,scope:{kind:d,...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:Ec(e.stateSnapshot),reasonCodes:Ic(i,a?.reasonCodes),publicSafe:!0}}function Sc(e){const t=g(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function vc(e){return g(e)?{stableId:te(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function vi(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Cc(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const i=Sc(t);let r=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>i&&r.length>0;){const o=r.pop();a=[...a,vc(o)].slice(-32),n={...t,items:r,skipped:a,warnings:vi(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>i&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:vi(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function tr(e,t={}){const i=t.limitBytes??qr,r=t.warningThresholdBytes??Math.floor(i*zr),a=Ht(e);if(a<i)return{body:e,degraded:!1,telemetry:er(e,a,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:r})};let n={...e,stateSnapshot:ga(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],d=Ht(n);d>=i&&(n={...n,stateSnapshot:Cc(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],d=Ht(n));const s=er(n,d,o,{limitBytes:i,warningThresholdBytes:r});if(d>=i){const l=n.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new qn(s):new Fn(s)}return{body:n,degraded:!0,telemetry:s}}function Ci(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function _c(e){const t=Ht(e);if(t<$n)return t;const i=er(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Ci(e)} scope=${i.scope.kind} mode=${i.scope.projectionMode??i.scope.kind} payloadBytes=${i.payloadBytes} limit=${i.limitBytes} includedStories=${i.includedStories} omittedStories=${i.omittedStories} includedEpics=${i.includedEpics} omittedEpics=${i.omittedEpics} graphRetrieval.accepted=${i.graphRetrieval.accepted} graphRetrieval.itemCount=${i.graphRetrieval.itemCount} reasonCodes=${i.reasonCodes.join(",")||"none"}
13
- `),t}function _i(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Ci(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 Rc(e){const t=va(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:wc(t),metadata:Ri(t)};const i=e.bootstrapper??_a;let r;try{r=await i({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Ca.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=Ri(t,r);if(r.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 wc(e){return!e.reasonCodes.includes(Sa.SKIPPED_NON_CONTINUITY_COMMAND)}function Ri(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:Me([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Me(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function _n(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function Rn(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function q(e,t=ei){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=ze(i,t),a=Do.test(r)?Et:r;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function nr(e,t=ei){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function rr(e,t,i,r){const a=nr(e?.targetId??t,120),n=e?.selectorKind??(a?ar(a):void 0),o=(e?.relatedJobIds??[]).map(d=>nr(d,120)).filter(d=>!!d);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...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:Me(r.length>0?r:[F.OK]),publicSafe:!0}}function dt(e,t,i,r,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":i&&r===0?"empty":"available":"unavailable",d=nr(t[t.length-1]?.eventId,120),s=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:r,...d?{latestEventId:d}:{},reasonCodes:Me(s),publicSafe:!0}}function Xe(e,t,i,r,a=[],n){const o=r[r.length-1],d=i??o?.cursor,s=!!(d&&d!==t&&r.length>0),l=n??(s?"advanced":t||d?"unchanged":"not_started"),y=a.length>0?a:l==="advanced"?[F.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[F.WATCH_EVIDENCE_UNAVAILABLE]:[F.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...d?{nextCursor:q(d,200)}:{},cursorAdvanced:s,...o?.eventId?{eventId:q(o.eventId,120)}:{},reasonCodes:Me(y),publicSafe:!0}}function Ze(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:Me([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Ac(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",d=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${i}`,`snapshot=${d}`,`generatedAt=${s}`,`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 et(e,t,i,r=!1){if(r){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};i.write(t==="json"?`${JSON.stringify(a)}
7
+ `)}catch{}}}function Gd(){Kn=!1}function ri(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Xo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Zo=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"]),ec=/(?:[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 tc(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),n=Buffer.byteLength(i);if(n>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:n<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(ec.test(i))return{};const a=(o,d)=>{if(Object.keys(o).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!g(e.intake))return{};if(Object.keys(e.intake).some(o=>!Zo.has(o)))return{};for(const[o,d]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!g(l))return{};if(a(l,s),Object.values(l).some(y=>typeof y!="string"||y.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(o==="rawIntent"?aa:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const r=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!g(o))return{};if(a(o,r),Object.values(o).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[o];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ii(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function nc(e){const t={};let i=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const a=e[n];if(!Array.isArray(a)||a.length>128||a.some(r=>hn(r)===void 0)){i=!0;continue}t[n]=a.map(r=>hn(r))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const n=e.planning;for(const o of["claims","semanticArtifacts"]){if(n[o]===void 0)continue;const d=n[o];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(n.attempts!==void 0&&(!Array.isArray(n.attempts)||n.attempts.length>32))throw new Error("planning-attempts");for(const o of n.attempts??[]){if(!g(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(d=>!g(d)||hn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...r}=ro(n);t.planning=r}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Q(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function q(e){if(typeof e!="string")return;const t=e.trim(),i=Q(e);return i===t?i:void 0}function Ee(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(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(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 pt(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 En(e){if(!g(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),n=(u,C)=>Array.isArray(u)&&u.length<=C&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,C)=>{if(!(!g(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||C&&(!i(u.outputHash)||!i(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,...C?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},r=(u,C)=>{if(!(!g(u)||u.schemaVersion!=="1.1"||u.kind!==C||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:C,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,C)=>{if(!g(u)||u.kind!==C||!i(u.receiptId)||!n(u.evidenceIds,24)||C==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||C==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const h=C==="architecture-stage-validation"?r(u.isolated,"isolated"):void 0,I=C==="architecture-stage-validation"?r(u.regression,"regression"):void 0;if(!(C==="architecture-stage-validation"&&(!h||!I)))return{...E,kind:C,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...h&&I?{isolated:h,regression:I}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=n(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=Er(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!g(e.accounting)||u.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}g(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&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const y=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(y&&(d.completionEvidence=y),S&&(d.validationEvidence=S),g(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&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=n(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(g(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=n(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(C=>{if(!g(C)||!t(C.targetEpicId)||!t(C.stageCommand))return;const E=o(C.completionEvidence,"architecture-stage-completion"),h=o(C.validationEvidence,"architecture-stage-validation");return E&&h?{targetEpicId:C.targetEpicId,stageCommand:C.stageCommand,completionEvidence:E,validationEvidence:h}:void 0});u.every(C=>C!==void 0)&&(d.acceptedStages=u)}if(g(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=n(e.accounting.receiptIds,32);u&&(d.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(d).length<=96e3?d:void 0}function rc(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=g(t)?t.checkpoint:void 0,n=g(t)?t:void 0,a=g(i)?i:void 0,r=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],d=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.completionEvidence===void 0&&r.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&n?.nextAction==="delegate",s=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&g(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,r.completionEvidence)&&v(o[0].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",l=r.currentStageCommand==="arch-architecture"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",y=r.currentStageCommand==="arch-architecture"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===1&&v(o[0],r.acceptedStages[0])&&v(o[1].completionEvidence,r.completionEvidence)&&v(o[1].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",S=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",u=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===2&&v(o.slice(0,2),r.acceptedStages)&&v(o[2].completionEvidence,r.completionEvidence)&&v(o[2].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",C=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&g(o[3])&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===3&&v(o.slice(0,3),r.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,r.completionEvidence)&&v(o[3].validationEvidence,r.validationEvidence)&&v(a.questionIds,E)&&v(n?.questionIds,E)&&n?.nextAction==="ask-user",I=r.currentStageCommand==="generate-pacts"&&r.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,r.acceptedStages)&&v(r.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(n?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&n?.nextAction==="resume",b=r.currentStageCommand==="generate-pacts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&v(r.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===4&&v(o.slice(0,4),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(o[4])&&v(o[4].completionEvidence,r.completionEvidence)&&v(o[4].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",M=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",P=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===5&&v(o.slice(0,5),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(o[5])&&v(o[5].completionEvidence,r.completionEvidence)&&v(o[5].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",k=r.currentStageCommand==="arch-database"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",_=r.currentStageCommand==="arch-database"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===6&&v(o.slice(0,6),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&g(o[6])&&v(o[6].completionEvidence,r.completionEvidence)&&v(o[6].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",w=r.currentStageCommand==="arch-security"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",L=r.currentStageCommand==="arch-security"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===7&&v(o.slice(0,7),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&g(o[7])&&v(o[7].completionEvidence,r.completionEvidence)&&v(o[7].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",D=r.currentStageCommand==="arch-design-system"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",Y=r.currentStageCommand==="arch-design-system"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===8&&v(o.slice(0,8),r.acceptedStages)&&o.map(V=>g(V)?V.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"&&g(o[8])&&v(o[8].completionEvidence,r.completionEvidence)&&v(o[8].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",X=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,r.acceptedStages)&&n?.nextAction==="blocked",pe=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===9&&v(o.slice(0,9),r.acceptedStages)&&o.map(V=>g(V)?V.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"&&g(o[9])&&v(o[9].completionEvidence,r.completionEvidence)&&v(o[9].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",x=r.currentStageCommand==="arch-performance"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",Se=r.currentStageCommand==="arch-performance"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===10&&v(o.slice(0,10),r.acceptedStages)&&o.map(V=>g(V)?V.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"&&g(o[10])&&v(o[10].completionEvidence,r.completionEvidence)&&v(o[10].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",Z=r.currentStageCommand==="arch-testing"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",J=r.currentStageCommand==="arch-testing"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===11&&v(o.slice(0,11),r.acceptedStages)&&o.map(V=>g(V)?V.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"&&g(o[11])&&v(o[11].completionEvidence,r.completionEvidence)&&v(o[11].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",gt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",wt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===12&&v(o.slice(0,12),r.acceptedStages)&&o.map(V=>g(V)?V.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"&&g(o[12])&&v(o[12].completionEvidence,r.completionEvidence)&&v(o[12].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",ue=r.currentStageCommand==="arch-review"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",O=r.currentStageCommand==="arch-review"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&r.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,r.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&n?.nextAction==="ask-user",$=r.currentStageCommand==="arch-review"&&r.continuationState==="ask-user"&&r.childStatus==="succeeded"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&v(r.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===13&&v(o.slice(0,13),r.acceptedStages)&&g(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,r.completionEvidence)&&v(o[13].validationEvidence,r.validationEvidence)&&v(a.reviewDecision,r.reviewDecision)&&n?.nextAction==="resume",xe=r.currentStageCommand==="update-memory"&&r.continuationState==="advance"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,r.acceptedStages)&&v(a.reviewDecision,r.reviewDecision)&&n?.nextAction==="delegate",Te=r.currentStageCommand==="update-memory"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===14&&v(o.slice(0,14),r.acceptedStages)&&g(o[14])&&o[14].targetEpicId===r.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,r.completionEvidence)&&v(o[14].validationEvidence,r.validationEvidence)&&v(a.reviewDecision,r.reviewDecision)&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,r)!==null&&v(a.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Pe=r.currentStageCommand==="update-memory"&&r.continuationState==="complete"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,r.acceptedStages)&&v(a.reviewDecision,r.reviewDecision)&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,r)&&v(a.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Nt=n?qi(r,n,Ft(r.terminalMemoryCheckpoint,r)&&v(a?.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==r.targetEpicId||i.graphRevision!==r.graphRevision||i.graphSource!==r.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(Nt||d||s||l||y||S||u||C||h||I||b||M||P||k||_||w||L||D||Y||X||pe||x||Se||Z||J||gt||wt||ue||O||$||xe||Te||Pe)||!g(i.accounting)||i.accounting.charged!==!0||!v(En(i),i))throw new Error("architecture-root-checkpoint-invalid");const rt=z(e.projectRoot,".neocortex"),K=z(rt,"state.json"),ve=z(rt,"state.json.architecture.lock"),he=zt(ve,"wx",384);let qe;try{const V=Vt(K);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(K,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const ge=JSON.parse(ft),oe=g(ge)&&g(ge.archPlan)?ge.archPlan:{};if(!g(ge)||!g(ge.epics)||!Object.hasOwn(ge.epics,i.targetEpicId)||(e.initialBinding?oe.execution!==void 0||r.graphSource!=="committed-epic-v1":!v(En(oe.execution),r))||g(ge.scope)&&ge.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...r,continuationState:"delegate",acceptedStages:r.acceptedStages.slice(0,Ir(r))};if(!v(r.terminalMemoryCheckpoint,Ln(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const ye=dn(),Ve=Ge("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ee=Zi(Ve)?Mn(Ve):Mn(e.projectRoot,Ve);if(Xi(ee)!==ee)throw new Error("architecture-root-backup-dir-invalid");const mt=z(ee,"neocortex-architecture");qt(mt,{recursive:!0,mode:448});const ze=Vt(mt);if(!ze.isDirectory()||ze.isSymbolicLink()||ze.uid!==process.getuid?.()||(ze.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ke=z(mt,`state-backup-${ye}.json`),Qe=zt(ke,"wx",384);try{pn(Qe,ft),ln(Qe)}finally{Jt(Qe)}const H=zt(mt,"r");try{ln(H)}finally{Jt(H)}const bn={...ge,archPlan:{...oe,execution:i}};qe=z(rt,`state.json.architecture-tmp-${ye}`);const it=zt(qe,"wx",384);try{pn(it,`${JSON.stringify(bn,null,2)}
8
+ `),ln(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!v(r.terminalMemoryCheckpoint,Ln(e.projectRoot,r)))throw new Error("architecture-root-state-conflict");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");vr(qe,K),qe=void 0;const N=zt(rt,"r");try{ln(N)}finally{Jt(N)}}finally{if(qe)try{Dn(qe)}catch{}Jt(he),Dn(ve)}}function Sn(e,t){if(!g(e))return;const i={};for(const n of t){const a=e[n];if(typeof a=="boolean")i[n]=a;else if(typeof a=="number"&&Number.isFinite(a))i[n]=a;else if(typeof a=="string"){const r=Q(a);r&&(i[n]=r)}}return Object.keys(i).length>0?i:void 0}function vn(e){return e==="epic"||e==="story"?e:void 0}function ai(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.ownerStoryId),i=q(e.sessionId),n=q(e.idempotencyKey),a=De(e.acquiredAt),r=De(e.expiresAt);if(!(!t||!i||!n||!a||!r||Date.parse(r)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:n,acquiredAt:a,expiresAt:r}}function oi(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),n=Ee(e.branch),a=R(e.baseSha),r=R(e.headSha),o=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(R).filter(M=>!!M).slice(0,256),l=de(e.receiptRefs).map(pt).filter(M=>!!M).slice(0,256),y=e.dispatchId===void 0?void 0:q(e.dispatchId),S=e.bundleId===void 0?void 0:q(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),C=e.graphRevision===void 0?void 0:R(e.graphRevision),E=e.claimRevision===void 0?void 0:q(e.claimRevision),h=ic(e.qaReceipt),I=ac(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:So(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!n||!a||!r||a===r||!o||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!C||C.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==n||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!I||e.reviewVerdict==="pending"&&I||h.verdict!==e.qaVerdict||I&&I.verdict!==e.reviewVerdict||!di(h,{storyId:t,epicId:i,baseSha:a,headSha:r,bundleDigest:u,graphRevision:C})||I&&(!di(I,{storyId:t,epicId:i,baseSha:a,headSha:r,bundleDigest:u,graphRevision:C})||I.qaReceiptRef!==h?.receiptRef||I.receiptRef===h?.receiptRef)||!l.includes(String(h.receiptRef))||I&&(!l.includes(String(I.receiptRef))||Date.parse(String(I.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:n,baseSha:a,headSha:r,idempotencyKey:o,...y?{dispatchId:y}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...C?{graphRevision:C}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...I?{reviewReceipt:I}:{},recordedAt:d,commits:s,receiptRefs:l}}function ic(e){if(!g(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=q(e.storyId),i=q(e.epicId),n=R(e.baseSha),a=R(e.headSha),r=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=De(e.checkedAt),l=pt(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,C=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(q).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!i||!n||!a||!r||r.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!y||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!C||C.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:S,manifestDigest:u,gateIds:E,resultDigest:C}:{},baseSha:n,headSha:a,bundleDigest:r,graphRevision:o,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ci(e){if(!g(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=q(e.storyId),i=q(e.epicId),n=Ee(e.branch),a=R(e.baseSha),r=R(e.headSha),o=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=R(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=R(e.manifestDigest),C=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),E=R(e.resultDigest),h=R(e.graphRevision),I=R(e.executionEvidenceDigest),b=R(e.sourceEvidenceDigest),M=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).slice(0,16);if(!(!t||!i||!n||!a||a.length<40||!r||r.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||!y||y.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||C.length!==e.gateIds.length||!E||E.length!==64||!h||h.length!==64||!I||I.length!==64||!b||b.length!==64||!M||P.length===0||e.verdict==="verified"&&(C.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:n,baseSha:a,headSha:r,aggregateHeadSha:o,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:y,command:S,manifestDigest:u,gateIds:C,resultDigest:E,graphRevision:h,executionEvidenceDigest:I,sourceEvidenceDigest:b,verifiedAt:M,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function si(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!g(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 i=q(e.storyId),n=q(e.epicId),a=Ee(e.branch),r=R(e.baseSha),o=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),y=De(e.verifiedAt),S=de(e.reasonCodes).map(q).filter(u=>!!u);if(!(!i||!n||!a||!r||r.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!y||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:n,branch:a,baseSha:r,headSha:o,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:y,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function ac(e){if(!g(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=q(e.storyId),i=q(e.epicId),n=R(e.baseSha),a=R(e.headSha),r=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),y=pt(e.receiptRef);if(!(!t||!i||!n||!a||!r||r.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:n,headSha:a,bundleDigest:r,graphRevision:o,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:y}}function di(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function pi(e){if(!g(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,i=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!i)return;const n=Ee(e.originBranch),a=R(e.originHeadSha),r=Ee(e.executionBranch),o=De(e.capturedAt);if(!(!n||!a||a.length<40||!r||!o||n===r))return t?{schemaVersion:1,originBranch:n,originHeadSha:a,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:o}:{schemaVersion:2,originBranch:n,originHeadSha:a,executionBranch:r,capturedFrom:e.capturedFrom,capturedAt:o}}function li(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),n=De(e.checkedAt),a=pt(e.receiptRef),r=de(e.gateIds).map(q).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",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?R(e.manifestDigest):void 0,l=o?R(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!n||!a||r.length===0||!Array.isArray(e.gateIds)||r.length!==e.gateIds.length||e.gateIds.length>128||!d&&!o||o&&(!s||s.length!==64||!l||l.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:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:n,receiptRef:a,gateIds:r}}const oc=16384;function cc(e){if(!g(e))return;const t=(n,a)=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"?n.length<=512&&!n.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(n)&&!n.includes("\\")&&!/:\/\//.test(n)&&!/[\u0000-\u001f]/.test(n):a>=4?!1:Array.isArray(n)?n.length<=256&&n.every(r=>t(r,a+1)):g(n)?Object.keys(n).length<=64&&Object.entries(n).every(([r,o])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(r)&&t(o,a+1)):!1;if(!t(e,0))return;const i=JSON.stringify(e);if(!(Buffer.byteLength(i,"utf8")>oc))return JSON.parse(i)}function ui(e){if(!g(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:q(e.epicId),executionBranch:Ee(e.executionBranch),originBranch:Ee(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],n=i.filter(d=>e[d]!==void 0).length;if(n!==0&&n!==i.length)return;const a=n===0?void 0:{originSyncHeadSha:R(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:R(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:R(e.originSyncResolvedPathsDigest)};if(a&&(!a.originSyncHeadSha||a.originSyncHeadSha.length<40||a.originSyncCommitShas.length===0||a.originSyncCommitShas.length>256||a.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||a.originSyncPaths.length>2048||a.originSyncResolvedPaths.length>64||a.originSyncPathsDigest!==gn(a.originSyncPaths)||a.originSyncResolvedPathsDigest!==gn(a.originSyncResolvedPaths))||!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(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||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!==ao(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==gn(t.changedPaths)||t.allowedWriteSetDigest!==gn(t.allowedWriteSet))return;const r={...t,...a??{}},o=R(e.inputDigest);if(!(!o||o.length!==64||o!==io(r)))return{...r,inputDigest:o}}function Qn(e){if(!g(e)||e.schemaVersion!==1)return;const t=Sn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=de(e.receiptRefs).map(pt).filter(a=>!!a).slice(0,256),n=de(e.revertCommits).map(Q).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...n.length?{revertCommits:n}:{}}}function sc(e){if(!(!g(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 hi(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=q(e.epicId),i=Ee(e.executionBranch),n=Ee(e.originBranch),a=R(e.baseSha),r=R(e.executionHeadSha),o=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=q(e.idempotencyKey),l=De(e.attemptStartedAt),y=e.completedAt===void 0?void 0:De(e.completedAt),S=de(e.localGateReceiptRefs).map(pt).filter(h=>!!h).slice(0,256),u=de(e.reasonCodes).map(q).filter(h=>!!h).slice(0,64),C=pc(e.candidateQa),E=dc(e.providerGuard);if(!(!t||!i||!n||!a||!r||!s||!l||S.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&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:n,baseSha:a,executionHeadSha:r,...o?{mergeSha:o}:{},...d?{pushedSha:d}:{},strategy:e.strategy,..._t(e.prNumber)?{prNumber:_t(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...C?{candidateQa:C}:{},...E?{providerGuard:E}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function dc(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),n=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=R(e.prHeadSha),r=R(e.originHeadSha),o=De(e.checkedAt);if(!(!n||!a||!r||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:r,checkedAt:o,publicSafe:!0}}function pc(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,R(e[o])])),n=De(e.checkedAt),a=pt(e.receiptRef),r=de(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!n||!a||r.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:n,receiptRef:a,gateIds:r}}function lc(e){if(!g(e))return;const t={...Q(e.active_epic_id??e.activeEpicId)?{active_epic_id:Q(e.active_epic_id??e.activeEpicId)}:{},...Q(e.active_story_id??e.activeStoryId)?{active_story_id:Q(e.active_story_id??e.activeStoryId)}:{},...Q(e.active_step_id??e.activeStepId)?{active_step_id:Q(e.active_step_id??e.activeStepId)}:{},...Q(e.session_id??e.sessionId)?{session_id:Q(e.session_id??e.sessionId)}:{},...Q(e.started_at??e.startedAt)?{started_at:Q(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function uc(e){const t=Sn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=Sn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=Sn(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}:{},...Q(e.physicalMergeStatus)?{physicalMergeStatus:Q(e.physicalMergeStatus)}:{},...Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...Q(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:Q(e.issue_state??e.issueState??e.workflow_issue_state)}:{},..._t(e.issue_number??e.issueNumber)?{issue_number:_t(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...n?{scopedCiEvidence:n}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const hc=new Set(["yolo","yoloop","finalize-epic","audit"]);function gi(e){return typeof e=="string"&&hc.has(e)}function Xn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let n;try{n=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!g(n)||!g(n.epics)||!g(n.stories))throw new lt("git-lifecycle-state-shape-invalid");const a=Object.values(n.epics).some(r=>g(r)&&(r.branch_mode==="epic"||Ee(r.execution_branch)!==void 0));if(a)try{fn(e,{required:!0})}catch(r){const o=r instanceof Error&&/^git-lifecycle-/.test(r.message)?r.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function Cn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n,a;try{const E=Fe(i,"utf-8");a=Ne("sha256").update(E).digest("hex");const h=Ea(e,a)??JSON.parse(E),I=g(h.epics)?h.epics:{},b=Object.values(I).some(w=>g(w)&&(w.branch_mode==="epic"||Ee(w.execution_branch)!==void 0)),M=fn(e,{required:!!(t.epicAware&&b&&!t.projectless)});n=Br(h,M);const P=g(n.stories)?n.stories:{},k=g(n.epics)?n.epics:{},_=g(h.stories)?h.stories:{};for(const[w,L]of Object.entries(P)){const D=g(L)?L:void 0;if(!D?.checkpoint)continue;const Y=typeof D.epic_id=="string"?D.epic_id:w.split(".")[0],X=g(k[Y])?k[Y]:void 0,pe=Ee(X?.execution_branch);if(!pe)continue;const x=oo(e,D.checkpoint,w,Y,pe,t.p205Authorities?.[w],Ur(w,D,g(D.checkpoint)?D.checkpoint:void 0));if(x.kind==="integration-authorized")D.checkpoint_verification=x.verification,delete D.scheduling_checkpoint_evidence;else if(x.kind==="scheduling-only")D.scheduling_checkpoint_evidence=x.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(x.kind==="rejected"){D.checkpoint_verification=x.verification,delete D.scheduling_checkpoint_evidence;const Se=g(_[w])?_[w]:void 0;if(delete D.checkpoint,M.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?D[Z]=structuredClone(Se[Z]):delete D[Z];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const h=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new lt(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Ko(n);E.length>0&&Qo(E)}catch{}const r=n.config??n.project??{},o=n.stories??{},d={};for(const[E,h]of Object.entries(o)){const I=g(h.review_request)&&h.review_request.kind==="git-pull-request"?sc(h.review_request):Qn(h.review_request);d[E]={id:h.id??E,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...ii(h.source)?{source:ii(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...oi(h.checkpoint)?{checkpoint:oi(h.checkpoint)}:{},...ci(h.checkpoint_verification)?{checkpoint_verification:ci(h.checkpoint_verification)}:{},...si(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:si(h.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Qn(h.rollback_receipt)?{rollback_receipt:Qn(h.rollback_receipt)}:{},..._t(h.workflow_issue)?{workflow_issue:_t(h.workflow_issue)}:{},...uc(h),...Array.isArray(h.depends_on)?{depends_on:ri(h.depends_on)}:{},files_to_modify:de(h.files_to_modify),...nc(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const s=n.epics??{},l={};for(const[E,h]of Object.entries(s)){const I=Xo(h.lifecycle_classification),b=tc(h.createEpicPlanning,E),M=b.checkpoint;let P,k,_,w;if(M&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Cr(n,h.createEpicPlanningClaim.claimId,E,!0),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(P&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningResearchPhysical))try{_r(n,h.createEpicPlanningClaim.claimId,E),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&M&&h.status==="generated"&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningGenerationPhysical))try{if(ia(e,h.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(_&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const L=Rr(e,h.createEpicPlanningClaim.claimId,E);if(L.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(L))}catch{}l[E]={id:h.id??E,title:h.title,...M?{createEpicPlanning:M}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:ri(h.depends_on),...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...Ee(h.execution_branch)?{execution_branch:Ee(h.execution_branch)}:{},...Ee(h.origin_branch)?{origin_branch:Ee(h.origin_branch)}:{},...ai(h.branch_lease)?{branch_lease:ai(h.branch_lease)}:{},...pi(h.origin_binding)?{origin_binding:pi(h.origin_binding)}:{},...li(h.aggregate_qa_receipt)?{aggregate_qa_receipt:li(h.aggregate_qa_receipt)}:{},...ui(h.head_reconciliation_receipt)?{head_reconciliation_receipt:ui(h.head_reconciliation_receipt)}:{},...mo(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...(L=>L?{branch_mode_conversion_receipt:L}:{})(cc(h.branch_mode_conversion_receipt)),..._t(h.pr_number)?{pr_number:_t(h.pr_number)}:{},...Q(h.physicalMergeStatus)?{physicalMergeStatus:Q(h.physicalMergeStatus)}:{},...R(h.graph_revision)?{graph_revision:R(h.graph_revision)}:{},...hi(h.terminal_git_receipt)?{terminal_git_receipt:hi(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=lc(n.current_session??n.currentSession),S=g(n.archPlan)?En(n.archPlan.execution):void 0,u=n.epic_id_ledger,C=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:r.project_name??r.name??"unknown",default_branch:r.default_branch??"main",language:r.language??"pt-BR",yolo_mode:r.yolo_mode,user_name:r.user_name,worktree_base:r.worktree_base,max_parallel_stories:r.max_parallel_stories,project_id:typeof r.project_id=="string"?r.project_id:void 0},stories:d,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...y?{current_session:y}:{},...S?{archPlan:{execution:S}}:{}}}const Zn=[["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"]],er="6a41a47ff2521f80c2296ed811b0f0b304c54750",tr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",fi="30dccfff07f9c969be11ae1d28e62a09731a0768";function gc(e,t){try{const i=t.indexOf(fi);if(i<1||t[i-1]!==er)return new Map;const n=Ge("git",["show","--no-patch","--format=%P",fi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=Ge("git",["show","--no-patch","--format=%P",tr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(n!==`${er} ${tr}`||a!==`${Zn.at(-1)[1]} ${er}`)return new Map;const r=Ge("git",["rev-list","--first-parent","--reverse",tr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
+ `),o=new Map;let d=-1;for(const[s,[l,y]]of Zn.entries()){const S=r.indexOf(y);if(S<=d)return new Map;d=S,o.set(l,{headSha:y,position:s-Zn.length})}return o}catch{return new Map}}function fc(e){return e instanceof Error&&(lo(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}async function mc(e,t,i){if(!gi(i))return{};if(i==="audit"||i==="yoloop")return{};if(kr(t,i))return{};try{const n=JSON.parse(Fe(z(e,".neocortex","state.json"),"utf8")),a=fn(e,{required:!0}),r=Br(n,a),o=g(r.stories)?r.stories:{},d=g(r.epics)?r.epics:{},s=Ge("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),y=Ge("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
+ `).filter(Boolean),S=new Map(y.map((_,w)=>[_,w])),u=gc(e,y),C=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],E=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,I=Object.entries(o).flatMap(([_,w])=>{if(C&&_!==C)return[];const L=g(w)?w:void 0,D=g(L?.checkpoint)?L.checkpoint:void 0;if(!D)return[];const Y=typeof L?.epic_id=="string"?L.epic_id:_.split(".")[0];if(E&&Y!==E)return[];const X=R(D?.headSha),pe=Y==="P222"?u.get(_):void 0,x=S.get(X??"")??(pe&&pe.headSha===X?pe.position:void 0);if(!X||X.length<40||x===void 0)return h.add(Y),[];const Se=g(d[Y])?d[Y]:void 0;if(Se?.branch_mode!=="epic"||Ee(Se.execution_branch)!==l||Ee(D.branch)!==l)return h.add(Y),[];const Z=R(D.graphRevision);if(!Z||Z.length!==64)return h.add(Y),[];const J=R(D.claimRevision),gt=[...Ur(_,L,D)].sort(),wt=Io(e,D,_,Y,l,gt);if(!wt&&J){if(gt.length===0)return h.add(Y),[];const ue=Ge("git",["diff-tree","--no-commit-id","--name-only","-r","-z",X],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),O=ho(_,gt).map(xe=>[...xe].sort()).find(xe=>J===Ne("sha256").update(xe.join("\0")).digest("hex")||J===Ne("sha256").update(JSON.stringify(xe)).digest("hex"));if(!O)return h.add(Y),[];let $=[];if(D.rootMemoryEffect!==void 0)try{$=Eo(e,D.rootMemoryEffect,{storyId:_,executionBranch:l,baseSha:String(D.baseSha),headRef:X,childPaths:O}).files.map(xe=>xe.path)}catch{return h.add(Y),[]}if(ue.length===0||ue.some(xe=>!O.some(Te=>go(Te,xe))&&!$.includes(xe)))return h.add(Y),[]}else if(!wt)return h.add(Y),[];return Z?.length===64?[{storyId:_,epicId:Y,graphRevision:Z,checkpointHead:X,position:x}]:[]}),b=new Set(h);for(const[_,w]of Object.entries(d)){const L=g(w)?w:void 0,D=Array.isArray(L?.stories)?L.stories.filter(x=>typeof x=="string"):Object.keys(o).filter(x=>x.startsWith(`${_}.`)),Y=I.filter(x=>x.epicId===_),X=D.filter(x=>Y.some(Se=>Se.storyId===x)),pe=[...Y].sort((x,Se)=>x.position-Se.position).map(x=>x.storyId);(JSON.stringify(X)!==JSON.stringify(pe)||new Set(pe).size!==pe.length)&&b.add(_)}const M={},P=[...new Set(I.filter(_=>!b.has(_.epicId)).map(_=>_.graphRevision))],k=P.length>0?await po(e,{headSha:s,graphRevisions:P}):new Map;for(const _ of I){if(b.has(_.epicId))continue;const w=k.get(_.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");M[_.storyId]=w}return await yc({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:d,candidates:I,authorities:M}),M}catch(n){const a=fc(n);return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
+ `),{}}}async function yc(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],i=g(t)?t:void 0,n=g(i?.aggregate_qa_receipt)?i.aggregate_qa_receipt:void 0,a=R(i?.graph_revision);if(!n||!a||a.length!==64||n.schemaVersion!==1||n.evidenceVersion!=="p205-execution-v2"||n.producer!=="local-yolo-tdd"||n.contract!=="P205-CI-02"||n.command!==Xt||n.verdict!=="passed"||n.executionHeadSha!==e.currentHead||n.graphRevision!==a||!Array.isArray(n.gateIds)||n.gateIds.length===0||!n.gateIds.every(S=>typeof S=="string")||typeof n.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(n.manifestDigest)||typeof n.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(n.resultDigest)||typeof n.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(n.receiptRef))return;const r=n.gateIds,o=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,n.manifestDigest,r.join(","),n.resultDigest].join("\0")).digest("hex")}`;if(n.receiptRef!==o)return;const d=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===a&&e.authorities[S.storyId]),s=d?yo(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==n.manifestDigest||!Ic(s.gateIds,r))return;const l=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,y=n.receiptRef;await $r(e.projectRoot,S=>{const u=co(S,e.targetEpicId),C=g(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!C||C.executionHeadSha!==e.currentHead||C.graphRevision!==a||C.receiptRef!==y||(u.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Xt,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:a,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function Ic(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((n,a)=>n===i[a])}function Fd(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 mi="neocortex:menu:cache";async function Ec(e){try{const t=await e.get(mi);if(!t)return null;const i=JSON.parse(t);return i.version!==Pt||Date.now()-i.cachedAt>Yr?null:i}catch{return null}}async function Sc(e,t,i){try{const n={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(mi,JSON.stringify(n),Yr),vc()}catch{}}function vc(){try{jt(Fr)&&Dn(Fr)}catch{}}function yi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Vn(),()=>Vn({strictReadOnly:!0}))}async function Ii(e,t,i){const n=i.mode==="strict";try{let a;if(n&&t)a=new jn({cacheDir:Hn,passphrase:t,strictReadOnly:!0});else if(n)a=new Ar;else if(t){const y=z(mn,"cache");a=new jn({cacheDir:y,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
+ `),a=new Ar;const r=jr(i,a,"auth-cache"),o=jr(i,a,"tier-cache"),d=new da({serverUrl:e,licenseKey:t??"",cacheProvider:r,strictReadOnly:n});let s;if(n){const y=await d.inspectToken();if(y.status!=="authenticated")return y;s=y.token}else s=await d.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new pa({cacheProvider:o,licenseClient:d});return{status:"authenticated",token:s,client:d,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Ei=!1;function Cc(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 Si=3,_n=50;function _c(e){return new Promise(t=>setTimeout(t,e))}function Rc(e,t,i){return e.status>=500&&e.status<=599?!0:i&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Zt(e,t,i,n,a={}){const r=Math.max(1,Math.min(a.maxAttempts??Si,Si)),o=a.sleep??_c;let d=n,s=!1,l=!1,y=0;for(let S=1;S<=r;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),y+1);y=u;const C=wc(t,i,d,{nowSeconds:u}),E=new AbortController,h=setTimeout(()=>E.abort(),qr);try{const I=await fetch(`${e}${t}`,{method:"POST",headers:C.headers,body:C.body,signal:E.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(I))return{response:I,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const b=await I.text().catch(()=>""),M=I.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return b?JSON.parse(b):{}}catch{return{}}})();if(I.status===401&&!s&&a.refreshToken&&(M.fallback_action==="refresh_token"||M.fallback_action==="re_authenticate")){s=!0;const P=await a.refreshToken();if(P&&S<r){d=P,a.onTokenChanged?.(P),await o(_n*S);continue}}if(I.status===401&&M.error_code==="SIGNATURE_EXPIRED"&&!l&&S<r){l=!0,await o(_n*S);continue}if(S<r&&Rc(I,M,a.allowReplayRetry===!0)){await o(_n*S);continue}return{response:I,text:b,parsed:M,networkFailure:!1}}catch{if(S<r){await o(_n*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function wc(e,t,i,n={}){const a=Buffer.from(JSON.stringify(t),"utf8"),r=Na({method:"POST",target:e,body:a,bearerToken:i,clientVersion:Pt,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:r.body,headers:{...r.headers,Authorization:`Bearer ${i}`}}}function vi(e){return Ne("sha256").update(e).digest("hex")}function Ac(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function bc(e,t,i){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function Ci(e,t,i,n,a={}){const r=await Zt(e,t,i,n,{...a,allowReplayRetry:!0});if(r.networkFailure||!r.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:d}=r;if(!o.ok){const s=typeof d.error_code=="string"?d.error_code:`HTTP_${o.status}`,l=typeof d.message=="string"?d.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return d}async function xc(e,t,i,n){const a=Buffer.from(t,"utf8"),r=Ac(),o=[];for(let E=0,h=0;E<a.byteLength;E+=r,h++){const I=a.subarray(E,Math.min(E+r,a.byteLength));o.push({index:h,sha256:vi(I),byteLength:I.byteLength})}const d=vi(a),s=bc(d,a.byteLength,o),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let y=i;const S={refreshToken:n,onTokenChanged(E){y=E}};for(const E of o){const h=E.index*r,I=a.subarray(h,h+E.byteLength);await Ci(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:E.index,sha256:E.sha256,byteLength:E.byteLength,contentBase64:I.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${E.index}:${E.sha256}`},y,S)}const C=(await Ci(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:d,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},y,S)).argsRef;if(!C?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:C,chunks:o}}function Wt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Tc(...e){const t=new Set,i=[];for(const n of e)for(const a of n??[]){const r=Q(a);if(!(!r||t.has(r))&&(t.add(r),i.push(r),i.length>=16))return i}return i}function Pc(e){const t=e.graphRetrieval;if(!g(t))return{accepted:!1,itemCount:0};const i=Array.isArray(t.items)?t.items.length:0;return{accepted:i>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:i}}function nr(e,t=Wt(e),i=[],n={}){const a=e.stateSnapshot.scope,r=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,d=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:n.limitBytes??Jr,warningThresholdBytes:n.warningThresholdBytes??Wn,scope:{kind:d,...a?.projectionMode?{projectionMode:a.projectionMode}:{},commandId:a?.commandId??null,stateProjectionPolicy:a?.stateProjectionPolicy??null},includedStories:a?.includedStoryCount??r,omittedStories:a?.omittedStoryCount??0,includedEpics:a?.includedEpicCount??o,omittedEpics:a?.omittedEpicCount??0,graphRetrieval:Pc(e.stateSnapshot),reasonCodes:Tc(i,a?.reasonCodes),publicSafe:!0}}function kc(e){const t=g(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function Oc(e){return g(e)?{stableId:Q(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function _i(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Nc(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const i=kc(t);let n=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],r=t;for(;Buffer.byteLength(JSON.stringify(r),"utf8")>i&&n.length>0;){const o=n.pop();a=[...a,Oc(o)].slice(-32),r={...t,items:n,skipped:a,warnings:_i(t.warnings)}}return Buffer.byteLength(JSON.stringify(r),"utf8")>i&&(r={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:_i(t.warnings)}),r===t?e:{...e,graphRetrieval:r}}function rr(e,t={}){const i=t.limitBytes??Jr,n=t.warningThresholdBytes??Math.floor(i*Kr),a=Wt(e);if(a<i)return{body:e,degraded:!1,telemetry:nr(e,a,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:n})};let r={...e,stateSnapshot:ma(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],d=Wt(r);d>=i&&(r={...r,stateSnapshot:Nc(r.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],d=Wt(r));const s=nr(r,d,o,{limitBytes:i,warningThresholdBytes:n});if(d>=i){const l=r.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new Jn(s):new zn(s)}return{body:r,degraded:!0,telemetry:s}}function Ri(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Lc(e){const t=Wt(e);if(t<Wn)return t;const i=nr(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Ri(e)} scope=${i.scope.kind} mode=${i.scope.projectionMode??i.scope.kind} payloadBytes=${i.payloadBytes} limit=${i.limitBytes} includedStories=${i.includedStories} omittedStories=${i.omittedStories} includedEpics=${i.includedEpics} omittedEpics=${i.omittedEpics} graphRetrieval.accepted=${i.graphRetrieval.accepted} graphRetrieval.itemCount=${i.graphRetrieval.itemCount} reasonCodes=${i.reasonCodes.join(",")||"none"}
13
+ `),t}function wi(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Ri(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 Dc(e){const t=Ra(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Mc(t),metadata:Ai(t)};const i=e.bootstrapper??Aa;let n;try{n=await i({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{n={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[wa.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=Ai(t,n);if(n.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:a};const r=a.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...a,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${r}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:a,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${r}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Mc(e){return!e.reasonCodes.includes(_a.SKIPPED_NON_CONTINUITY_COMMAND)}function Ai(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:Be([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Be(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function Rn(e,t,i){const n=Math.floor(e??t);return Number.isFinite(n)?Math.max(1,Math.min(i,n)):t}function wn(e,t){const i=process.env[e];if(!i)return t;const n=Number(i);return Number.isFinite(n)?n:t}function F(e,t=ni){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",n=Je(i,t),a=Wo.test(n)?Ct:n;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function ir(e,t=ni){if(!(typeof e!="string"||e.trim().length===0))return F(e,t)}function ar(e,t,i,n){const a=ir(e?.targetId??t,120),r=e?.selectorKind??(a?cr(a):void 0),o=(e?.relatedJobIds??[]).map(d=>ir(d,120)).filter(d=>!!d);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...r?{targetKind:r}:{},...a?{targetId:a}:{},...t?{targetJobId:F(t,120)}:{},...e?.jobId?{jobId:F(e.jobId,120)}:{},...e?.goalId?{goalId:F(e.goalId,120)}:{},...e?.loopId?{loopId:F(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:Be(n.length>0?n:[G.OK]),publicSafe:!0}}function ut(e,t,i,n,a=[]){const r=(e?.redactions?.length??0)>0,o=e?r?"unsafe":i&&n===0?"empty":"available":"unavailable",d=ir(t[t.length-1]?.eventId,120),s=a.length>0?a:o==="unavailable"?[G.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[G.WATCH_NO_SUMMARIES_YET]:[G.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:F(e.generatedAt,80)}:{},renderedSummaryCount:n,...d?{latestEventId:d}:{},reasonCodes:Be(s),publicSafe:!0}}function et(e,t,i,n,a=[],r){const o=n[n.length-1],d=i??o?.cursor,s=!!(d&&d!==t&&n.length>0),l=r??(s?"advanced":t||d?"unchanged":"not_started"),y=a.length>0?a:l==="advanced"?[G.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[G.WATCH_EVIDENCE_UNAVAILABLE]:[G.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:F(e,200)}:{},...t?{currentCursor:F(t,200)}:{},...d?{nextCursor:F(d,200)}:{},cursorAdvanced:s,...o?.eventId?{eventId:F(o.eventId,120)}:{},reasonCodes:Be(y),publicSafe:!0}}function tt(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:Be([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:F(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function jc(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,n=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",r=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",d=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===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=${n}`,`summaries=${i}`,`snapshot=${d}`,`generatedAt=${s}`,`cursor=${a}`,`current=${F(r,200)}`,`next=${F(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function nt(e,t,i,n=!1){if(n){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};i.write(t==="json"?`${JSON.stringify(a)}
15
15
  `:`[watch-status] status=${a.watchStatus} active=${a.active} summaries=${a.renderedSummaryCount} stop=${a.stopReason}
16
16
  `);return}if(t==="json"){i.write(JSON.stringify(e)+`
17
- `);return}i.write(Ac(e)+`
18
- `)}function bc(e,t,i){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:i,statusRecord:e,publicSafe:!0}}}function pt(e,t,i,r,a=!1){return a?{status:e,summariesEmitted:t,polls:i,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:i,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:i,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:bc(r,t,i),publicSafe:!0}}function xc(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",i=e.goalId?` goal=${q(e.goalId,100)}`:"",r=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${i}${r} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function Tc(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 Pc(e,t,i,r=!1){if(r){i.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}i.write(jc(e)+`
18
+ `)}function Vc(e,t,i){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:i,statusRecord:e,publicSafe:!0}}}function ht(e,t,i,n,a=!1){return a?{status:e,summariesEmitted:t,polls:i,reasonCodes:[],watchStatus:n.watchStatus,stopReason:n.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:n.watchStatus,stopReason:n.stopReason??"not_stopped",summariesEmitted:t,polls:i,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:i,reasonCodes:n.reasonCodes,watchStatus:n.watchStatus,stopReason:n.stopReason,targetEvidence:n.targetEvidence,snapshotEvidence:n.snapshotEvidence,cursorEvidence:n.cursorEvidence,statusRecord:n,metadata:Vc(n,t,i),publicSafe:!0}}function Bc(e){const t=e.reasonCode?` reason=${F(e.reasonCode,80)}`:"",i=e.goalId?` goal=${F(e.goalId,100)}`:"",n=e.loopId?` loop=${F(e.loopId,100)}`:"";return`[watch] ${F(e.createdAt,80)} event=${F(e.eventId,120)} job=${F(e.jobId,100)}${i}${n} execution=${F(e.executionId,120)}${t} -- ${F(e.publicSummary)}`}function Uc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:F(e.eventId,120),jobId:F(e.jobId,100),...e.goalId?{goalId:F(e.goalId,100)}:{},...e.loopId?{loopId:F(e.loopId,100)}:{},executionId:F(e.executionId,120),...e.reasonCode?{reasonCode:F(e.reasonCode,80)}:{},createdAt:F(e.createdAt,80),publicSummary:F(e.publicSummary),publicSafe:!0}}function $c(e,t,i,n=!1){if(n){i.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"){i.write(JSON.stringify(Tc(e))+`
21
- `);return}i.write(xc(e)+`
22
- `)}function ir(e){return No.has(e.status)}function kc(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&ir(a))}return i<=0?!1:e.filter(a=>!ir(a)).length===0}function Oc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!ir(a)):e.length===0}function Nc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(a,e);function a(){clearTimeout(r),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Lc(e){return e.includes(ke.MALFORMED)?"malformed":e.includes(ke.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(ke.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function wi(e,t){const i=t?Zt(t):void 0,r=Me([...e,_e.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),a=rr(i,i?.targetId,Lc(r),r),n=dt({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Xe(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return Ze({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Dc(e,t,i,r,a=!1){const n=wi(e,bi(t));return et(n,i,r,a),pt("target-unresolved",0,0,n,a)}async function Mc(e){if(e.signal?.aborted){const P=rr(e.target??Zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=dt(void 0,[],!1,0),w=Xe(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),M=Ze({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return pt("cancelled",0,0,M,e.protectedOutput)}const t=e.target??Zt(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const P=wi([ke.MISSING,_e.TARGET_UNRESOLVED]);return et(P,e.format,r,e.protectedOutput),pt("target-unresolved",0,0,P,e.protectedOutput)}const a=_n(e.limit??Rn("NEOCORTEX_INVOKE_WATCH_LIMIT",kr),kr,50),n=Math.max(50,_n(e.pollIntervalMs??Rn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Lr),Lr,6e4)),o=_n(e.maxIdlePolls??Rn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Or),Or,120),d=_n(e.maxPolls??Rn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Nr),Nr,86400),s=e.sleep??Nc;let l=e.initialCursor,y=0,S=0,u=0;const C=rr(t,i,"resolved",[F.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},h=Xe(e.initialCursor,l,l,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");et(Ze({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:E,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,r,e.protectedOutput);let I;try{I=await wa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=dt(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),_=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=Ze({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(w,e.format,r,e.protectedOutput),pt("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const P=l,_=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=w.jobs;if(_.summaries.length>0){for(const Z of _.summaries)Pc(Z,e.format,r,e.protectedOutput),y+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const N=dt(w,_.summaries,!0,_.summaries.length),z=Xe(e.initialCursor,P,l,_.summaries,_.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(et(Ze({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:N,cursorEvidence:z,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!_.hasMore&&kc(M,i,y)){const Z=dt(w,_.summaries,!1,y,[_e.COMPLETED]),j=Xe(e.initialCursor,P,l,_.summaries,[_e.COMPLETED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:Z,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("completed",y,u,V,e.protectedOutput)}if(!_.hasMore&&Oc(M,i,S,o)){const Z=dt(w,_.summaries,!1,y,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),j=Xe(e.initialCursor,P,l,_.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:Z,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("idle-timeout",y,u,V,e.protectedOutput)}_.hasMore||await s(n,e.signal)}}catch{const P=dt(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),_=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=Ze({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(w,e.format,r,e.protectedOutput),pt("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const P=dt(void 0,[],!1,y,[_e.CANCELLED]),_=Xe(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return et(w,e.format,r,e.protectedOutput),pt("cancelled",y,u,w,e.protectedOutput)}const b=dt(void 0,[],!1,y,[F.WATCH_STOP_MAX_POLLS_REACHED]),L=Xe(e.initialCursor,l,l,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:L,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return et(T,e.format,r,e.protectedOutput),pt("max-polls",y,u,T,e.protectedOutput)}function Je(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function ar(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Ai(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const a=Je(r[1]);a&&t.push(a)}return Me(t)}function bi(e){return Ai(e)[0]}function Zt(e){const t=e?Je(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function or(e){return Me(e.filter(t=>typeof t=="string").map(t=>Je(t)).filter(t=>!!t?.startsWith("job-J")))}function jc(e,t){const i=or(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Vc(e){if(!e)return;const t=g(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Je(e.targetId):typeof t?.targetId=="string"?Je(t.targetId):typeof e.targetJobId=="string"?Je(e.targetJobId):void 0,a=Zt(r);if(!a||i&&i!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=or([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==a.targetId&&d!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Je(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Je(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Je(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function xi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const xe=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"}),Bc=new Set(["create","start","resume"]),Uc=new Set(["create","resume","run-once"]);function cr(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Me(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Ne(e,t=[],i,r){const a=t.length>0?t:[xe.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:cr(!1,a,i,r),publicSafe:!0}}function $c(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Ne(e,[],"jobs","watch");if(i!==1)return Ne(e,[xe.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return xi(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Ne(e,[xe.AMBIGUOUS],"jobs","watch"):bi(r)?{args:r,watch:!0,reasonCodes:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],"jobs","watch"),publicSafe:!0}:Ne(e,[xe.TARGET_INVALID],"jobs","watch"):Ne(e,[xe.UNSUPPORTED],"jobs","watch")}function Hc(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const a=r;let n="",o=!1,d=null;for(;r<e.length;){const s=e[r];if(d){if(s===d){o=!0,d=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,d=s,r+=1;continue}n+=s,r+=1}d&&(i=!0),t.push({value:n,start:a,end:r,quoted:o})}return{tokens:t,malformed:i}}function Wc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Gc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Bc:Uc).has(i)?i:void 0}function Yc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Fc(e){const{tokens:t,malformed:i}=Hc(e),r=Wc(t[0]),a=Gc(r,t[1]);if(i)return Ne(e,[xe.MALFORMED],r,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(Yc);if(!(n.length>0||o.length>0||d.length>0))return Ne(e,[],r,a);if(n.length>1)return Ne(e,[xe.DUPLICATE],r,a);if(n.length===1&&(o.length>0||d.length>0))return Ne(e,[xe.AMBIGUOUS],r,a);if(o.length>0)return Ne(e,[xe.QUOTED],r,a);if(d.length>0)return Ne(e,[xe.MALFORMED],r,a);const l=n[0];if(!l)return Ne(e,[],r,a);if(t[t.length-1]!==l)return Ne(e,[xe.NON_FINAL],r,a);if(!r||!a)return Ne(e,[xe.UNRESOLVED],r,a);const y=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],r,a,S),publicSafe:!0}}function qc(e){return xi(e)?$c(e):Fc(e)}function zc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Lo.has(t)):[]}function Wt(e){return{disabled:!0,reasonCodes:Me(e.length>0?e:[ke.MISSING])}}function sr(e,t,i=[],r){const a=Zt(t);if(a)return{source:e,target:jc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Jc(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(r);if(!a){t.set(r,i);continue}const n=Me([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function vt(e,t,i,r){return{source:e,hasEvidence:t,candidates:Jc(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Me(r)}:{}}}function Kc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function en(e,t){const i=Me(e.filter(r=>typeof r=="string").map(r=>Je(r)).filter(r=>!!r));if(t){const r=i.find(a=>ar(a)===t);if(r)return r}return i[0]}function wn(e,t){return Me(e.filter(i=>typeof i=="string").map(i=>Je(i)).filter(i=>!!i)).find(i=>ar(i)===t)}function Qc(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.jobs)?t.jobs:void 0,r=g(i?.watcher)?i.watcher:void 0,a=zc(r?.reasonCodes??i?.reasonCodes);if(!r)return vt("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return vt("watcher-metadata",!0,[],a.length>0?a:[ke.MALFORMED]);if(r.serverHeldStream!==!1)return vt("watcher-metadata",!0,[],[ke.SERVER_HELD_STREAM]);const n=Vc(r);if(!n)return vt("watcher-metadata",!0,[],[ke.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return vt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Ti(e,t){const i=g(e.loopJobPlan)?e.loopJobPlan:void 0,r=g(i?.metadata)?i.metadata:void 0,a=g(e.metadata)?e.metadata:void 0,o=(t==="goal"?en([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):en([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,r?.loopId,r?.jobId],"loop"))??en([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return sr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function Xc(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.goal)?t.goal:void 0,r=g(t?.loop)?t.loop:void 0,a=[i?Ti(i,"goal"):void 0,r?Ti(r,"loop"):void 0],n=!!(i||r);return vt("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[ke.MISSING]:void 0)}function Zc(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Pi(e,t){const i=g(t.metadata)?t.metadata:void 0,r=wn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=wn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=en([t.jobId,t.targetJobId,i?.jobId],"job"),o=r??a??n;if(!o)return;const d=e.get(o)??{targetId:o,relatedJobIds:[]};d.relatedJobIds.push(...or([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function es(e){const t=g(e.metadata)?e.metadata:void 0;return!!(wn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??wn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ts(e){const t=g(e.metadata)?e.metadata:void 0;return!!en([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function ki(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[o];g(d)&&i.push(d)}const r=g(t.event)?t.event:void 0;g(r?.metadata)&&i.push(r.metadata),g(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const a=g(t.receipt)?t.receipt:void 0;g(a?.metadata)&&i.push(a.metadata);const n=i.some(ts);for(const o of i)Pi(e,o);(!n||es(t))&&Pi(e,t)}function ns(e){const t=Zc(e?.continuityStateUpdate),i=new Map;for(const a of t){ki(i,a);const n=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of n)ki(i,o)}const r=Array.from(i.values()).map(a=>sr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return vt("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[ke.MISSING]:void 0)}function rs(e){const t=Ai(e);return vt("explicit-args",t.length>0,t.map(i=>sr("explicit-args",i)))}function is(e,t){const i=[Qc(e),Xc(e),ns(e),rs(t)];for(let r=0;r<i.length;r+=1){const a=i[r];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Wt(a.disabledReasonCodes);if(a.candidates.length!==1)return Wt([a.candidates.length>1?ke.AMBIGUOUS:ke.MISSING]);const n=a.candidates[0];for(const o of i.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Wt(o.disabledReasonCodes);if(o.candidates.length>1)return Wt([ke.AMBIGUOUS]);const d=o.candidates[0];if(d&&!Kc(n,d))return Wt([ke.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Wt([ke.MISSING])}async function dr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const d=await Xt(e,a,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const C=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!za(C))throw new Error("header-shape");if(n=C,C.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=o==="malformed"?Ut.RESULT_MALFORMED:n?.reasonCodes[0]??Ut.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=d;let y=d.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${Ut.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=qa({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:Ut.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{y=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const S=y,u=s.headers.get("X-Client-Version-Warning");return u&&!yi&&(yi=!0,process.stderr.write(`
20
+ `);return}if(t==="json"){i.write(JSON.stringify(Uc(e))+`
21
+ `);return}i.write(Bc(e)+`
22
+ `)}function or(e){return $o.has(e.status)}function Hc(e,t,i){if(t){const a=e.find(r=>r.jobId===t);return!!(a&&or(a))}return i<=0?!1:e.filter(a=>!or(a)).length===0}function Wc(e,t,i,n){return i<n?!1:t?!e.some(a=>a.jobId===t&&!or(a)):e.length===0}function Gc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const n=setTimeout(a,e);function a(){clearTimeout(n),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Fc(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function bi(e,t){const i=t?en(t):void 0,n=Be([...e,_e.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),a=ar(i,i?.targetId,Fc(n),n),r=ut({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),o=et(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:r,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:n,generatedAt:r.generatedAt})}function Yc(e,t,i,n,a=!1){const r=bi(e,Ti(t));return nt(r,i,n,a),ht("target-unresolved",0,0,r,a)}async function qc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),L=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return ht("cancelled",0,0,L,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const k=bi([Le.MISSING,_e.TARGET_UNRESOLVED]);return nt(k,e.format,n,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const a=Rn(e.limit??wn("NEOCORTEX_INVOKE_WATCH_LIMIT",Nr),Nr,50),r=Math.max(50,Rn(e.pollIntervalMs??wn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Mr),Mr,6e4)),o=Rn(e.maxIdlePolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Lr),Lr,120),d=Rn(e.maxPolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Dr),Dr,86400),s=e.sleep??Gc;let l=e.initialCursor,y=0,S=0,u=0;const C=ar(t,i,"resolved",[G.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},h=et(e.initialCursor,l,l,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:E,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,n,e.protectedOutput);let I;try{I=await xa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,n,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,_=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),L=w.jobs;if(_.summaries.length>0){for(const X of _.summaries)$c(X,e.format,n,e.protectedOutput),y+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const D=ut(w,_.summaries,!0,_.summaries.length),Y=et(e.initialCursor,k,l,_.summaries,_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:D,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,n,e.protectedOutput),!_.hasMore&&Hc(L,i,y)){const X=ut(w,_.summaries,!1,y,[_e.COMPLETED]),pe=et(e.initialCursor,k,l,_.summaries,[_e.COMPLETED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("completed",y,u,x,e.protectedOutput)}if(!_.hasMore&&Wc(L,i,S,o)){const X=ut(w,_.summaries,!1,y,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,_.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("idle-timeout",y,u,x,e.protectedOutput)}_.hasMore||await s(r,e.signal)}}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,n,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,y,[_e.CANCELLED]),_=et(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return nt(w,e.format,n,e.protectedOutput),ht("cancelled",y,u,w,e.protectedOutput)}const b=ut(void 0,[],!1,y,[G.WATCH_STOP_MAX_POLLS_REACHED]),M=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:M,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,n,e.protectedOutput),ht("max-polls",y,u,P,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(i==="job"&&n!=="J"||i==="goal"&&n!=="G"||i==="loop"&&n!=="L"))return`${i}-${n}${t[3]}`}function cr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function xi(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=i.exec(e))!==null;){const a=Ke(n[1]);a&&t.push(a)}return Be(t)}function Ti(e){return xi(e)[0]}function en(e){const t=e?Ke(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 sr(e){return Be(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function zc(e,t){const i=sr(t).filter(n=>n!==e.targetId&&n!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Jc(e){if(!e)return;const t=g(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,a=en(n);if(!a||i&&i!==a.selectorKind)return;const r=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=sr([...r??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==a.targetId&&d!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function Pi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&n==="watch"}const be=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"}),Kc=new Set(["create","start","resume"]),Qc=new Set(["create","resume","run-once"]);function dr(e,t,i,n,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...n?{operation:n}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Be(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],i,n){const a=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:dr(!1,a,i,n),publicSafe:!0}}function Xc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(r=>r==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const n=t.filter((r,o)=>o<2||r!=="--watch").join(" ");return Pi(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Ti(n)?{args:n,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function Zc(e){const t=[];let i=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const a=n;let r="",o=!1,d=null;for(;n<e.length;){const s=e[n];if(d){if(s===d){o=!0,d=null,n+=1;continue}if(s==="\\"&&n+1<e.length){r+=e[n+1],n+=2;continue}r+=s,n+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,d=s,n+=1;continue}r+=s,n+=1}d&&(i=!0),t.push({value:r,start:a,end:n,quoted:o})}return{tokens:t,malformed:i}}function es(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ts(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Kc:Qc).has(i)?i:void 0}function ns(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function rs(e){const{tokens:t,malformed:i}=Zc(e),n=es(t[0]),a=ts(n,t[1]);if(i)return Me(e,[be.MALFORMED],n,a);const r=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(ns);if(!(r.length>0||o.length>0||d.length>0))return Me(e,[],n,a);if(r.length>1)return Me(e,[be.DUPLICATE],n,a);if(r.length===1&&(o.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],n,a);if(o.length>0)return Me(e,[be.QUOTED],n,a);if(d.length>0)return Me(e,[be.MALFORMED],n,a);const l=r[0];if(!l)return Me(e,[],n,a);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],n,a);if(!n||!a)return Me(e,[be.UNRESOLVED],n,a);const y=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],n,a,S),publicSafe:!0}}function is(e){return Pi(e)?Xc(e):rs(e)}function as(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Ho.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Be(e.length>0?e:[Le.MISSING])}}function pr(e,t,i=[],n){const a=en(t);if(a)return{source:e,target:zc(a,i),targetJobId:a.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function os(e){const t=new Map;for(const i of e){const n=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(n);if(!a){t.set(n,i);continue}const r=Be([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(n,{...a,target:r.length>0?{...a.target,relatedJobIds:r}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function Rt(e,t,i,n){return{source:e,hasEvidence:t,candidates:os(i.filter(a=>!!a)),...n&&n.length>0?{disabledReasonCodes:Be(n)}:{}}}function cs(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Be(e.filter(n=>typeof n=="string").map(n=>Ke(n)).filter(n=>!!n));if(t){const n=i.find(a=>cr(a)===t);if(n)return n}return i[0]}function An(e,t){return Be(e.filter(i=>typeof i=="string").map(i=>Ke(i)).filter(i=>!!i)).find(i=>cr(i)===t)}function ss(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.jobs)?t.jobs:void 0,n=g(i?.watcher)?i.watcher:void 0,a=as(n?.reasonCodes??i?.reasonCodes);if(!n)return Rt("watcher-metadata",a.length>0,[],a);if(n.active===!1||a.length>0)return Rt("watcher-metadata",!0,[],a.length>0?a:[Le.MALFORMED]);if(n.serverHeldStream!==!1)return Rt("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const r=Jc(n);if(!r)return Rt("watcher-metadata",!0,[],[Le.MISSING]);const o=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Rt("watcher-metadata",!0,[{source:"watcher-metadata",target:r,targetJobId:r.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ki(e,t){const i=g(e.loopJobPlan)?e.loopJobPlan:void 0,n=g(i?.metadata)?i.metadata:void 0,a=g(e.metadata)?e.metadata:void 0,o=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,n?.loopId,n?.jobId],"loop"))??tn([e.jobId,e.targetJobId,a?.jobId,n?.jobId]);return pr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,n?.jobId])}function ds(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.goal)?t.goal:void 0,n=g(t?.loop)?t.loop:void 0,a=[i?ki(i,"goal"):void 0,n?ki(n,"loop"):void 0],r=!!(i||n);return Rt("goal-loop-continuity-metadata",r,a,r&&a.every(o=>!o)?[Le.MISSING]:void 0)}function ps(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Oi(e,t){const i=g(t.metadata)?t.metadata:void 0,n=An([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=An([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),r=tn([t.jobId,t.targetJobId,i?.jobId],"job"),o=n??a??r;if(!o)return;const d=e.get(o)??{targetId:o,relatedJobIds:[]};d.relatedJobIds.push(...sr([r,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function ls(e){const t=g(e.metadata)?e.metadata:void 0;return!!(An([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??An([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function us(e){const t=g(e.metadata)?e.metadata:void 0;return!!tn([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Ni(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[o];g(d)&&i.push(d)}const n=g(t.event)?t.event:void 0;g(n?.metadata)&&i.push(n.metadata),g(n?.processingOutputSummary)&&i.push(n.processingOutputSummary);const a=g(t.receipt)?t.receipt:void 0;g(a?.metadata)&&i.push(a.metadata);const r=i.some(us);for(const o of i)Oi(e,o);(!r||ls(t))&&Oi(e,t)}function hs(e){const t=ps(e?.continuityStateUpdate),i=new Map;for(const a of t){Ni(i,a);const r=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of r)Ni(i,o)}const n=Array.from(i.values()).map(a=>pr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return Rt("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(a=>!a)?[Le.MISSING]:void 0)}function gs(e){const t=xi(e);return Rt("explicit-args",t.length>0,t.map(i=>pr("explicit-args",i)))}function fs(e,t){const i=[ss(e),ds(e),hs(e),gs(t)];for(let n=0;n<i.length;n+=1){const a=i[n];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const r=a.candidates[0];for(const o of i.slice(n+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=o.candidates[0];if(d&&!cs(r,d))return Gt([Le.CONFLICT])}return{target:r.target,targetJobId:r.targetJobId,...r.initialCursor?{initialCursor:r.initialCursor}:{},source:r.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function lr(e,t,i,n={}){const a="/api/v1/invoke";let r,o;const d=await Zt(e,a,t,i,{...n,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const C=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Qa(C))throw new Error("header-shape");if(r=C,C.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return n.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=o==="malformed"?$t.RESULT_MALFORMED:r?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:r?.remediationHint??"upgrade-client"},...r?{compatibility:r}:{}}}const{response:s,text:l}=d;let y=d.parsed;try{if(t.compatibility&&!r){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};r=Ka({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{y=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...r?{compatibility:r}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(y).length>0?y:void 0,...r?{compatibility:r}:{}};const S=y,u=s.headers.get("X-Client-Version-Warning");return u&&!Ei&&(Ei=!0,process.stderr.write(`
23
23
  [Neocortex] ${u}
24
24
 
25
- `)),{ok:!0,status:s.status,data:S,...n?{compatibility:n}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${Yr/1e3}s`:"Network error: invalid response"}}}async function as(e,t,i){const r=await Xt(e,"/api/v1/invoke/private-execution/consume",t,i,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function os(e,t,i){const r=await Xt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function Oi(e,t,i,r={}){const a=await Xt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:ot,registryChecksum:at},t,r);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||a.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function cs(e,t,i,r,a,n={}){if(!a)return 0;const o=$t(e);let d=0;for(const[s,l]of Object.entries(o.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await Oi(i,r,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},n)||(bo(e,s),d+=1);return d}function ss(e,t){const i=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||i?.length!==1||!r)return;const a=i[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const d=typeof r.epicId=="string"?r.epicId:"",s=e.epics[d],l=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],y=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[y]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const E=(Array.isArray(s.stories)?s.stories.filter(h=>typeof h=="string"):[]).find(h=>{const I=e.stories[h];return!I||["done","completed","merged"].includes(String(I.status))?!1:(Array.isArray(I.depends_on)?I.depends_on.filter(L=>typeof L=="string"):[]).every(L=>["done","completed","merged"].includes(String(e.stories[L]?.status)))});if(E)return{epicId:d,expectedNextStoryId:E,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.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"}}}const pr=["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"],Ni=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Li=new Set(["skipped-with-debt","documented"]);function Di(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function ds(e){const t=Di(e);if(Ni.has(t)||Li.has(t))return 0;const i=pr.indexOf(t);return i<0?pr.length:pr.length-1-i}function ps(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(y=>typeof y!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(y)))return null;const r=[...i.stories],a=[],n=[];let o=0,d=0;const s=[];for(const y of r){const S=e.stories[y];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(h=>typeof h!="string"))return null;const u=[...S.depends_on].sort(),C=ds(S.status),E=Di(S.status);a.push({id:y,dependsOn:u}),n.push({id:y,status:S.status,dependsOn:u}),s.push({storyId:y,remaining:C}),o+=C,!Ni.has(E)&&!Li.has(E)&&(d+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:It("p205-yoloop-graph-v1",a),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:It("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:n}),initialRank:{version:1,queue:0,epic:d,lifecycle:o},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:It("p205-yoloop-session-v1",l)})}function Mi(e){const t=e instanceof Error?e.message:"";return/^[a-z0-9][a-z0-9-]{0,79}$/.test(t)?t:"yoloop-causal-reconciliation-unavailable"}async function ls(e){try{if(!/^P[1-9][0-9]*$/.test(e.targetEpicId)||!/^[a-f0-9]{64}$/.test(e.originalInputSha256)||!/^[a-f0-9]{64}$/.test(e.canonicalInputSha256))throw new Error("yoloop-causal-reconciliation-binding-invalid");const t=ps(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=_r(e.projectRoot),a=Object.values(r.operational.identities).filter(M=>M.epicId===e.targetEpicId&&M.graphRevision===i);if(a.length!==1)throw new Error("epic-operational-identity-mismatch");const n=e.snapshot.yoloop,o=n?n.lock!==null||n.state.currentSession!==null?"active":"inactive":"unknown",d=oa({document:r.document,targetIdentityHash:a[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:o});if(d.kind!=="eligible")throw new Error(d.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=r.operational,l=s.yoloop.state.continuationSession,y=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||y.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=It("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),C=It("p224-common-pending-authorities-v1",y),E=It("p224-common-continuation-session-v1",t),h=It("p224-invoke-session-recovery-v1",{identityHash:a[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:C,nextSessionHash:E,runId:S.runId,runRevision:S.revision}),I={operationId:`p224rec-${h.slice(0,32)}`,idempotencyKey:`p224rec-${h.slice(0,32)}`,expectedCommonRevision:r.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:a[0].identityHash,sourceEpicId:d.evidence.sourceEpicId,sourceGraphRevision:d.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:C,expectedPendingCount:y.length,nextSession:t,nextSessionHash:E},b=aa(I),L={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:I.operationId,idempotencyKey:I.idempotencyKey,payloadHash:b,sourceEpicId:I.sourceEpicId,sourceGraphRevision:I.sourceGraphRevision,targetEpicId:I.targetEpicId,targetGraphRevision:I.targetGraphRevision,runId:I.expectedRunId,previousSessionHash:u,nextSessionHash:E,retiredAuthorityHash:C,retiredAuthorityCount:I.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},T={type:"reconcile_cross_epic_continuation",...I,payloadHash:b,receipt:L};await ia(e.projectRoot,T);const P=_r(e.projectRoot),_=P.operational.yoloop.state.pendingContinuationAuthorities??[];if(!P.operational.reconciliationReceipts.find(M=>M.payloadHash===b)||_.length!==0||It("p224-common-continuation-session-v1",P.operational.yoloop.state.continuationSession??null)!==E)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:b,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Mi(t),retryCount:0,publicSafe:!0})}}const us=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,ji=9e4,Vi=6,hs=1e3;function gs(e){return typeof e=="string"&&us.test(e)&&!e.includes("..")}function fs(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const i=t;return i.decision==="spec-barrier-waiting"&&i.phase==="phase-1"?i:void 0}async function ms(e,t,i={}){const r=i.sleep??(l=>new Promise(y=>setTimeout(y,l))),a=i.now??Date.now,n=Math.max(1,Math.min(i.maxAttempts??Vi,Vi)),o=Math.max(0,Math.min(i.maxWaitMs??ji,ji)),d=a();let s=0;for(;;){const l=await t(e);s+=1;const y=fs(l);if(!y)return l;const S=typeof y.maxWaitMs=="number"&&Number.isFinite(y.maxWaitMs)?y.maxWaitMs:0,u=Math.min(o,Math.max(0,S)),C=typeof y.retryAfterMs=="number"&&Number.isFinite(y.retryAfterMs)?y.retryAfterMs:0,E=Math.min(Math.max(C,hs),u),h=a()-d;if(s>=n||h+E>u)return{success:!0,instructions:`# Story-worktree spec barrier timeout
25
+ `)),{ok:!0,status:s.status,data:S,...r?{compatibility:r}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${qr/1e3}s`:"Network error: invalid response"}}}async function ms(e,t,i){const n=await Zt(e,"/api/v1/invoke/private-execution/consume",t,i,{maxAttempts:1,allowReplayRetry:!1});if(n.networkFailure||!n.response||!n.response.ok)throw new Error("private-execution-delivery-unavailable");return n.parsed}async function ys(e,t,i){const n=await Zt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function Li(e,t,i,n={}){const a=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:dt,registryChecksum:st},t,n);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||a.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function Is(e,t,i,n,a,r={}){if(!a)return 0;const o=Ht(e);let d=0;for(const[s,l]of Object.entries(o.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await Li(i,n,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},r)||(Do(e,s),d+=1);return d}function Es(e,t){const i=t.state.pendingContinuationAuthorities,n=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||i?.length!==1||!n)return;const a=i[0],r=a.certificate,o=r?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||r?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const d=typeof n.epicId=="string"?n.epicId:"",s=e.epics[d],l=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],y=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[y]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const E=(Array.isArray(s.stories)?s.stories.filter(h=>typeof h=="string"):[]).find(h=>{const I=e.stories[h];return!I||["done","completed","merged"].includes(String(I.status))?!1:(Array.isArray(I.depends_on)?I.depends_on.filter(M=>typeof M=="string"):[]).every(M=>["done","completed","merged"].includes(String(e.stories[M]?.status)))});if(E)return{epicId:d,expectedNextStoryId:E,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.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"}}}const ur=["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"],Di=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Mi=new Set(["skipped-with-debt","documented"]);function ji(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function Ss(e){const t=ji(e);if(Di.has(t)||Mi.has(t))return 0;const i=ur.indexOf(t);return i<0?ur.length:ur.length-1-i}function vs(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(y=>typeof y!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(y)))return null;const n=[...i.stories],a=[],r=[];let o=0,d=0;const s=[];for(const y of n){const S=e.stories[y];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(h=>typeof h!="string"))return null;const u=[...S.depends_on].sort(),C=Ss(S.status),E=ji(S.status);a.push({id:y,dependsOn:u}),r.push({id:y,status:S.status,dependsOn:u}),s.push({storyId:y,remaining:C}),o+=C,!Di.has(E)&&!Mi.has(E)&&(d+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:n,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:vt("p205-yoloop-graph-v1",a),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:vt("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:r}),initialRank:{version:1,queue:0,epic:d,lifecycle:o},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:vt("p205-yoloop-session-v1",l)})}function Vi(e){const t=e instanceof Error?e.message:"";return/^[a-z0-9][a-z0-9-]{0,79}$/.test(t)?t:"yoloop-causal-reconciliation-unavailable"}async function Cs(e){try{if(!/^P[1-9][0-9]*$/.test(e.targetEpicId)||!/^[a-f0-9]{64}$/.test(e.originalInputSha256)||!/^[a-f0-9]{64}$/.test(e.canonicalInputSha256))throw new Error("yoloop-causal-reconciliation-binding-invalid");const t=vs(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),n=wr(e.projectRoot),a=Object.values(n.operational.identities).filter(L=>L.epicId===e.targetEpicId&&L.graphRevision===i);if(a.length!==1)throw new Error("epic-operational-identity-mismatch");const r=e.snapshot.yoloop,o=r?r.lock!==null||r.state.currentSession!==null?"active":"inactive":"unknown",d=sa({document:n.document,targetIdentityHash:a[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:o});if(d.kind!=="eligible")throw new Error(d.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=n.operational,l=s.yoloop.state.continuationSession,y=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||y.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=vt("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),C=vt("p224-common-pending-authorities-v1",y),E=vt("p224-common-continuation-session-v1",t),h=vt("p224-invoke-session-recovery-v1",{identityHash:a[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:C,nextSessionHash:E,runId:S.runId,runRevision:S.revision}),I={operationId:`p224rec-${h.slice(0,32)}`,idempotencyKey:`p224rec-${h.slice(0,32)}`,expectedCommonRevision:n.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:a[0].identityHash,sourceEpicId:d.evidence.sourceEpicId,sourceGraphRevision:d.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:C,expectedPendingCount:y.length,nextSession:t,nextSessionHash:E},b=ca(I),M={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:I.operationId,idempotencyKey:I.idempotencyKey,payloadHash:b,sourceEpicId:I.sourceEpicId,sourceGraphRevision:I.sourceGraphRevision,targetEpicId:I.targetEpicId,targetGraphRevision:I.targetGraphRevision,runId:I.expectedRunId,previousSessionHash:u,nextSessionHash:E,retiredAuthorityHash:C,retiredAuthorityCount:I.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},P={type:"reconcile_cross_epic_continuation",...I,payloadHash:b,receipt:M};await oa(e.projectRoot,P);const k=wr(e.projectRoot),_=k.operational.yoloop.state.pendingContinuationAuthorities??[];if(!k.operational.reconciliationReceipts.find(L=>L.payloadHash===b)||_.length!==0||vt("p224-common-continuation-session-v1",k.operational.yoloop.state.continuationSession??null)!==E)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:b,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Vi(t),retryCount:0,publicSafe:!0})}}const _s=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,Bi=9e4,Ui=6,Rs=1e3;function ws(e){return typeof e=="string"&&_s.test(e)&&!e.includes("..")}function As(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const i=t;return i.decision==="spec-barrier-waiting"&&i.phase==="phase-1"?i:void 0}async function bs(e,t,i={}){const n=i.sleep??(l=>new Promise(y=>setTimeout(y,l))),a=i.now??Date.now,r=Math.max(1,Math.min(i.maxAttempts??Ui,Ui)),o=Math.max(0,Math.min(i.maxWaitMs??Bi,Bi)),d=a();let s=0;for(;;){const l=await t(e);s+=1;const y=As(l);if(!y)return l;const S=typeof y.maxWaitMs=="number"&&Number.isFinite(y.maxWaitMs)?y.maxWaitMs:0,u=Math.min(o,Math.max(0,S)),C=typeof y.retryAfterMs=="number"&&Number.isFinite(y.retryAfterMs)?y.retryAfterMs:0,E=Math.min(Math.max(C,Rs),u),h=a()-d;if(s>=r||h+E>u)return{success:!0,instructions:`# Story-worktree spec barrier timeout
26
26
 
27
27
  The C04 barrier did not open within the bounded wait. Return this resumable receipt to the root; the root re-dispatches the same phase-1 prompt, which resumes at C05. No C05 step was executed.
28
28
 
29
- [STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...y,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,h),publicSafe:!0}},exitCode:0};await r(E)}}async function ys(e,t){const i=t.metadata?.storyWorktreePhase;if(!t.success||!i||typeof i!="object"||Array.isArray(i))return;const r=i,a=r.specAcceptance,n=r.phaseOneReceipt,o=typeof r.storyId=="string"?r.storyId:void 0,d=o&&/^P[0-9]{1,12}\./.test(o)?o.split(".")[0]:void 0;if(!(!d||a===void 0&&n===void 0))try{await Ur(e,s=>{so(s,d,{...a!==void 0?{specAcceptances:[a]}:{},...n!==void 0?{receipts:[n]}:{}})})}catch(s){const l=s instanceof Error&&/^[a-z0-9-]{1,80}$/.test(s.message)?s.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${l}); the root must re-dispatch this phase-1 prompt.
30
- `)}}async function Is(e){if(!gs(e.args))return Bi(e);const t=e.projectRoot??process.cwd();return ms(e.args,async()=>{const i=await Bi(e);return await ys(t,i),i})}async function Bi(e){let t;try{if(t=e.inputEnvelope??Kt(e.inputSource??"args",e.args),Ua(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 i=t.rawArgs,r=Vn(t);let a=i,n=r,o=Zr(i),d;if(o.outcome!=="resolved"){const c=Oo(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,n=Vn(Kt(t.source,a)),d=c.binding,o=Zr(a))}if(o.outcome!=="resolved"){const c=Ha(o,"client"),p=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=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:t.source,byteLength:t.byteLength,remediation:p==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":p==="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(d&&(e={...e,args:a}),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=Wn(e.projectRoot),l=o.selection.commandId,y=l==="yolo"&&!Tr(a,l)?mo(a):null,S=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),u=da.find(c=>c.id===l),C=u?.subcommands.find(c=>c.id===o.selection.operationId),E=C?C.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",h=l==="diagnose";let I;try{I=ja({invocationId:dn(),intent:e.strictReadOnly||h?{schemaVersion:1,policy:La,registryVersion:ot,registryChecksum:at}:void 0,registryVersion:ot,registryChecksum:at,registryAllowsStrict:E,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Vt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{I.beginProjection();for(const c of Mr)I.project(c);for(const c of Da)I.project(c);I.seal()}const b=I.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=Xa(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 p=c instanceof Bn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const L=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"&&!S||b||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const T=Ta({cwd:s,env:L,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),P=T.targetId,_=e.privateExecutionBeta?void 0:xa({cwd:s,env:L,targetFlag:e.platformTarget,nativeHostVersion:$o(T,L)},T);if(y)try{Kn(s,{allowMissingRuntime:!0})}catch(c){const p=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
31
- `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=y?Mn({strictReadOnly:!0}):fi(I);const M=(e.serverUrl??w?.serverUrl??la).replace(/\/+$/,"");let N;if(y){const c=await fo(M);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${ka}; 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{N=$r({projectRoot:s,storyId:y,epicId:y.split(".")[0],inputSha256:n.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
32
- `)})}catch(p){const m=p instanceof Error&&/^yolo-spec-envelope-[a-z-]+$/.test(p.message)?p.message:"yolo-spec-envelope-unsafe";return{success:!1,error:m,errorCode:m,exitCode:1}}w=fi(I)}if(l!=="migrate-project-id"&&I.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>To(),()=>{}),l==="migrate-project-id"){const c=await Za(M);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 p=[];let m;try{m=Qa(s)}catch($){const Ee=$ instanceof Bn?$.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}p.push(Bt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const A=vn(s);if(A.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const U=await mi(M,w?.licenseKey,I);if(U.status!=="authenticated"){const $=U.status==="refresh-required";return{success:!1,error:$?"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:$?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p},exitCode:$?1:2}}let ie;try{ie=xr(e.args.trim(),A)}catch($){const Ee=$ instanceof Pr?$.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}let de={args:i,projectRoot:s.replace(Jt(),"~"),stateSnapshot:ie,platformTarget:P,..._?{nativeHostAttestation:_}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:ot,registryChecksum:at,compatibility:Yn()};try{de=tr(de).body}catch($){if($ instanceof Fn||$ instanceof qn)return{success:!1,error:$.message,errorCode:$.code,metadata:{invokePayload:$.telemetry,invocationDiagnostics:p},exitCode:1};throw $}const ae=await jn("invoke-query",()=>dr(M,de,U.token,{refreshToken:()=>U.client.forceRefresh()}));if(!ae.ok||!ae.data)return p.push(Bt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:ze(ae.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof ae.errorBody?.error_code=="string"?ae.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:ae.status===401?2:1};const fe=ae.data.metadata?.projectIdentityMigration;try{$a(fe),p.push(Bt({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ja(s,fe),p.push(Bt({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ka(s,fe),p.push(Bt({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch($){p.push(Bt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ee=$ instanceof Bn?$.code:$ instanceof Error?$.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}return I.complete(),{success:!0,instructions:ae.data.instructions,metadata:{...ae.data.metadata,...ae.compatibility?{compatibility:ae.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(e.args,{projectRoot:s});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
29
+ [STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...y,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,h),publicSafe:!0}},exitCode:0};await n(E)}}async function xs(e,t){const i=t.metadata?.storyWorktreePhase;if(!t.success||!i||typeof i!="object"||Array.isArray(i))return;const n=i,a=n.specAcceptance,r=n.phaseOneReceipt,o=typeof n.storyId=="string"?n.storyId:void 0,d=o&&/^P[0-9]{1,12}\./.test(o)?o.split(".")[0]:void 0;if(!(!d||a===void 0&&r===void 0))try{await $r(e,s=>{fo(s,d,{...a!==void 0?{specAcceptances:[a]}:{},...r!==void 0?{receipts:[r]}:{}})})}catch(s){const l=s instanceof Error&&/^[a-z0-9-]{1,80}$/.test(s.message)?s.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${l}); the root must re-dispatch this phase-1 prompt.
30
+ `)}}async function Ts(e){if(!ws(e.args))return $i(e);const t=e.projectRoot??process.cwd();return bs(e.args,async()=>{const i=await $i(e);return await xs(t,i),i})}async function $i(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),Wa(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 i=t.rawArgs,n=Un(t);let a=i,r=n,o=ti(i),d;if(o.outcome!=="resolved"){const c=Uo(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,r=Un(Qt(t.source,a)),d=c.binding,o=ti(a))}if(o.outcome!=="resolved"){const c=Fa(o,"client"),p=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=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:t.source,byteLength:t.byteLength,remediation:p==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":p==="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(d&&(e={...e,args:a}),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=Fn(e.projectRoot),l=o.selection.commandId,y=l==="yolo"&&!kr(a,l)?_o(a):null,S=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),u=la.find(c=>c.id===l),C=u?.subcommands.find(c=>c.id===o.selection.operationId),E=C?C.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",h=l==="diagnose";let I;try{I=Ua({invocationId:dn(),intent:e.strictReadOnly||h?{schemaVersion:1,policy:ja,registryVersion:dt,registryChecksum:st}:void 0,registryVersion:dt,registryChecksum:st,registryAllowsStrict:E,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{I.beginProjection();for(const c of Vr)I.project(c);for(const c of Va)I.project(c);I.seal()}const b=I.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=to(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 p=c instanceof $n?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const M=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"&&!S||b||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const P=Oa({cwd:s,env:M,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),k=P.targetId,_=e.privateExecutionBeta?void 0:ka({cwd:s,env:M,targetFlag:e.platformTarget,nativeHostVersion:Jo(P,M)},P);if(y)try{Xn(s,{allowMissingRuntime:!0})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
31
+ `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=y?Vn({strictReadOnly:!0}):yi(I);const L=(e.serverUrl??w?.serverUrl??ha).replace(/\/+$/,"");let D,Y=!1;if(y){const c=await vo(L);if(Y=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${La}; 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{D=Hr({projectRoot:s,storyId:y,epicId:y.split(".")[0],inputSha256:r.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
32
+ `)})}catch(p){const m=Gr(p);return{success:!1,error:m,errorCode:m,exitCode:1}}w=yi(I)}if(l!=="migrate-project-id"&&I.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>jo(),()=>{}),l==="migrate-project-id"){const c=await no(L);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 p=[];let m;try{m=eo(s)}catch(U){const Ie=U instanceof $n?U.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ie,errorCode:Ie,exitCode:1}}p.push(Ut({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const A=Cn(s);if(A.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const B=await Ii(L,w?.licenseKey,I);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:p},exitCode:U?1:2}}let ne;try{ne=Pr(e.args.trim(),A)}catch(U){const Ie=U instanceof Or?U.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:p},exitCode:1}}let ce={args:i,projectRoot:s.replace(Kt(),"~"),stateSnapshot:ne,platformTarget:k,..._?{nativeHostAttestation:_}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:n,idempotencyKey:m.document.operationId,registryVersion:dt,registryChecksum:st,compatibility:qn()};try{ce=rr(ce).body}catch(U){if(U instanceof zn||U instanceof Jn)return{success:!1,error:U.message,errorCode:U.code,metadata:{invokePayload:U.telemetry,invocationDiagnostics:p},exitCode:1};throw U}const re=await Bn("invoke-query",()=>lr(L,ce,B.token,{refreshToken:()=>B.client.forceRefresh()}));if(!re.ok||!re.data)return p.push(Ut({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:Je(re.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof re.errorBody?.error_code=="string"?re.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:re.status===401?2:1};const fe=re.data.metadata?.projectIdentityMigration;try{Ga(fe),p.push(Ut({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Xa(s,fe),p.push(Ut({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Za(s,fe),p.push(Ut({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch(U){p.push(Ut({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ie=U instanceof $n?U.code:U instanceof Error?U.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:p},exitCode:1}}return I.complete(),{success:!0,instructions:re.data.instructions,metadata:{...re.data.metadata,...re.compatibility?{compatibility:re.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(e.args,{projectRoot:s});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
33
33
  `),{success:!1,error:p.message,exitCode:1};p.changed&&(e={...e,args:p.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${p.reasonCodes.join(",")}
34
34
  `))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
35
- `),{success:!1,error:c,exitCode:1}}const z=ui(l);if(z)try{Kn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>ao(s),async()=>{}),Kn(s))}catch(c){const p=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
36
- `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{I.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>ma(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof ya)return process.stderr.write(`${c.message}
35
+ `),{success:!1,error:c,exitCode:1}}const X=gi(l);if(X)try{Xn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>so(s),async()=>{}),Xn(s))}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
36
+ `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{I.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ia(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof Sa)return process.stderr.write(`${c.message}
37
37
  `),{success:!1,error:c.message,exitCode:1};const p=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${p}. No request was sent; inspect .neocortex/state.json and rerun.
38
- `),{success:!1,error:p,exitCode:1}}let Z;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"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");Z=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let j;try{const c=await ac(s,e.args,l);j=vn(s,{epicAware:z,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const p=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
38
+ `),{success:!1,error:p,exitCode:1}}let pe;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"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");pe=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args))try{await(await import("../yoloop/invoke-hooks.js")).maybeCaptureYoloopStartOriginBinding(e.args,s)}catch{}let x;try{const c=await mc(s,e.args,l);x=Cn(s,{epicAware:X,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
39
39
  `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),p={args:e.args,projectRoot:s,logger:{info:m=>process.stderr.write(`${m}
40
40
  `),warn:m=>process.stderr.write(`${m}
41
- `)}};c(p),p.args!==e.args&&(e={...e,args:p.args},a=p.args,n=Vn(Kt(t.source,a)))}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${p}. Proceeding with raw args.
42
- `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const m=ss(j,p);j.yoloop=m?{...p,continuationRecoveryEvidence:m}:p}}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.
43
- `),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,I,{includeExistingStore:!h});p&&(j.continuity=p)}catch(c){if(c instanceof Vt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${p}. Proceeding without continuity state.
44
- `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:j,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:p=>{console.warn(p)},info:p=>{console.error(p)}}})}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${p}. Proceeding without enrichment.
45
- `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(s);p&&(j.architecture_policy=p)}catch(c){const p=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${p}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:p}=await import("../yoloop/invoke-hooks.js"),m=await p({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:A=>process.stderr.write(`${A}
46
- `)}});m.applied&&m.metadata&&(j.graphRetrieval=m.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
47
- `)}try{if(Vo(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(j.projectEvidence=m)}}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${p}. Proceeding without local project evidence.
48
- `)}try{const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(s)},async()=>{});c&&(j.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
49
- `)}const V=w?.licenseKey?new Dn({cacheDir:Un,passphrase:w.licenseKey,strictReadOnly:b}):null,ee=a.trim();if(!ee&&V){const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>sc(V),async()=>null);if(c)return I.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const W=await mi(M,w?.licenseKey,I);if(W.status!=="authenticated"){const c=W.status==="refresh-required",p=!c&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=br(),A=wr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);A&&process.stderr.write(Ar(A,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${p} 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 lt=j.config.project_id;try{await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>cs(s,j,M,W.token,lt,{refreshToken:()=>W.client.forceRefresh()}),async()=>0)}catch{}const Fe=Es(ee);if(Fe&&!h)try{const c=await W.tierClient.preFlightCheck(Fe);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
50
- `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const he=await Rc({args:ee,projectRoot:s,platformTarget:P,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:I});if(he.attachToRequest&&(j.runnerBootstrap=he.metadata),he.warning&&process.stderr.write(`[Neocortex] ${he.warning}
51
- `),!he.shouldContinue)return he.error&&process.stderr.write(`[Neocortex] ${he.error}
52
- `),{success:!1,error:he.error??"Runner auto-bootstrap required but failed.",errorCode:he.errorCode,exitCode:he.exitCode??1};if(he.metadata.command==="runner"&&(he.metadata.operation==="status"||he.metadata.operation==="doctor"))try{const c=e.runnerObserver??Ra;j.runnerOperationalStatus=await c(he.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:I})}catch{}let O;try{const c=fa(ee,j);if(c&&!c.ok){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
53
- `),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??xr(ee,j),un(ee)==="migrate-state"&&(O={...O,migrationAuthority:Ia(s)})}catch(c){if(c instanceof Ea)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Pr){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
54
- `),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!b)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),m=p(s);if(Mt(m.databasePath)){const A=await c(s);try{const U=A.store.listRecentNativeAgentDispatches(20);U.length>0&&(O.nativeAgentDispatches=U)}finally{A.store.close()}}}catch{}const H=un(ee);let Ct=!1;if(H==="arch-plan"&&!b&&O.archPlan?.execution===void 0){const c=qi(a);if(c)try{if(!Object.hasOwn(j.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=Yt(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},Ct=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Yt(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 De=lt;if((H==="create-epic"||H==="idea-diagnose")&&!De){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}
55
- `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let se;try{se=I.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?Ao(s,ee,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const tt=se?.key??(H==="yolo"?xo(s,ee,De,O):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&se){const c=$t(s).operations[se.fingerprint],p=c?.epicId?j.epics[c.epicId]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&j.stories[A]?.epic_id===c.epicId).map(A=>[A,j.stories[A]]))}})}const ut=b?{schemaVersion:1,invocationId:I.invocationId,intent:I.intent,clientProjection:Ma(Mr.map(c=>({...c,count:1})))}:void 0;let X,ye,le;if(e.privateExecutionBeta&&H==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ie=Ge(A),de=JSON.parse(ie.toString("utf8")),ae=Sr(de,m.claimId,c),fe=g(de)&&g(de.epics)&&g(de.epics[c])?de.epics[c]:void 0,$=g(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Ke=We("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ge(Q(s,me)).equals(Ke))throw new Error("planning-research-source-uncommitted")}ye={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ie=Ge(A),de=JSON.parse(ie.toString("utf8")),ae=vr(de,m.claimId,c),fe=g(de)&&g(de.epics)&&g(de.epics[c])?de.epics[c]:void 0,$=g(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Ke=We("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ge(Q(s,me)).equals(Ke))throw new Error("planning-generation-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,researchReceiptId:ae.researchReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:ae.physicalAcceptanceReceiptId,sourceStateSha256:Pe("sha256").update(ie).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");X=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const Nt=X?{schemaVersion:1,hostKind:"codex-cli",hostVersion:X.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:X.observedAtMs}}:void 0;let Re;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(Re=Ir(s),!Re)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let B;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(B=Ir(s),!B||!v(O.archPlan.execution.pactAnswerReceipt,B))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let je,J,ge;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(J=Fi(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!J||!v(p.pactAnswerReceipt,J.receipt))throw new Error("private-execution-pact-admission-unverified");const m=zi(s,J.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");je=m.writeSet,ge={schemaVersion:1,targetEpicId:c,graphRevision:J.receipt.graphRevision,answersSha256:J.receipt.answersSha256,specSha256:je.specSha256,pathsSha256:je.pathsSha256,endpointCount:je.endpointCount,pathCount:je.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ne;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ne={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let _t,qe,Ie;if(e.privateExecutionBeta&&H==="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:p}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");_t=m.choices,qe=m.plan,Ie=p(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ht;if(H==="yoloop"&&!b&&!e.privateExecutionBeta)try{ht=(e.hostCapacityProbe??Xi)({platformTarget:P,env:L})}catch{ht=void 0}let G={args:a,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...Re?{architectureAnswerReceipt:Re}:{},...ge?{pactExecutionInput:ge}:{},...ne?{uxExecutionInput:ne}:{},...Ie?{propertyTestExecutionInput:Ie}:{},platformTarget:P,..._?{nativeHostAttestation:_}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Yn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}};const tn=Ht(G);if(!b&&e.inputSource&&e.inputSource!=="args"&&tn>=$n)try{G={argsRef:(await Na(I,"secondary-mutation",()=>yc(M,a,W.token,()=>W.client.forceRefresh()),async()=>{throw new Vt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...Re?{architectureAnswerReceipt:Re}:{},platformTarget:P,..._?{nativeHostAttestation:_}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Yn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}}}catch(c){return c instanceof Vt?{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}}let Rt;if(H==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!N||N.storyId!==c||N.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Hr(N);if(/\sbranchless-preparation\s*$/.test(a))G={...G,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");Rt=await U({projectRoot:s,storyId:c,epicId:p}),Rt.repair==="applied"&&(m=Hr(N));const ie=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:Rt});G={...G,yoloSpecEnvelope:m,yoloChangeEvidence:ie}}}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),U=A(m),ie=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:ie,errorCode:ie,...U?{metadata:{yoloChangeEvidence:U}}:{},exitCode:1}}}try{const c=tr(G);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};G=c.body,c.degraded?_i(G,c.telemetry):_c(G)}catch(c){if(c instanceof Fn||c instanceof qn)return _i(G,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
56
- `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&G.yoloSpecEnvelope)try{const c=$r({projectRoot:s,storyId:G.yoloSpecEnvelope.storyId,epicId:G.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:G.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==G.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(G.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),m=p({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...Rt?{reconciliation:Rt}:{}});if(m.pathsSha256!==G.yoloChangeEvidence.pathsSha256||m.baseSha!==G.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:m}=await import("../yolo/change-evidence-collector.js"),A=m(c);return{success:!1,error:p,errorCode:p,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const k=H==="arch-plan"?G.stateSnapshot.archPlan?.execution:void 0;let wt;if(k?.owner==="root"&&(k.currentStageCommand==="arch-prd"||k.currentStageCommand==="arch-architecture"||k.currentStageCommand==="arch-fitness-functions"||k.currentStageCommand==="arch-api-contracts"||k.currentStageCommand==="generate-pacts"||k.currentStageCommand==="arch-api-integrations"||k.currentStageCommand==="arch-database"||k.currentStageCommand==="arch-security"||k.currentStageCommand==="arch-design-system"||k.currentStageCommand==="arch-ux-design"||k.currentStageCommand==="arch-performance"||k.currentStageCommand==="arch-testing"||k.currentStageCommand==="arch-infrastructure"||k.currentStageCommand==="arch-review"||k.currentStageCommand==="update-memory")&&(k.continuationState==="delegate"||k.continuationState==="advance"||k.currentStageCommand==="update-memory"&&k.continuationState==="complete"||k.currentStageCommand==="arch-review"&&k.continuationState==="ask-user"||k.currentStageCommand==="generate-pacts"&&k.continuationState==="ask-user"))try{const c=Ge(Q(s,".neocortex","state.json"),"utf8"),p=JSON.parse(c),m=g(p.archPlan)?p.archPlan.execution:void 0;if(Ct?m!==void 0||!g(p.epics)||!Object.hasOwn(p.epics,String(k.targetEpicId))||k.graphSource!=="committed-epic-v1"||k.graphRevision!==Yt(s,String(k.targetEpicId)):!v(In(m),k))throw new Error("architecture-root-state-binding-invalid");if(wt=Pe("sha256").update(c).digest("hex"),Re&&Re.stateSha256!==wt)throw new Error("architecture-root-state-binding-invalid");if(k.currentStageCommand==="update-memory"&&k.childStatus==="succeeded"){const A=k.continuationState==="complete"&&Array.isArray(k.acceptedStages)?{...k,continuationState:"delegate",acceptedStages:k.acceptedStages.slice(0,mr(k))}:k;if(!Gt(k.terminalMemoryCheckpoint,k)||!v(k.terminalMemoryCheckpoint,On(s,A)))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 jn("invoke-query",()=>dr(M,G,W.token,{refreshToken:()=>W.client.forceRefresh()}));if(H==="yoloop"&&!b&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=O.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await ls({projectRoot:s,snapshot:j,targetEpicId:c,originalInputSha256:n.sha256,canonicalInputSha256:d?.canonicalSha256??n.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:m}=await import("../yoloop/invoke-hooks.js"),A=await m(a,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");G=tr({...G,stateSnapshot:{...G.stateSnapshot,yoloop:A}}).body}catch(m){const A=Mi(m);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await jn("invoke-query",()=>dr(M,G,W.token,{refreshToken:()=>W.client.forceRefresh()}))}let nn;if(b&&f.ok)try{if(h){const p=f.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>p[A]!==void 0))throw new Vt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;Va(I,c),h&&Ga(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),nn=c.security}catch(c){const p=c instanceof Vt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
41
+ `)}};c(p),p.args!==e.args&&(e={...e,args:p.args},a=p.args,r=Un(Qt(t.source,a)))}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${p}. Proceeding with raw args.
42
+ `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const m=Es(x,p);x.yoloop=m?{...p,continuationRecoveryEvidence:m}:p}}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.
43
+ `),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,I,{includeExistingStore:!h});p&&(x.continuity=p)}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${p}. Proceeding without continuity state.
44
+ `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:x,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:p=>{console.warn(p)},info:p=>{console.error(p)}}})}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${p}. Proceeding without enrichment.
45
+ `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(s);p&&(x.architecture_policy=p)}catch(c){const p=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${p}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:p}=await import("../yoloop/invoke-hooks.js"),m=await p({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:A=>process.stderr.write(`${A}
46
+ `)}});m.applied&&m.metadata&&(x.graphRetrieval=m.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
47
+ `)}try{if(Yo(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(x.projectEvidence=m)}}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${p}. Proceeding without local project evidence.
48
+ `)}try{const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(s)},async()=>{});c&&(x.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
49
+ `)}const Se=w?.licenseKey?new jn({cacheDir:Hn,passphrase:w.licenseKey,strictReadOnly:b}):null,Z=a.trim();if(!Z&&Se){const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Ec(Se),async()=>null);if(c)return I.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const J=await Ii(L,w?.licenseKey,I);if(J.status!=="authenticated"){const c=J.status==="refresh-required",p=!c&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=Tr(),A=br(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);A&&process.stderr.write(xr(A,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${p} 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 gt=x.config.project_id;try{await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Is(s,x,L,J.token,gt,{refreshToken:()=>J.client.forceRefresh()}),async()=>0)}catch{}const wt=Ps(Z);if(wt&&!h)try{const c=await J.tierClient.preFlightCheck(wt);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
50
+ `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ue=await Dc({args:Z,projectRoot:s,platformTarget:k,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:I});if(ue.attachToRequest&&(x.runnerBootstrap=ue.metadata),ue.warning&&process.stderr.write(`[Neocortex] ${ue.warning}
51
+ `),!ue.shouldContinue)return ue.error&&process.stderr.write(`[Neocortex] ${ue.error}
52
+ `),{success:!1,error:ue.error??"Runner auto-bootstrap required but failed.",errorCode:ue.errorCode,exitCode:ue.exitCode??1};if(ue.metadata.command==="runner"&&(ue.metadata.operation==="status"||ue.metadata.operation==="doctor"))try{const c=e.runnerObserver??ba;x.runnerOperationalStatus=await c(ue.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:I})}catch{}let O;try{const c=ya(Z,x);if(c&&!c.ok){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
53
+ `),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??Pr(Z,x),un(Z)==="migrate-state"&&(O={...O,migrationAuthority:va(s)})}catch(c){if(c instanceof Ca)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Or){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
54
+ `),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!b)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),m=p(s);if(jt(m.databasePath)){const A=await c(s);try{const B=A.store.listRecentNativeAgentDispatches(20);B.length>0&&(O.nativeAgentDispatches=B)}finally{A.store.close()}}}catch{}const $=un(Z);let xe=!1;if($==="arch-plan"&&!b&&O.archPlan?.execution===void 0){const c=Ji(a);if(c)try{if(!Object.hasOwn(x.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=Yt(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},xe=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if(($==="arch-plan"||$?.startsWith("arch-")||$==="generate-pacts"||$==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Yt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Te=gt;if(($==="create-epic"||$==="idea-diagnose")&&!Te){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
55
+ `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=I.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$==="create-epic"||$==="idea-diagnose"?Lo(s,Z,$):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??($==="yolo"?Mo(s,Z,Te,O):void 0);if(e.privateExecutionBeta&&$==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?x.epics[c.epicId]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&x.stories[A]?.epic_id===c.epicId).map(A=>[A,x.stories[A]]))}})}const rt=b?{schemaVersion:1,invocationId:I.invocationId,intent:I.intent,clientProjection:Ba(Vr.map(c=>({...c,count:1})))}:void 0;let K,ve,he;if(e.privateExecutionBeta&&$==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Cr(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(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`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&$==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=_r(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(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`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}he={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(ne).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");K=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const qe=K?{schemaVersion:1,hostKind:"codex-cli",hostVersion:K.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:K.observedAtMs}}:void 0;let V;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(V=Sr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(ft=Sr(s),!ft||!v(O.archPlan.execution.pactAnswerReceipt,ft))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ge,oe,ye;if(e.privateExecutionBeta&&$==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(oe=zi(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!oe||!v(p.pactAnswerReceipt,oe.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Ki(s,oe.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ge=m.writeSet,ye={schemaVersion:1,targetEpicId:c,graphRevision:oe.receipt.graphRevision,answersSha256:oe.receipt.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ee;if(e.privateExecutionBeta&&$==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ee={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let mt,ze,ke;if(e.privateExecutionBeta&&$==="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:p}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");mt=m.choices,ze=m.plan,ke=p(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if($==="yoloop"&&!b&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??ea)({platformTarget:k,env:M})}catch{Qe=void 0}let H={args:a,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},...ye?{pactExecutionInput:ye}:{},...ee?{uxExecutionInput:ee}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const bn=Wt(H);if(!b&&e.inputSource&&e.inputSource!=="args"&&bn>=Wn)try{H={argsRef:(await Ma(I,"secondary-mutation",()=>xc(L,a,J.token,()=>J.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{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}}let it;if($==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!D||D.storyId!==c||D.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Wr(D);if(/\sbranchless-preparation\s*$/.test(a))H={...H,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");it=await B({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(m=Wr(D));const ne=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});H={...H,yoloSpecEnvelope:m,yoloChangeEvidence:ne}}H=Co(H,{projectRoot:s,supported:Y})}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),B=A(m),ne=Gr(m,!0);return{success:!1,error:ne,errorCode:ne,...B?{metadata:{yoloChangeEvidence:B}}:{},exitCode:1}}}try{const c=rr(H);if($==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};H=c.body,c.degraded?wi(H,c.telemetry):Lc(H)}catch(c){if(c instanceof zn||c instanceof Jn)return wi(H,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
56
+ `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if($==="yolo"&&H.yoloSpecEnvelope)try{const c=Hr({projectRoot:s,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:r.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),m=p({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...it?{reconciliation:it}:{}});if(m.pathsSha256!==H.yoloChangeEvidence.pathsSha256||m.baseSha!==H.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:m}=await import("../yolo/change-evidence-collector.js"),A=m(c);return{success:!1,error:p,errorCode:p,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const N=$==="arch-plan"?H.stateSnapshot.archPlan?.execution:void 0;let Lt;if(N?.owner==="root"&&(N.currentStageCommand==="arch-prd"||N.currentStageCommand==="arch-architecture"||N.currentStageCommand==="arch-fitness-functions"||N.currentStageCommand==="arch-api-contracts"||N.currentStageCommand==="generate-pacts"||N.currentStageCommand==="arch-api-integrations"||N.currentStageCommand==="arch-database"||N.currentStageCommand==="arch-security"||N.currentStageCommand==="arch-design-system"||N.currentStageCommand==="arch-ux-design"||N.currentStageCommand==="arch-performance"||N.currentStageCommand==="arch-testing"||N.currentStageCommand==="arch-infrastructure"||N.currentStageCommand==="arch-review"||N.currentStageCommand==="update-memory")&&(N.continuationState==="delegate"||N.continuationState==="advance"||N.currentStageCommand==="update-memory"&&N.continuationState==="complete"||N.currentStageCommand==="arch-review"&&N.continuationState==="ask-user"||N.currentStageCommand==="generate-pacts"&&N.continuationState==="ask-user"))try{const c=Fe(z(s,".neocortex","state.json"),"utf8"),p=JSON.parse(c),m=g(p.archPlan)?p.archPlan.execution:void 0;if(xe?m!==void 0||!g(p.epics)||!Object.hasOwn(p.epics,String(N.targetEpicId))||N.graphSource!=="committed-epic-v1"||N.graphRevision!==Yt(s,String(N.targetEpicId)):!v(En(m),N))throw new Error("architecture-root-state-binding-invalid");if(Lt=Ne("sha256").update(c).digest("hex"),V&&V.stateSha256!==Lt)throw new Error("architecture-root-state-binding-invalid");if(N.currentStageCommand==="update-memory"&&N.childStatus==="succeeded"){const A=N.continuationState==="complete"&&Array.isArray(N.acceptedStages)?{...N,continuationState:"delegate",acceptedStages:N.acceptedStages.slice(0,Ir(N))}:N;if(!Ft(N.terminalMemoryCheckpoint,N)||!v(N.terminalMemoryCheckpoint,Ln(s,A)))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 Bn("invoke-query",()=>lr(L,H,J.token,{refreshToken:()=>J.client.forceRefresh()}));if($==="yoloop"&&!b&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=O.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await Cs({projectRoot:s,snapshot:x,targetEpicId:c,originalInputSha256:r.sha256,canonicalInputSha256:d?.canonicalSha256??r.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:m}=await import("../yoloop/invoke-hooks.js"),A=await m(a,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");H=rr({...H,stateSnapshot:{...H.stateSnapshot,yoloop:A}}).body}catch(m){const A=Vi(m);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await Bn("invoke-query",()=>lr(L,H,J.token,{refreshToken:()=>J.client.forceRefresh()}))}let nn;if(b&&f.ok)try{if(h){const p=f.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>p[A]!==void 0))throw new Bt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;$a(I,c),h&&qa(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),nn=c.security}catch(c){const p=c instanceof Bt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
57
57
  `),process.stderr.write(`==================================================
58
58
  `),process.stderr.write(` UPGRADE REQUIRED
59
59
  `),process.stderr.write(`==================================================
@@ -68,11 +68,11 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
68
68
  `),process.stderr.write(` After updating, re-run your command.
69
69
  `),process.stderr.write(`==================================================
70
70
 
71
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${m}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=lc(f),m=Po(p);if(m)return process.stderr.write(`[Neocortex] ${m.error}
72
- `),m;try{if(p){const A=br(),U=wr(p,A);U&&process.stderr.write(Ar(U,A))}}catch{}return{success:!1,error:ze(f.error??"Unknown error from server",kt),...p?{errorCode:p}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const lr=ko(f.data);if(lr)return I.complete(nn),lr;let we;try{we=e.privateExecutionBeta&&H==="create-epic"&&se?$t(s).operations[se.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=we?.planningProtocol==="root-staged-v1"&&typeof we.claimId=="string"&&typeof we.epicId=="string"&&ea(f.data,{claimId:we.claimId,epicId:we.epicId,...g(j.epics[we.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:j.epics[we.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!Zi(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(wt&&k&&f.data.metadata?.mode==="arch-plan"&&g(f.data.metadata.archPlan)&&g(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 I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>Jo({projectRoot:s,sourceStateSha256:wt,requestExecution:k,initialBinding:Ct,answerReceipt:Re,pactRecordedReceipt:B,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const p=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${p}. Root stage instruction was not released.
73
- `),{success:!1,error:p,errorCode:p,exitCode:1}}if(!ee&&f.data.metadata?.mode==="menu"&&V&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>dc(V,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>W.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const p=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${p}
74
- `),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${ze(p,kt)}).`;return process.stderr.write(`${m}
75
- `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>co(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const p=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${p}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
71
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${m}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=Cc(f),m=Vo(p);if(m)return process.stderr.write(`[Neocortex] ${m.error}
72
+ `),m;try{if(p){const A=Tr(),B=br(p,A);B&&process.stderr.write(xr(B,A))}}catch{}return{success:!1,error:Je(f.error??"Unknown error from server",kt),...p?{errorCode:p}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const hr=Bo(f.data);if(hr)return I.complete(nn),hr;let Re;try{Re=e.privateExecutionBeta&&$==="create-epic"&&Pe?Ht(s).operations[Pe.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=Re?.planningProtocol==="root-staged-v1"&&typeof Re.claimId=="string"&&typeof Re.epicId=="string"&&na(f.data,{claimId:Re.claimId,epicId:Re.epicId,...g(x.epics[Re.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:x.epics[Re.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!ta(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Lt&&N&&f.data.metadata?.mode==="arch-plan"&&g(f.data.metadata.archPlan)&&g(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 I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>rc({projectRoot:s,sourceStateSha256:Lt,requestExecution:N,initialBinding:xe,answerReceipt:V,pactRecordedReceipt:ft,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const p=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${p}. Root stage instruction was not released.
73
+ `),{success:!1,error:p,errorCode:p,exitCode:1}}if(!Z&&f.data.metadata?.mode==="menu"&&Se&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Sc(Se,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>J.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const p=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${p}
74
+ `),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Je(p,kt)}).`;return process.stderr.write(`${m}
75
+ `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>uo(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const p=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${p}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
76
76
  `),{success:!1,error:p,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(`
77
77
  `),process.stderr.write(`==================================================
78
78
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
@@ -92,51 +92,51 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
92
92
  `),{success:!1,error:A,errorCode:A,exitCode:1}}}catch(m){if(p){const A=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] ${A}. No yoloop continuation instructions were released.
93
93
  `),{success:!1,error:A,errorCode:A,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:p}=await import("../continuity/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const p=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${p}. No continuity mutation was committed.
94
94
  `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${p}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const p=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${p}. No continuity mutation was committed.
95
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${ze(p,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await W.client.forceRefresh()?(await W.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
95
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(p,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await J.client.forceRefresh()?(await J.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
96
96
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
97
97
  `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
98
- `)}}let re,ur=!1;if(e.privateExecutionBeta&&!rn)try{if(!X||!f.data.metadata?.privateExecution||!De||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:p}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),U=f.data.metadata.mode==="yolo",ie=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",de=f.data.metadata.mode==="create-epic",ae=g(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=g(ae?.binding)?ae.binding:void 0,$=de&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(de&&!$)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||$,Be=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",Ue=de||Ee;if(Be&&!ye||me&&!le)throw new Error("private-execution-planning-predecessor-unavailable");const Ke=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=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,gt=Ce!==void 0,bn=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",nt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",ft=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",mt=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",xn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",hr=S?"tech-debt-registry-v1":xn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ye=O.archPlan?.execution,on=Ye?.targetEpicId,cn=Ye?.graphRevision;if(gt&&(Ye?.currentStageCommand!==Ce||typeof on!="string"||!/^P[1-9][0-9]{0,11}$/.test(on)||typeof cn!="string"||!/^[a-f0-9]{64}$/.test(cn)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!ge||!je||!J||Ye?.currentStageCommand!=="generate-pacts"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ge.targetEpicId||Ye.graphRevision!==ge.graphRevision||!v(Ye.pactAnswerReceipt,J.receipt)))throw new Error("private-execution-pact-admission-unverified");if(ft&&(!ne||!Ve||Ye?.currentStageCommand!=="arch-ux-design"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ne.targetEpicId||Ye.graphRevision!==ne.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(mt&&(!Ie||!_t||!qe||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let gr;if(nt){const{planPactToolchainManifest:ce,preparePactToolchainCandidate:ue}=await import("../private-execution/pact-toolchain.js");try{ce(s,J.answers.generateProvider),gr=ue(s,J.answers.generateProvider)}catch(Y){if(Y.message!=="pact-toolchain-manifest-unsupported")throw Y}}let At,pe,Tn;const oe=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Qe;if(U){if(!oe||typeof oe.storyId!="string"||typeof oe.graphRevision!="string"||typeof oe.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Qe=oe.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:x}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Te}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:yt}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:He,recordPrivateYoloCleanBaseline:Ae}=await import("../private-execution/clean-baseline.js"),be=x(f.data.metadata.privateExecution,{projectId:De,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:oe.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion}),it=await W.client.getToken();if(!it)throw new Error("private-execution-auth-unavailable");if(!await os(M,{leaseId:be.leaseId,...be.binding},it))throw new Error("private-execution-setup-lease-cancel-unverified");const Dt=He(s),sn=await Te({projectRoot:s,storyId:bt.storyId});if(!sn.ok)throw new Error("private-execution-root-setup-denied");await Ae(s,sn.value,Dt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,oe.graphRevision,e.privateExecutionWorkspaceParent);const Tt=await yt({projectRoot:s,storyId:bt.storyId});if(!Tt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Tt.reasonCode}`);re={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const Pn=mn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return I.complete(nn),{success:!0,instructions:`# Setup do branch validado
98
+ `)}}let te,gr=!1;if(e.privateExecutionBeta&&!rn)try{if(!K||!f.data.metadata?.privateExecution||!Te||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:p}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),B=f.data.metadata.mode==="yolo",ne=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",ce=f.data.metadata.mode==="create-epic",re=g(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=g(re?.binding)?re.binding:void 0,U=ce&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(ce&&!U)throw new Error("private-execution-planning-root-protocol-required");const Ie=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||U,Ue=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",$e=ce||Ie;if(Ue&&!ve||me&&!he)throw new Error("private-execution-planning-predecessor-unavailable");const Xe=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=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,yt=Ce!==void 0,Tn=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",at=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",It=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",Et=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",Pn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",fr=S?"tech-debt-registry-v1":Pn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ye=O.archPlan?.execution,on=Ye?.targetEpicId,cn=Ye?.graphRevision;if(yt&&(Ye?.currentStageCommand!==Ce||typeof on!="string"||!/^P[1-9][0-9]{0,11}$/.test(on)||typeof cn!="string"||!/^[a-f0-9]{64}$/.test(cn)))throw new Error("private-execution-architecture-admission-unverified");if(at&&(!ye||!ge||!oe||Ye?.currentStageCommand!=="generate-pacts"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ye.targetEpicId||Ye.graphRevision!==ye.graphRevision||!v(Ye.pactAnswerReceipt,oe.receipt)))throw new Error("private-execution-pact-admission-unverified");if(It&&(!ee||!Ve||Ye?.currentStageCommand!=="arch-ux-design"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ee.targetEpicId||Ye.graphRevision!==ee.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(Et&&(!ke||!mt||!ze||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let mr;if(at){const{planPactToolchainManifest:ae,preparePactToolchainCandidate:le}=await import("../private-execution/pact-toolchain.js");try{ae(s,oe.answers.generateProvider),mr=le(s,oe.answers.generateProvider)}catch(W){if(W.message!=="pact-toolchain-manifest-unsupported")throw W}}let At,se,kn;const ie=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Ze;if(B){if(!ie||typeof ie.storyId!="string"||typeof ie.graphRevision!="string"||typeof ie.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Ze=ie.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:T}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Oe}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:St}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:We,recordPrivateYoloCleanBaseline:we}=await import("../private-execution/clean-baseline.js"),Ae=T(f.data.metadata.privateExecution,{projectId:Te,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:ie.graphRevision,inputSha256:r.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion}),ct=await J.client.getToken();if(!ct)throw new Error("private-execution-auth-unavailable");if(!await ys(L,{leaseId:Ae.leaseId,...Ae.binding},ct))throw new Error("private-execution-setup-lease-cancel-unverified");const Mt=We(s),sn=await Oe({projectRoot:s,storyId:bt.storyId});if(!sn.ok)throw new Error("private-execution-root-setup-denied");await we(s,sn.value,Mt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,ie.graphRevision,e.privateExecutionWorkspaceParent);const Tt=await St({projectRoot:s,storyId:bt.storyId});if(!Tt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Tt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const On=yn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return I.complete(nn),{success:!0,instructions:`# Setup do branch validado
99
99
 
100
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Pn.metadata,privateExecutionReceipt:re},exitCode:0}}let ce;try{ce=We("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(ce!==oe.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ue=gn(s,{required:!0}),Y=typeof oe.epicId=="string"?ue.epics[oe.epicId]:void 0,D=g(Y?.branch_lease)?Y.branch_lease:void 0;if(!Y||Y.graph_revision!==oe.graphRevision||!D||D.ownerStoryId!==oe.storyId||typeof D.expiresAt!="string"||!Number.isFinite(Date.parse(D.expiresAt))||Date.parse(D.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(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"||ie||Ee||Be||me||Ke||gt||nt||ft||mt){if(!Ue&&!Be&&!me&&!Ke&&!ie&&!gt&&!nt&&!ft&&!mt&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(U){const{ensurePrivateYoloIsolatedSession:ce,reconcilePrivateYoloIsolatedSession:ue}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await ue(s,Qe,oe.graphRevision);else{const Y=await ce(s,Qe,oe.graphRevision,e.privateExecutionWorkspaceParent),D=await m(Y.workspace.workspacePath);if(D.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=D}}if(Date.now()-X.observedAtMs>2e4){const ce=await m(X.projectRoot);if(ce.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=ce}const fr=await W.client.getToken();if(!fr)throw new Error("private-execution-auth-unavailable");const $e=Ue?f.data.metadata.epicClaim:void 0;if(Ue&&(!$e||typeof $e.claimId!="string"||typeof $e.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(Ue){if(!se)throw new Error("private-execution-epic-claim-admission-unverified");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Xr(s,se.fingerprint,$e.claimId,$e.epicId,$?"root-staged-v1":void 0),()=>{}),ur=!0;const{preparePrivateYoloIsolatedWorkspace:ce,PRIVATE_EPIC_PENDING_SIDECAR:ue}=await import("../private-execution/isolated-workspace.js"),Y=e.privateExecutionWorkspaceParent??Q(Jt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Ft(Y,{recursive:!0,mode:448}),At=ce(s,Y,!0),Tn=Pe("sha256").update(Ge(Q(s,ue))).digest("hex");const D=await m(At.workspacePath);if(D.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=D}else if(!U&&!ie){const{preparePrivateYoloIsolatedWorkspace:ce}=await import("../private-execution/isolated-workspace.js"),ue=e.privateExecutionWorkspaceParent??Q(Jt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Ft(ue,{recursive:!0,mode:448}),pe=ce(s,ue,Be||me),Ke||gt||nt||ft||mt){if(!Z)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:D}=await import("../private-execution/isolated-workspace.js");D(pe,Z)}const Y=await m(pe.workspacePath);if(Y.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=Y}const rt=await c(f.data.metadata.privateExecution,{projectId:De,commandId:U?"yolo":de?"create-epic":gt?Ce:nt?"generate-pacts":ft?"arch-ux-design":mt?"property-test":Ke?xn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...U?{graphRevision:oe.graphRevision}:{...Ue?{claimId:$e.claimId,epicId:$e.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:Be?{claimId:ye.claimId,epicId:ye.epicId,diagnosisReceiptId:ye.diagnosisReceiptId,intakeRevision:ye.intakeRevision,physicalAcceptanceReceiptId:ye.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,researchReceiptId:le.researchReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Ke?{writeSetId:hr}:ie?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:gt?{targetEpicId:on,graphRevision:cn,writeSetId:bn}:nt?{targetEpicId:ge.targetEpicId,graphRevision:ge.graphRevision,answersSha256:ge.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.pathCount}:ft?{targetEpicId:ne.targetEpicId,graphRevision:ne.graphRevision,adapterId:ne.adapterId,authoritySha256:ne.authoritySha256,pathsSha256:ne.pathsSha256,screenCount:ne.screenCount,pathCount:ne.pathCount}:mt?{prdPath:Ie.prdPath,prdSha256:Ie.prdSha256,planSha256:Ie.planSha256,pathsSha256:Ie.pathsSha256,aggregateCount:Ie.aggregateCount,invariantCount:Ie.invariantCount,pathCount:Ie.pathCount,language:Ie.language,numRuns:Ie.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:p(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion},ce=>as(M,{...ce},fr));if(ie){const{parsePrivateExecutionDescriptor:ce}=await import("../private-execution/delivery.js"),ue=ce(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:Y}=await import("../private-execution/private-report-store.js");re={schemaVersion:1,outcome:"report-stored",report:await Y({projectRoot:s,material:rt,format:ue.binding.format,sha256:ue.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ce}=await import("../private-execution/root-checkpoint.js");re={...await ce(s,bt)}}else{const ce=Ee?`${rt}
100
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...On.metadata,privateExecutionReceipt:te},exitCode:0}}let ae;try{ae=Ge("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!==ie.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const le=fn(s,{required:!0}),W=typeof ie.epicId=="string"?le.epics[ie.epicId]:void 0,j=g(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==ie.graphRevision||!j||j.ownerStoryId!==ie.storyId||typeof j.expiresAt!="string"||!Number.isFinite(Date.parse(j.expiresAt))||Date.parse(j.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"||ce&&f.data.metadata.resolvedTrigger==="create-epic"||ne||Ie||Ue||me||Xe||yt||at||It||Et){if(!$e&&!Ue&&!me&&!Xe&&!ne&&!yt&&!at&&!It&&!Et&&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:le}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await le(s,Ze,ie.graphRevision);else{const W=await ae(s,Ze,ie.graphRevision,e.privateExecutionWorkspaceParent),j=await m(W.workspace.workspacePath);if(j.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=j}}if(Date.now()-K.observedAtMs>2e4){const ae=await m(K.projectRoot);if(ae.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=ae}const yr=await J.client.getToken();if(!yr)throw new Error("private-execution-auth-unavailable");const He=$e?f.data.metadata.epicClaim:void 0;if($e&&(!He||typeof He.claimId!="string"||typeof He.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if($e){if(!Pe)throw new Error("private-execution-epic-claim-admission-unverified");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ei(s,Pe.fingerprint,He.claimId,He.epicId,U?"root-staged-v1":void 0),()=>{}),gr=!0;const{preparePrivateYoloIsolatedWorkspace:ae,PRIVATE_EPIC_PENDING_SIDECAR:le}=await import("../private-execution/isolated-workspace.js"),W=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||qt(W,{recursive:!0,mode:448}),At=ae(s,W,!0),kn=Ne("sha256").update(Fe(z(s,le))).digest("hex");const j=await m(At.workspacePath);if(j.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=j}else if(!B&&!ne){const{preparePrivateYoloIsolatedWorkspace:ae}=await import("../private-execution/isolated-workspace.js"),le=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||qt(le,{recursive:!0,mode:448}),se=ae(s,le,Ue||me),Xe||yt||at||It||Et){if(!pe)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:j}=await import("../private-execution/isolated-workspace.js");j(se,pe)}const W=await m(se.workspacePath);if(W.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=W}const ot=await c(f.data.metadata.privateExecution,{projectId:Te,commandId:B?"yolo":ce?"create-epic":yt?Ce:at?"generate-pacts":It?"arch-ux-design":Et?"property-test":Xe?Pn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...B?{graphRevision:ie.graphRevision}:{...$e?{claimId:He.claimId,epicId:He.epicId,...Ie?{writeSetId:"idea-diagnosis-v1"}:{}}:Ue?{claimId:ve.claimId,epicId:ve.epicId,diagnosisReceiptId:ve.diagnosisReceiptId,intakeRevision:ve.intakeRevision,physicalAcceptanceReceiptId:ve.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:he.claimId,epicId:he.epicId,diagnosisReceiptId:he.diagnosisReceiptId,researchReceiptId:he.researchReceiptId,intakeRevision:he.intakeRevision,physicalAcceptanceReceiptId:he.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Xe?{writeSetId:fr}:ne?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:yt?{targetEpicId:on,graphRevision:cn,writeSetId:Tn}:at?{targetEpicId:ye.targetEpicId,graphRevision:ye.graphRevision,answersSha256:ye.answersSha256,specSha256:ye.specSha256,pathsSha256:ye.pathsSha256,endpointCount:ye.endpointCount,pathCount:ye.pathCount}:It?{targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,authoritySha256:ee.authoritySha256,pathsSha256:ee.pathsSha256,screenCount:ee.screenCount,pathCount:ee.pathCount}:Et?{prdPath:ke.prdPath,prdSha256:ke.prdSha256,planSha256:ke.planSha256,pathsSha256:ke.pathsSha256,aggregateCount:ke.aggregateCount,invariantCount:ke.invariantCount,pathCount:ke.pathCount,language:ke.language,numRuns:ke.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:p(O)},inputSha256:r.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion},ae=>ms(L,{...ae},yr));if(ne){const{parsePrivateExecutionDescriptor:ae}=await import("../private-execution/delivery.js"),le=ae(f.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:ot,format:le.binding.format,sha256:le.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ae}=await import("../private-execution/root-checkpoint.js");te={...await ae(s,bt)}}else{const ae=Ie?`${ot}
101
101
 
102
102
  Private P01 handoff (local only):
103
- The durable reserved epic ID is ${$e.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${$e.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.
104
- `:Be?`${rt}
103
+ The durable reserved epic ID is ${He.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${He.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.
104
+ `:Ue?`${ot}
105
105
 
106
106
  Private P02 handoff (local only):
107
- The admitted epic is ${ye.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${ye.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.
108
- `:me?`${rt}
107
+ The admitted epic is ${ve.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${ve.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.
108
+ `:me?`${ot}
109
109
 
110
110
  Private P03 handoff (local only):
111
- The admitted epic is ${le.epicId}. Generate exactly docs/epics/epic-${le.epicId}.md, 1 to 24 contiguous docs/stories/${le.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.
112
- `:gt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,Ce,bn,yr(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
111
+ The admitted epic is ${he.epicId}. Generate exactly docs/epics/epic-${he.epicId}.md, 1 to 24 contiguous docs/stories/${he.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.
112
+ `:yt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(ot,Ce,Tn,Er(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):at?`${ot}
113
113
 
114
114
  Private A03.5 handoff (local only):
115
- ${JSON.stringify({consumer:J.answers.consumer,provider:J.answers.provider,matchersAggressive:J.answers.matchersAggressive,generateProvider:J.answers.generateProvider,brokerConfigured:J.answers.brokerUrl!==null,allowedPaths:je.paths})}
115
+ ${JSON.stringify({consumer:oe.answers.consumer,provider:oe.answers.provider,matchersAggressive:oe.answers.matchersAggressive,generateProvider:oe.answers.generateProvider,brokerConfigured:oe.answers.brokerUrl!==null,allowedPaths:ge.paths})}
116
116
  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.
117
- `:ft?`${rt}
117
+ `:It?`${ot}
118
118
 
119
119
  Private A08 handoff (local only):
120
- ${JSON.stringify({targetEpicId:ne.targetEpicId,graphRevision:ne.graphRevision,adapterId:ne.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
120
+ ${JSON.stringify({targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
121
121
  Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
122
- `:mt?`${rt}
122
+ `:Et?`${ot}
123
123
 
124
124
  Private property-test handoff (local only):
125
- ${JSON.stringify({language:qe.language,numRuns:qe.numRuns,aggregates:qe.aggregates.map(D=>({name:D.name,implementationFile:D.implementationFile,testFile:D.testFile,invariantCount:D.invariantCount}))})}
125
+ ${JSON.stringify({language:ze.language,numRuns:ze.numRuns,aggregates:ze.aggregates.map(j=>({name:j.name,implementationFile:j.implementationFile,testFile:j.testFile,invariantCount:j.invariantCount}))})}
126
126
  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.
127
- `:rt;let ue=ce;if(U){const{readPrivateYoloFrozenWriteSet:D}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:x}=await import("../private-execution/frozen-handoff.js"),Te=await D(s,Qe,oe.executionBranch,oe.graphRevision);ue=x(ce,Te);const{resumePrivateYoloIsolatedSession:yt}=await import("../private-execution/isolated-session.js"),He=await yt(s,Qe,oe.graphRevision),Ae=vn(s,{epicAware:!0}).stories[Qe],be=O.stories[Qe];if(!Ae||!be||Ae.status!==be.status||JSON.stringify(Ae.steps_completed)!==JSON.stringify(be.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const it=We("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ue+=`
127
+ `:ot;let le=ae;if(B){const{readPrivateYoloFrozenWriteSet:j}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:T}=await import("../private-execution/frozen-handoff.js"),Oe=await j(s,Ze,ie.executionBranch,ie.graphRevision);le=T(ae,Oe);const{resumePrivateYoloIsolatedSession:St}=await import("../private-execution/isolated-session.js"),We=await St(s,Ze,ie.graphRevision),we=Cn(s,{epicAware:!0}).stories[Ze],Ae=O.stories[Ze];if(!we||!Ae||we.status!==Ae.status||JSON.stringify(we.steps_completed)!==JSON.stringify(Ae.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const ct=Ge("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();le+=`
128
128
  Root physical dispatch observations (data, not phase completion):
129
- `+JSON.stringify({storyId:Qe,graphRevision:oe.graphRevision,sourceHeadSha:it,privateSnapshotSha:He.snapshotSha,effectiveStatus:Ae.status,hostKind:"codex-cli",hostVersion:X.hostVersion})+`
129
+ `+JSON.stringify({storyId:Ze,graphRevision:ie.graphRevision,sourceHeadSha:ct,privateSnapshotSha:We.snapshotSha,effectiveStatus:we.status,hostKind:"codex-cli",hostVersion:K.hostVersion})+`
130
130
  Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
131
- `}const Y=await A(ue,X,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...U?{expectedExecutionBranch:oe.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:pe?{expectedExecutionBranch:pe.executionBranch}:{}});if(U){const{admitPrivateYoloIsolatedSessionStep:D}=await import("../private-execution/isolated-session.js"),x=await D(s,Qe,oe.graphRevision);let Te;if(f.data.metadata.stepId===ta){const He=f.data.metadata.mutationQaFeature;if(!He)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!He.enabled)Te={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Ae,be;try{const it=x.session.workspace.workspacePath,Dt=`sha:${x.session.workspace.baseSha}`,{planMutationQa:sn}=await import("./mutation-qa.js"),xt=sn(it,Dt);if(xt.headSha!==x.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:kn}=await import("./mutation-qa-checkpoint.js");if(Tt=kn(it,Dt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Pn}=await import("./mutation-qa-gate.js");if(Ae=Pn(it,Dt,xt.planSha256),Ae.followUpDebtRequired){const{recordMutationQaFollowUpDebt:kn}=await import("./mutation-qa-checkpoint.js");be=kn(it,Dt,xt.planSha256,Ae.status,Tt,s)}const{resumePrivateYoloIsolatedSession:Gi}=await import("../private-execution/isolated-session.js");if((await Gi(s,Qe,oe.graphRevision)).snapshotSha!==x.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Ae.blocksLocalQa||!Ae.safeToContinueLocalQa&&!be)throw new Error(`private-execution-mutation-qa-${Ae.status}`);Te={...Ae,...be?{followUpDebt:{status:"recorded",owner:be.owner,severity:be.severity,reasonCode:be.reasonCode,planSha256:be.planSha256,publicSafe:!0}}:{}}}}const yt={schemaVersion:1,outcome:x.admission.outcome,sequence:x.session.sequence,snapshotSha:x.session.snapshotSha,patchSha256:x.admission.patchSha256,changedPathCount:x.admission.changedPaths.length};re={...Y,isolation:yt,...Te?{mutationQa:Te}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:D,admitPrivateIdeaDiagnosisWorkspace:x}=await import("../private-execution/isolated-admission.js"),Te=Ee?x(At,$e.claimId,$e.epicId,se.fingerprint,Tn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):D(At,$e.claimId,$e.epicId,se.fingerprint,Tn);re={...Y,isolation:{schemaVersion:1,outcome:Te.outcome,baseSha:Te.baseSha,patchSha256:Te.patchSha256,changedPathCount:Te.changedPaths.length}}}else if(pe&&Be){const{admitPrivateIdeaResearchWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,ye.claimId,ye.epicId,ye.diagnosisReceiptId,ye.intakeRevision,ye.sourceStateSha256);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&me){const{admitPrivateGenerateEpicWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,le.claimId,le.epicId,le.diagnosisReceiptId,le.researchReceiptId,le.intakeRevision,le.sourceStateSha256);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&nt){const{admitPrivatePactWorkspace:D}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:x}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Te}=await import("../private-execution/pact-consumer-runtime.js"),yt=J.answers.generateProvider,He=D(pe,ge.targetEpicId,ge.graphRevision,J.receipt,je,gr),Ae=x(s,yt),be=Te(s,je,yt);re={...Y,isolation:{schemaVersion:1,outcome:He.outcome,baseSha:He.baseSha,patchSha256:He.patchSha256,changedPathCount:He.changedPaths.length,consumerBindingCandidateCount:He.consumerBindingCandidateCount,consumerScaffoldCount:He.consumerScaffoldCount,toolchain:Ae,consumerRuntime:be}}}else if(pe&&ft){const{admitPrivateUxWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,ne.targetEpicId,ne.graphRevision,Ve);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&mt){const{admitPrivatePropertyTestWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,_t,qe);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(pe&&gt){const{admitPrivateArchitectureStageWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,Ce,bn,on,cn);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&Ke){const{admitPrivateProjectStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,xn,hr);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe){const{admitPrivateStateBoundStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,f.data.metadata.storyId);re={...Y,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else re={...Y}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:p,errorCode:p,exitCode:1}}let An;if(rn&&g(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!we?.claimId||!we.epicId||!De)throw new Error("missing-reservation");const c=Cr(s,we.claimId,we.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=vn(s,{verifyPlanningGeneration:!0}),m=p.epics[we.epicId];if(!g(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:De},epics:{[we.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(ie=>[ie,p.stories[ie]])),epic_id_ledger:p.epic_id_ledger};if(!await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Oi(M,W.token,{claimId:we.claimId,projectId:De,epicId:we.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>W.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");An={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 an=mn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Lt=re?.isolation,Wi=an.metadata?.resolvedTrigger==="property-test"&&Lt!==null&&typeof Lt=="object"&&!Array.isArray(Lt)&&Lt.outcome==="admitted-unverified"&&Lt.checkpointAccepted===!1&&Lt.rootNextAction==="property-semantic-review-required";if(se&&!ur&&!rn&&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 p=c;if(p.outcome!=="reserved"||typeof p.claimId!="string"||typeof p.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Xr(s,se.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return I.complete(nn),{success:!0,instructions:re?re.outcome==="checkpoint-validated"?`# Checkpoint da story validado
131
+ `}const W=await A(le,K,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...B?{expectedExecutionBranch:ie.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(B){const{admitPrivateYoloIsolatedSessionStep:j}=await import("../private-execution/isolated-session.js"),T=await j(s,Ze,ie.graphRevision);let Oe;if(f.data.metadata.stepId===ra){const We=f.data.metadata.mutationQaFeature;if(!We)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!We.enabled)Oe={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let we,Ae;try{const ct=T.session.workspace.workspacePath,Mt=`sha:${T.session.workspace.baseSha}`,{planMutationQa:sn}=await import("./mutation-qa.js"),xt=sn(ct,Mt);if(xt.headSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:Nn}=await import("./mutation-qa-checkpoint.js");if(Tt=Nn(ct,Mt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:On}=await import("./mutation-qa-gate.js");if(we=On(ct,Mt,xt.planSha256),we.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Nn}=await import("./mutation-qa-checkpoint.js");Ae=Nn(ct,Mt,xt.planSha256,we.status,Tt,s)}const{resumePrivateYoloIsolatedSession:Yi}=await import("../private-execution/isolated-session.js");if((await Yi(s,Ze,ie.graphRevision)).snapshotSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(we.blocksLocalQa||!we.safeToContinueLocalQa&&!Ae)throw new Error(`private-execution-mutation-qa-${we.status}`);Oe={...we,...Ae?{followUpDebt:{status:"recorded",owner:Ae.owner,severity:Ae.severity,reasonCode:Ae.reasonCode,planSha256:Ae.planSha256,publicSafe:!0}}:{}}}}const St={schemaVersion:1,outcome:T.admission.outcome,sequence:T.session.sequence,snapshotSha:T.session.snapshotSha,patchSha256:T.admission.patchSha256,changedPathCount:T.admission.changedPaths.length};te={...W,isolation:St,...Oe?{mutationQa:Oe}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:j,admitPrivateIdeaDiagnosisWorkspace:T}=await import("../private-execution/isolated-admission.js"),Oe=Ie?T(At,He.claimId,He.epicId,Pe.fingerprint,kn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):j(At,He.claimId,He.epicId,Pe.fingerprint,kn);te={...W,isolation:{schemaVersion:1,outcome:Oe.outcome,baseSha:Oe.baseSha,patchSha256:Oe.patchSha256,changedPathCount:Oe.changedPaths.length}}}else if(se&&Ue){const{admitPrivateIdeaResearchWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,ve.claimId,ve.epicId,ve.diagnosisReceiptId,ve.intakeRevision,ve.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&me){const{admitPrivateGenerateEpicWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,he.claimId,he.epicId,he.diagnosisReceiptId,he.researchReceiptId,he.intakeRevision,he.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&at){const{admitPrivatePactWorkspace:j}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:T}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Oe}=await import("../private-execution/pact-consumer-runtime.js"),St=oe.answers.generateProvider,We=j(se,ye.targetEpicId,ye.graphRevision,oe.receipt,ge,mr),we=T(s,St),Ae=Oe(s,ge,St);te={...W,isolation:{schemaVersion:1,outcome:We.outcome,baseSha:We.baseSha,patchSha256:We.patchSha256,changedPathCount:We.changedPaths.length,consumerBindingCandidateCount:We.consumerBindingCandidateCount,consumerScaffoldCount:We.consumerScaffoldCount,toolchain:we,consumerRuntime:Ae}}}else if(se&&It){const{admitPrivateUxWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,ee.targetEpicId,ee.graphRevision,Ve);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&Et){const{admitPrivatePropertyTestWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,mt,ze);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(se&&yt){const{admitPrivateArchitectureStageWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,Ce,Tn,on,cn);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&Xe){const{admitPrivateProjectStepWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,Pn,fr);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se){const{admitPrivateStateBoundStepWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,f.data.metadata.storyId);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else te={...W}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:p,errorCode:p,exitCode:1}}let xn;if(rn&&g(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Re?.claimId||!Re.epicId||!Te)throw new Error("missing-reservation");const c=Rr(s,Re.claimId,Re.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=Cn(s,{verifyPlanningGeneration:!0}),m=p.epics[Re.epicId];if(!g(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:Te},epics:{[Re.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(ne=>[ne,p.stories[ne]])),epic_id_ledger:p.epic_id_ledger};if(!await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Li(L,J.token,{claimId:Re.claimId,projectId:Te,epicId:Re.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>J.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");xn={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 an=yn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Dt=te?.isolation,Fi=an.metadata?.resolvedTrigger==="property-test"&&Dt!==null&&typeof Dt=="object"&&!Array.isArray(Dt)&&Dt.outcome==="admitted-unverified"&&Dt.checkpointAccepted===!1&&Dt.rootNextAction==="property-semantic-review-required";if(Pe&&!gr&&!rn&&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 p=c;if(p.outcome!=="reserved"||typeof p.claimId!="string"||typeof p.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ei(s,Pe.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return I.complete(nn),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
132
132
 
133
- O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:re.outcome==="setup-accepted"?`# Setup do branch validado
133
+ O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:te.outcome==="setup-accepted"?`# Setup do branch validado
134
134
 
135
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:re.outcome==="report-stored"?`# Relat\xF3rio privado salvo
135
+ 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
136
136
 
137
- Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Wi?"# 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
137
+ Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Fi?"# 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
138
138
 
139
- O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:re?{...an.metadata,privateExecutionReceipt:re}:{...an.metadata,...An?{planningMaterialization:An}:{}},exitCode:0}}function Es(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":un(t):null}const Ui="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Ss=`
139
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:te?{...an.metadata,privateExecutionReceipt:te}:{...an.metadata,...xn?{planningMaterialization:xn}:{}},exitCode:0}}function Ps(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":un(t):null}const Hi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",ks=`
140
140
  neocortex-client invoke - Send orchestration request to server
141
141
 
142
142
  Usage:
@@ -207,12 +207,12 @@ Safety:
207
207
  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.
208
208
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
209
209
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
210
- `.trim();function vs(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Le(e,t,i,r){return new yn("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function Ot(e){return Le("missing-input-value",`${e} requires a value. ${Ui}`)}function Cs(e){try{if(!Ji(e).isFile())throw Le("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ge(e)}catch(t){throw t instanceof yn?t:Le("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function _s(){try{if(process.stdin.isTTY)throw Le("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ge(0)}catch(e){throw e instanceof yn?e:Le("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Rs(e,t={}){let i,r=!1,a,n,o="plain",d=!1,s,l,y=!1,S=!1,u;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const _=e[++T];if(_===void 0)throw Ot("--args");if(i!==void 0)throw Le("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=_;break}case"--stdin":if(r)throw Le("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const _=e[++T];if(_===void 0)throw Ot("--args-file");if(a!==void 0)throw Le("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=_;break}case"--project-root":{const _=e[++T];if(_===void 0)throw Ot("--project-root");n=_;break}case"--format":{const _=e[++T];if(_===void 0)throw Ot("--format");if(_!=="json"&&_!=="plain")throw Le("unexpected-cli-token","--format accepts only json or plain.");o=_;break}case"--watch":d=!0;break;case"--server-url":{const _=e[++T];if(_===void 0)throw Ot("--server-url");s=_;break}case"--platform-target":{const _=e[++T];if(_===void 0)throw Ot("--platform-target");l=_;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const _=e[++T];if(_===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(_))throw Le("unexpected-cli-token","Invalid or duplicate private execution model.");u=_;break}default:if(i!==void 0&&P&&(!P.startsWith("-")||P==="-")){i+=` ${P}`;break}throw Le("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&&(!S||y))throw Le("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const C=[i!==void 0?"args":void 0,r?"stdin":void 0,a!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(C.length===0)throw Le("missing-input-value",Ui);if(C.length>1)throw Le("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const E=C[0],h=E==="args"?i:E==="stdin"?(t.readStdin??_s)():(t.readArgsFile??Cs)(a);let I;try{I=Kt(E,h)}catch(T){throw T instanceof Ya?Le("invalid-utf8",T.message,E):T}const b=E==="args"?qc(I.rawArgs):Ne(I.rawArgs),L=b.args===I.rawArgs?I:Kt(E,b.args);return{args:b.args,inputSource:E,inputEnvelope:L,projectRoot:n,format:o,watch:d||b.watch,commandLevelWatch:b.metadata,serverUrl:s,platformTarget:l,strictReadOnly:y,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function $i(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Hi(e,t,i=process.stdout,r=process.stderr){if(t.format==="json"){const o=mn(e.instructions,e.metadata),d=$i(o.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:d,publicSafe:!0})+`
210
+ `.trim();function Os(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function je(e,t,i,n){return new In("INVOCATION_MALFORMED_INPUT",t,e,i,n)}function Ot(e){return je("missing-input-value",`${e} requires a value. ${Hi}`)}function Ns(e){try{if(!Qi(e).isFile())throw je("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Fe(e)}catch(t){throw t instanceof In?t:je("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Ls(){try{if(process.stdin.isTTY)throw je("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Fe(0)}catch(e){throw e instanceof In?e:je("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Ds(e,t={}){let i,n=!1,a,r,o="plain",d=!1,s,l,y=!1,S=!1,u;for(let P=0;P<e.length;P++){const k=e[P];switch(k){case"--args":{const _=e[++P];if(_===void 0)throw Ot("--args");if(i!==void 0)throw je("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=_;break}case"--stdin":if(n)throw je("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");n=!0;break;case"--args-file":{const _=e[++P];if(_===void 0)throw Ot("--args-file");if(a!==void 0)throw je("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=_;break}case"--project-root":{const _=e[++P];if(_===void 0)throw Ot("--project-root");r=_;break}case"--format":{const _=e[++P];if(_===void 0)throw Ot("--format");if(_!=="json"&&_!=="plain")throw je("unexpected-cli-token","--format accepts only json or plain.");o=_;break}case"--watch":d=!0;break;case"--server-url":{const _=e[++P];if(_===void 0)throw Ot("--server-url");s=_;break}case"--platform-target":{const _=e[++P];if(_===void 0)throw Ot("--platform-target");l=_;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const _=e[++P];if(_===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(_))throw je("unexpected-cli-token","Invalid or duplicate private execution model.");u=_;break}default:if(i!==void 0&&k&&(!k.startsWith("-")||k==="-")){i+=` ${k}`;break}throw je("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&&(!S||y))throw je("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const C=[i!==void 0?"args":void 0,n?"stdin":void 0,a!==void 0?"args-file":void 0].filter(P=>P!==void 0);if(C.length===0)throw je("missing-input-value",Hi);if(C.length>1)throw je("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const E=C[0],h=E==="args"?i:E==="stdin"?(t.readStdin??Ls)():(t.readArgsFile??Ns)(a);let I;try{I=Qt(E,h)}catch(P){throw P instanceof za?je("invalid-utf8",P.message,E):P}const b=E==="args"?is(I.rawArgs):Me(I.rawArgs),M=b.args===I.rawArgs?I:Qt(E,b.args);return{args:b.args,inputSource:E,inputEnvelope:M,projectRoot:r,format:o,watch:d||b.watch,commandLevelWatch:b.metadata,serverUrl:s,platformTarget:l,strictReadOnly:y,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function Wi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Gi(e,t,i=process.stdout,n=process.stderr){if(t.format==="json"){const o=yn(e.instructions,e.metadata),d=Wi(o.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:d,publicSafe:!0})+`
211
211
  `);return}i.write(JSON.stringify({instructions:o.instructions,metadata:d})+`
212
- `);return}const a=mn(e.instructions,e.metadata),n=$i(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
213
- `),n&&r.write(JSON.stringify(n)+`
214
- `)}async function Nd(e=process.stdout,t=process.stderr){const i=a=>new Promise(n=>{let o=!1;const d=y=>{o||(o=!0,clearTimeout(l),setImmediate(()=>a.removeListener("error",s)),n(y))},s=()=>d(!1),l=setTimeout(()=>d(!1),1e4);a.once("error",s);try{a.write("",y=>d(!y))}catch{d(!1)}});return(await Promise.all([i(e),i(t)])).every(Boolean)}function ws(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Ld(e){if(vs(e))return process.stdout.write(`${Ss}
215
- `),0;let t;try{t=Rs(e)}catch(r){if(r instanceof yn)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
216
- `),1;throw r}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."})+`
217
- `),1):(await ba({args:t.args,projectRoot:Wn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await Is({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(!i.success&&i.errorCode==="YOLOOP_RELEASE_BLOCKED"&&i.instructions&&i.metadata)return Hi(i,t),i.exitCode;if(!i.success){const r=i.metadata?.invocationInput,a=jo(i.metadata?.yoloChangeEvidence),n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:ze(i.error??"",kt),...typeof n?.reason=="string"?{reason:ze(n.reason,80)}:{},...typeof n?.source=="string"?{source:ze(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:ze(n.remediation,kt)}:{},...a?{yolo_change_evidence:a}:{}})+`
218
- `),i.exitCode}if(Hi(i,t),t.watch){const r=new AbortController,a=ws(r);try{const n=is(i.metadata,t.args);n.disabled?Dc(n.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Mc({projectRoot:Wn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{a()}}return 0}export{Ss as INVOKE_HELP_TEXT,qr as INVOKE_PAYLOAD_LIMIT_BYTES,$n as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,yn as InvokeCliInputError,Fn as InvokePayloadTooLargeError,qn as InvokeStructuralContextTooLargeError,Vi as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,ji as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,st as StateSnapshotIntegrityError,kd as __resetSchemaDriftWarnedForTests,cs as acknowledgeMaterializedPendingEpicClaims,Zr as admitClientInvocation,Kn as assertEpicAwareStateShapeBeforeRepair,ic as boundedP222PremergeCheckpointPositions,Yn as buildInvokeCompatibilityOffer,gc as buildSignedInvokeAttempt,bo as clearPendingEpicIdempotencyKey,ac as collectInvokeP205Authorities,vn as collectStateSnapshot,Ht as computeInvokeRequestBodySizeBytes,Od as createFullStateSnapshotScope,er as createInvokePayloadTelemetry,xo as deriveYoloLogicalIdempotencyKey,Ho as detectStateSchemaDrift,Es as extractPreFlightTrigger,Nd as flushInvokeCliOutput,Ao as getOrCreatePendingEpicIdempotencyKey,tr as guardInvokeRequestBodySize,Is as invoke,Ld as invokeCliHandler,ui as isEpicAwareCommandId,gs as isStoryWorktreePhaseOneInvocation,_c as maybeEmitInvokePayloadSizeWarning,Rc as maybeRunInvokeRunnerAutoBootstrap,Rs as parseInvokeCliOptions,ys as persistStoryWorktreePhaseEvidence,ms as pollStoryWorktreeSpecBarrier,Si as postMaterializationJson,Po as projectRegistryDriftInvokeFailure,ko as projectReleaseBlockedInvokeResult,jo as projectYoloChangeEvidenceCliDiagnostic,ls as reconcileInvalidatedYoloopSession,Xr as recordPendingEpicReservation,Oo as recoverClientInvocation,qc as resolveInvokeCommandLevelWatch,Wn as resolveInvokeProjectRoot,lc as resolveInvokeTransportErrorCode,is as resolveInvokeWatchTarget,mn as sanitizeInvokeCliOutput,Oi as sendEpicClaimAcknowledgement,dr as sendInvokeRequest,os as sendPrivateExecutionCancelRequest,as as sendPrivateExecutionConsumeRequest,Vo as shouldCollectProjectEvidenceForInvoke,Mc as watchContinuityProcessingSummaries,Hi as writeInvokeCliSuccessOutput};
212
+ `);return}const a=yn(e.instructions,e.metadata),r=Wi(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
213
+ `),r&&n.write(JSON.stringify(r)+`
214
+ `)}async function Yd(e=process.stdout,t=process.stderr){const i=a=>new Promise(r=>{let o=!1;const d=y=>{o||(o=!0,clearTimeout(l),setImmediate(()=>a.removeListener("error",s)),r(y))},s=()=>d(!1),l=setTimeout(()=>d(!1),1e4);a.once("error",s);try{a.write("",y=>d(!y))}catch{d(!1)}});return(await Promise.all([i(e),i(t)])).every(Boolean)}function Ms(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function qd(e){if(Os(e))return process.stdout.write(`${ks}
215
+ `),0;let t;try{t=Ds(e)}catch(n){if(n instanceof In)return process.stderr.write(JSON.stringify({error_code:n.code,reason:n.reason,source:n.source,byte_length:n.byteLength,message:n.message,remediation:n.message})+`
216
+ `),1;throw n}if(Ta(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."})+`
217
+ `),1):(await Pa({args:t.args,projectRoot:Fn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await Ts({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(!i.success&&i.errorCode==="YOLOOP_RELEASE_BLOCKED"&&i.instructions&&i.metadata)return Gi(i,t),i.exitCode;if(!i.success){const n=i.metadata?.invocationInput,a=Fo(i.metadata?.yoloChangeEvidence),r=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Je(i.error??"",kt),...typeof r?.reason=="string"?{reason:Je(r.reason,80)}:{},...typeof r?.source=="string"?{source:Je(r.source,20)}:{},...Number.isSafeInteger(r?.byteLength)?{byte_length:r.byteLength}:{},...typeof r?.remediation=="string"?{remediation:Je(r.remediation,kt)}:{},...a?{yolo_change_evidence:a}:{}})+`
218
+ `),i.exitCode}if(Gi(i,t),t.watch){const n=new AbortController,a=Ms(n);try{const r=fs(i.metadata,t.args);r.disabled?Yc(r.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await qc({projectRoot:Fn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...r,signal:n.signal})}finally{a()}}return 0}export{ks as INVOKE_HELP_TEXT,Jr as INVOKE_PAYLOAD_LIMIT_BYTES,Wn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,In as InvokeCliInputError,zn as InvokePayloadTooLargeError,Jn as InvokeStructuralContextTooLargeError,Ui as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,Bi as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,lt as StateSnapshotIntegrityError,Gd as __resetSchemaDriftWarnedForTests,Is as acknowledgeMaterializedPendingEpicClaims,ti as admitClientInvocation,Xn as assertEpicAwareStateShapeBeforeRepair,gc as boundedP222PremergeCheckpointPositions,qn as buildInvokeCompatibilityOffer,wc as buildSignedInvokeAttempt,Do as clearPendingEpicIdempotencyKey,mc as collectInvokeP205Authorities,Cn as collectStateSnapshot,Wt as computeInvokeRequestBodySizeBytes,Fd as createFullStateSnapshotScope,nr as createInvokePayloadTelemetry,Mo as deriveYoloLogicalIdempotencyKey,Ko as detectStateSchemaDrift,Ps as extractPreFlightTrigger,Yd as flushInvokeCliOutput,Lo as getOrCreatePendingEpicIdempotencyKey,rr as guardInvokeRequestBodySize,Ts as invoke,qd as invokeCliHandler,fc as invokeP205ProjectionReasonCode,gi as isEpicAwareCommandId,ws as isStoryWorktreePhaseOneInvocation,Lc as maybeEmitInvokePayloadSizeWarning,Dc as maybeRunInvokeRunnerAutoBootstrap,Ds as parseInvokeCliOptions,xs as persistStoryWorktreePhaseEvidence,bs as pollStoryWorktreeSpecBarrier,Ci as postMaterializationJson,Vo as projectRegistryDriftInvokeFailure,Bo as projectReleaseBlockedInvokeResult,Fo as projectYoloChangeEvidenceCliDiagnostic,Gr as publicYoloSpecEnvelopeErrorCode,Cs as reconcileInvalidatedYoloopSession,ei as recordPendingEpicReservation,Uo as recoverClientInvocation,is as resolveInvokeCommandLevelWatch,Fn as resolveInvokeProjectRoot,Cc as resolveInvokeTransportErrorCode,fs as resolveInvokeWatchTarget,cc as sanitizeBranchModeConversionReceipt,yn as sanitizeInvokeCliOutput,Li as sendEpicClaimAcknowledgement,lr as sendInvokeRequest,ys as sendPrivateExecutionCancelRequest,ms as sendPrivateExecutionConsumeRequest,Yo as shouldCollectProjectEvidenceForInvoke,qc as watchContinuityProcessingSummaries,Gi as writeInvokeCliSuccessOutput};