@ornexus/neocortex 4.62.0 → 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 (77) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +28 -5
  5. package/package.json +3 -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/commands/invoke.d.ts +7 -0
  9. package/packages/client/dist/commands/invoke.js +50 -50
  10. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  11. package/packages/client/dist/commands/refresh-memory.js +5 -3
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +86 -1
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +30 -2
  15. package/packages/client/dist/git/git-lifecycle-store.js +7 -7
  16. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  17. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  18. package/packages/client/dist/git/release-gate-env.d.ts +2 -41
  19. package/packages/client/dist/git/release-gate-env.js +1 -1
  20. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  21. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  22. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  23. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  24. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  29. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  30. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  31. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  32. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  33. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +30 -0
  34. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -8
  35. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  36. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  37. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  38. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  39. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  40. package/packages/client/dist/runner/headless/types.js +2 -2
  41. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  42. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  43. package/packages/client/dist/state/state-json-repair.js +4 -3
  44. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  45. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  46. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  47. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  48. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  49. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  50. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  51. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  52. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  53. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +46 -1
  54. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  55. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  56. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  57. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  58. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  59. package/packages/shared/dist/compatibility/index.js +6 -0
  60. package/packages/shared/dist/project-manifest-projection.js +6 -3
  61. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  62. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  63. package/packages/shared/dist/yoloop/epic-terminal-git.js +4 -0
  64. package/targets-stubs/antigravity/gemini.md +1 -1
  65. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  66. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  67. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  68. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  69. package/targets-stubs/claude-code/neocortex.md +2 -2
  70. package/targets-stubs/codex/AGENTS.md +1 -1
  71. package/targets-stubs/codex/install-codex.sh +12 -4
  72. package/targets-stubs/cursor/agent.md +2 -2
  73. package/targets-stubs/gemini-cli/agent.md +2 -2
  74. package/targets-stubs/lib/managed-config-merge.js +385 -7
  75. package/targets-stubs/lib/managed-profile.sh +47 -7
  76. package/targets-stubs/opencode/neocortex-root.md +1 -1
  77. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,59 +1,59 @@
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 Rr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as _r}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,StateRepairHardStopError as Ea}from"../state/state-json-repair.js";import{StructuralDagError as Or}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Sa,StateMigrationApplyError as va}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Ca,classifyRunnerBootstrapPolicyFromArgs as Ra}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as _a,ensureRunnerSchedulerBootstrap as wa,observeRunnerOperationalStatus as Aa}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 ba}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as xa,runLocalJobsConsoleCommand as Ta}from"../runner/local-console.js";import{detectNativeHostAttestation as Pa,detectPlatform as ka}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Oa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as Na}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as La}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as jr,executeInvokeQueryTransport as Bn,executeSecondaryNetworkMutation as Da}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Ma,STRICT_READ_ONLY_CLIENT_PROJECTION as Vr,STRICT_READ_ONLY_SERVER_PROJECTION as ja,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as Va,createInvokeEffectContext as Ba,verifyStrictReadOnlyReceipt as Ua}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as $a,assertInvokeInputEnvelopeV2 as Ha,assertProjectIdentityMigrationReceiptV1 as Wa,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as Ga,projectInvokeInputEvidenceV1 as Un,recoverExplicitInvocation as Fa,verifyStrictDiagnoseReceiptV1 as Ya}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as qa}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as za,createLegacyCompatibilityResult as Ja,isCompatibilityResultV1 as Ka}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Qa,finalizeProjectIdentityMigration as Xa,prepareProjectIdentityMigration as Za,ProjectIdentityMigrationError as $n,readProjectIdentityMigrationPhase as eo}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as to}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as no}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as ro,epicHeadReconciliationPathsDigest as gn,epicHeadReconciliationRangeDigest as io}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Br,classifyGitLifecycleStoryCheckpointProjectionSync as ao,ensureRuntimeEpic as oo,ensureGitLifecycleRuntimeInitialized as co,executeP205TransientAuthorities as so,isP226GateReasonCode as po,persistGitLifecycleGraphAuthority as lo,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as Ur,gitLifecycleStoryClaimCandidates as uo,gitLifecycleWriteSetCovers as ho,appendStoryWorktreeEvidence as go,isStoryWorktreeEvidenceContainer as fo,mutateGitLifecycleRuntime as $r,projectP205TransientExecutionEvidence as mo,readGitLifecycleRuntimeSync as fn,verifyLegacyCheckpointMigrationCandidateSync as yo}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Io}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Eo}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as So}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as vo}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Hr,extractTargetedYoloStoryId as Co,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]",_o=1e5,kt=2e3,wo=200,Ao=200,bo=12,xo=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,To=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Po=/(?: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"),ko="pending-epic-claims.json",Xr=64;function Zr(e){return z(e,".neocortex",ko)}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 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>Xr)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 Gn(e,t){const i=Zr(e);qt(z(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"}),vr(r,i)}function Oo(e,t){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function No(e,t,i="create-epic"){const r=Oo(t,i),a=Ht(e),n=a.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(a.operations).length>=Xr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=dn(),d={...a.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Gn(e,{schemaVersion:1,operations:d}),{key:o,fingerprint:r}}function Lo(e,t){const i=Ht(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],Gn(e,{schemaVersion:1,operations:r})}function Do(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??Ne("sha256").update(`nx-yolo-project-path-v1\0${Mn(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-${Ne("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function ei(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=Ht(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");Gn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:i,epicId:r,...a?{planningProtocol:a}:{}}}})}function Mo(){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 jo(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 Vo(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=La(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 ti(e){return $a(e,{registryVersion:dt,registryChecksum:st})}function Bo(e){return Fa(e,{registryVersion:dt,registryChecksum:st})}const Uo=new Set(["completed","aborted","cancelled"]),$o=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Re=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,Ho=/(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 Wo(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(To,Ct).replace(Po,Ct)}function Je(e,t){const i=Wo(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>bo)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,wo).map(a=>Yn(a,t+1,i));const r={};for(const[a,n]of Object.entries(e).slice(0,Ao)){if(xo.test(a)){r[a]=Ct;continue}const o=Yn(n,t+1,i);o!==void 0&&(r[a]=o)}return r}finally{i.delete(e)}}}function yn(e,t){return{instructions:Je(e??"",_o),metadata:t?Yn(t):void 0}}function Go(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 In 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 Fo(e){const t=un(e);return(t==="arch-plan"||t==="ui-ux-review")&&Yo(e,"--project-evidence")}function Yo(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 qo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function zo(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(qo)?.[1]??null}catch{return null}}function qn(){return za({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 Jo(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 Ko(e){if(!(Kn||e.length===0)){Kn=!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 $d(){Kn=!1}function ri(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Qo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Xo=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"]),Zo=/(?:[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 ec(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(Zo.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=>!Xo.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 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 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 tc(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}=no(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 Rt(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 _(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),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=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=r(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=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 nc(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(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,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=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",P=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(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,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",k=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",R=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(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,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",j=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(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,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=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",Y=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(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,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",X=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",pe=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(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,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",x=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",Se=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(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,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",J=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(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,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",gt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",wt=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(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,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ue=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",O=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",$=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",xe=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",Te=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)&&Ft(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Pe=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)&&Ft(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Nt=r?qi(n,r,Ft(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)||!(Nt||d||s||l||y||S||u||C||h||I||b||D||P||k||R||w||j||L||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||n.graphSource!=="committed-epic-v1":!v(En(oe.execution),n))||g(ge.scope)&&ge.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(Pe||Nt==="complete-replay"){const Lt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,Ir(n))};if(!v(n.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(n.terminalMemoryCheckpoint,Ln(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");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 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=Q(a);n&&(i[r]=n)}}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),r=q(e.idempotencyKey),a=De(e.acquiredAt),n=De(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 oi(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),r=Ee(e.branch),a=_(e.baseSha),n=_(e.headSha),o=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(_).filter(D=>!!D).slice(0,256),l=de(e.receiptRefs).map(pt).filter(D=>!!D).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:_(e.bundleDigest),C=e.graphRevision===void 0?void 0:_(e.graphRevision),E=e.claimRevision===void 0?void 0:q(e.claimRevision),h=rc(e.qaReceipt),I=ic(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:Eo(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||!di(h,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I&&(!di(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 rc(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),r=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),d=_(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"?_(e.manifestDigest):void 0,C=e.evidenceVersion==="p205-execution-v2"?_(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||!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 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),r=Ee(e.branch),a=_(e.baseSha),n=_(e.headSha),o=_(e.aggregateHeadSha),d=_(e.commitBodyDigest),s=_(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=_(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=_(e.manifestDigest),C=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),E=_(e.resultDigest),h=_(e.graphRevision),I=_(e.executionEvidenceDigest),b=_(e.sourceEvidenceDigest),D=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).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||!D||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: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:D,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),r=q(e.epicId),a=Ee(e.branch),n=_(e.baseSha),o=_(e.headSha),d=_(e.graphRevision),s=_(e.effectiveClaimRevision),l=_(e.sourceEvidenceDigest),y=De(e.verifiedAt),S=de(e.reasonCodes).map(q).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 ic(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),r=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),d=_(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),y=pt(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 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 r=Ee(e.originBranch),a=_(e.originHeadSha),n=Ee(e.executionBranch),o=De(e.capturedAt);if(!(!r||!a||a.length<40||!n||!o||r===n))return t?{schemaVersion:1,originBranch:r,originHeadSha:a,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:o}:{schemaVersion:2,originBranch:r,originHeadSha:a,executionBranch:n,capturedFrom:e.capturedFrom,capturedAt:o}}function li(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=_(e.executionHeadSha),i=_(e.graphRevision),r=De(e.checkedAt),a=pt(e.receiptRef),n=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?_(e.manifestDigest):void 0,l=o?_(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 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:_(e.graphRevision),originHeadSha:_(e.originHeadSha),lastAcceptedCheckpointHeadSha:_(e.lastAcceptedCheckpointHeadSha),executionHeadSha:_(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:_(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:_(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:_(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:_(e.aggregateManifestDigest),aggregateResultDigest:_(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],r=i.filter(d=>e[d]!==void 0).length;if(r!==0&&r!==i.length)return;const a=r===0?void 0:{originSyncHeadSha:_(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:_(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:_(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!==io(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==gn(t.changedPaths)||t.allowedWriteSetDigest!==gn(t.allowedWriteSet))return;const n={...t,...a??{}},o=_(e.inputDigest);if(!(!o||o.length!==64||o!==ro(n)))return{...n,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),r=de(e.revertCommits).map(Q).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function ac(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),r=Ee(e.originBranch),a=_(e.baseSha),n=_(e.executionHeadSha),o=e.mergeSha===void 0?void 0:_(e.mergeSha),d=e.pushedSha===void 0?void 0:_(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=cc(e.candidateQa),E=oc(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,...Rt(e.prNumber)?{prNumber:Rt(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 oc(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=_(e.prHeadSha),n=_(e.originHeadSha),o=De(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 cc(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,_(e[o])])),r=De(e.checkedAt),a=pt(e.receiptRef),n=de(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 sc(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 dc(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"]),r=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)}:{},...Rt(e.issue_number??e.issueNumber)?{issue_number:Rt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const pc=new Set(["yolo","yoloop","finalize-epic","audit"]);function gi(e){return typeof e=="string"&&pc.has(e)}function Xn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let r;try{r=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!g(r)||!g(r.epics)||!g(r.stories))throw new lt("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>g(n)&&(n.branch_mode==="epic"||Ee(n.execution_branch)!==void 0));if(a)try{fn(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 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 r,a;try{const E=Fe(i,"utf-8");a=Ne("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"||Ee(w.execution_branch)!==void 0)),D=fn(e,{required:!!(t.epicAware&&b&&!t.projectless)});r=Br(h,D);const P=g(r.stories)?r.stories:{},k=g(r.epics)?r.epics:{},R=g(h.stories)?h.stories:{};for(const[w,j]of Object.entries(P)){const L=g(j)?j:void 0;if(!L?.checkpoint)continue;const Y=typeof L.epic_id=="string"?L.epic_id:w.split(".")[0],X=g(k[Y])?k[Y]:void 0,pe=Ee(X?.execution_branch);if(!pe)continue;const x=ao(e,L.checkpoint,w,Y,pe,t.p205Authorities?.[w],Ur(w,L,g(L.checkpoint)?L.checkpoint:void 0));if(x.kind==="integration-authorized")L.checkpoint_verification=x.verification,delete L.scheduling_checkpoint_evidence;else if(x.kind==="scheduling-only")L.scheduling_checkpoint_evidence=x.evidence,delete L.checkpoint,delete L.checkpoint_verification;else if(x.kind==="rejected"){L.checkpoint_verification=x.verification,delete L.scheduling_checkpoint_evidence;const Se=g(R[w])?R[w]:void 0;if(delete L.checkpoint,D.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?L[Z]=structuredClone(Se[Z]):delete L[Z];["done","completed","merged"].includes(String(L.status).toLowerCase())&&(L.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=Jo(r);E.length>0&&Ko(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"?ac(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)}:{},...Rt(h.workflow_issue)?{workflow_issue:Rt(h.workflow_issue)}:{},...dc(h),depends_on:ri(h.depends_on),files_to_modify:de(h.files_to_modify),...tc(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=Qo(h.lifecycle_classification),b=ec(h.createEpicPlanning,E),D=b.checkpoint;let P,k,R,w;if(D&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Cr(r,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{Rr(r,h.createEpicPlanningClaim.claimId,E),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&D&&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");R=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(R&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const j=_r(e,h.createEpicPlanningClaim.claimId,E);if(j.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(j))}catch{}l[E]={id:h.id??E,title:h.title,...D?{createEpicPlanning:D}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},...R?{createEpicPlanningGenerationPhysical:R}:{},...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)}:{},...fo(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...Rt(h.pr_number)?{pr_number:Rt(h.pr_number)}:{},...Q(h.physicalMergeStatus)?{physicalMergeStatus:Q(h.physicalMergeStatus)}:{},..._(h.graph_revision)?{graph_revision:_(h.graph_revision)}:{},...hi(h.terminal_git_receipt)?{terminal_git_receipt:hi(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=sc(r.current_session??r.currentSession),S=g(r.archPlan)?En(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 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 lc(e,t){try{const i=t.indexOf(fi);if(i<1||t[i-1]!==er)return new Map;const r=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(r!==`${er} ${tr}`||a!==`${Zn.at(-1)[1]} ${er}`)return new Map;const n=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=n.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 uc(e){return e instanceof Error&&(po(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}async function hc(e,t,i){if(!gi(i))return{};if(i==="audit"||i==="yoloop")return{};if(kr(t,i))return{};try{const r=JSON.parse(Fe(z(e,".neocortex","state.json"),"utf8")),a=fn(e,{required:!0}),n=Br(r,a),o=g(n.stories)?n.stories:{},d=g(n.epics)?n.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((R,w)=>[R,w])),u=lc(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(([R,w])=>{if(C&&R!==C)return[];const j=g(w)?w:void 0,L=g(j?.checkpoint)?j.checkpoint:void 0;if(!L)return[];const Y=typeof j?.epic_id=="string"?j.epic_id:R.split(".")[0];if(E&&Y!==E)return[];const X=_(L?.headSha),pe=Y==="P222"?u.get(R):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(L.branch)!==l)return h.add(Y),[];const Z=_(L.graphRevision);if(!Z||Z.length!==64)return h.add(Y),[];const J=_(L.claimRevision),gt=[...Ur(R,j,L)].sort(),wt=yo(e,L,R,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=uo(R,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(L.rootMemoryEffect!==void 0)try{$=Io(e,L.rootMemoryEffect,{storyId:R,executionBranch:l,baseSha:String(L.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=>ho(Te,xe))&&!$.includes(xe)))return h.add(Y),[]}else if(!wt)return h.add(Y),[];return Z?.length===64?[{storyId:R,epicId:Y,graphRevision:Z,checkpointHead:X,position:x}]:[]}),b=new Set(h);for(const[R,w]of Object.entries(d)){const j=g(w)?w:void 0,L=Array.isArray(j?.stories)?j.stories.filter(x=>typeof x=="string"):Object.keys(o).filter(x=>x.startsWith(`${R}.`)),Y=I.filter(x=>x.epicId===R),X=L.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(R)}const D={},P=[...new Set(I.filter(R=>!b.has(R.epicId)).map(R=>R.graphRevision))],k=P.length>0?await so(e,{headSha:s,graphRevisions:P}):new Map;for(const R of I){if(b.has(R.epicId))continue;const w=k.get(R.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");D[R.storyId]=w}return await gc({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:d,candidates:I,authorities:D}),D}catch(r){const a=uc(r);return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
- `),{}}}async function gc(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=_(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!==Xt||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:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,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?mo(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==r.manifestDigest||!fc(s.gateIds,n))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=r.receiptRef;await $r(e.projectRoot,S=>{const u=oo(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 fc(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,a)=>r===i[a])}function Hd(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 mc(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 yc(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(mi,JSON.stringify(r),Yr),Ic()}catch{}}function Ic(){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 r=i.mode==="strict";try{let a;if(r&&t)a=new jn({cacheDir:Hn,passphrase:t,strictReadOnly:!0});else if(r)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 n=jr(i,a,"auth-cache"),o=jr(i,a,"tier-cache"),d=new da({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 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 Ec(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,Rn=50;function Sc(e){return new Promise(t=>setTimeout(t,e))}function vc(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,r,a={}){const n=Math.max(1,Math.min(a.maxAttempts??Si,Si)),o=a.sleep??Sc;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=Cc(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(()=>""),D=I.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return b?JSON.parse(b):{}}catch{return{}}})();if(I.status===401&&!s&&a.refreshToken&&(D.fallback_action==="refresh_token"||D.fallback_action==="re_authenticate")){s=!0;const P=await a.refreshToken();if(P&&S<n){d=P,a.onTokenChanged?.(P),await o(Rn*S);continue}}if(I.status===401&&D.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await o(Rn*S);continue}if(S<n&&vc(I,D,a.allowReplayRetry===!0)){await o(Rn*S);continue}return{response:I,text:b,parsed:D,networkFailure:!1}}catch{if(S<n){await o(Rn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function Cc(e,t,i,r={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=Oa({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 vi(e){return Ne("sha256").update(e).digest("hex")}function Rc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function _c(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,r,a={}){const n=await Zt(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 wc(e,t,i,r){const a=Buffer.from(t,"utf8"),n=Rc(),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:vi(I),byteLength:I.byteLength})}const d=vi(a),s=_c(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 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 Ac(...e){const t=new Set,i=[];for(const r of e)for(const a of r??[]){const n=Q(a);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function bc(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=[],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??Jr,warningThresholdBytes:r.warningThresholdBytes??Wn,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:bc(e.stateSnapshot),reasonCodes:Ac(i,a?.reasonCodes),publicSafe:!0}}function xc(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 Tc(e){return g(e)?{stableId:Q(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Ri(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Pc(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const i=xc(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,Tc(o)].slice(-32),n={...t,items:r,skipped:a,warnings:Ri(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:Ri(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function rr(e,t={}){const i=t.limitBytes??Jr,r=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:r})};let n={...e,stateSnapshot:ma(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],d=Wt(n);d>=i&&(n={...n,stateSnapshot:Pc(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],d=Wt(n));const s=nr(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 Jn(s):new zn(s)}return{body:n,degraded:!0,telemetry:s}}function _i(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function kc(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=${_i(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=${_i(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 Oc(e){const t=Ra(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Nc(t),metadata:Ai(t)};const i=e.bootstrapper??wa;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:[_a.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=Ai(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 Nc(e){return!e.reasonCodes.includes(Ca.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 _n(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function wn(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function F(e,t=ni){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Je(i,t),a=Ho.test(r)?Ct:r;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,r){const a=ir(e?.targetId??t,120),n=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,...n?{targetKind:n}:{},...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(r.length>0?r:[G.OK]),publicSafe:!0}}function ut(e,t,i,r,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":i&&r===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:r,...d?{latestEventId:d}:{},reasonCodes:Be(s),publicSafe:!0}}function et(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"?[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 Lc(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=${F(n,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,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(Lc(e)+`
18
- `)}function Dc(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,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:Dc(r,t,i),publicSafe:!0}}function Mc(e){const t=e.reasonCode?` reason=${F(e.reasonCode,80)}`:"",i=e.goalId?` goal=${F(e.goalId,100)}`:"",r=e.loopId?` loop=${F(e.loopId,100)}`:"";return`[watch] ${F(e.createdAt,80)} event=${F(e.eventId,120)} job=${F(e.jobId,100)}${i}${r} execution=${F(e.executionId,120)}${t} -- ${F(e.publicSummary)}`}function jc(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 Vc(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(jc(e))+`
21
- `);return}i.write(Mc(e)+`
22
- `)}function or(e){return Uo.has(e.status)}function Bc(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&or(a))}return i<=0?!1:e.filter(a=>!or(a)).length===0}function Uc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!or(a)):e.length===0}function $c(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 Hc(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(Re.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function bi(e,t){const i=t?en(t):void 0,r=Be([...e,Re.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),a=ar(i,i?.targetId,Hc(r),r),n=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:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Wc(e,t,i,r,a=!1){const n=bi(e,Ti(t));return nt(n,i,r,a),ht("target-unresolved",0,0,n,a)}async function Gc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Re.CANCELLED]),R=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[Re.CANCELLED],"unavailable"),j=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:R,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[Re.CANCELLED]});return ht("cancelled",0,0,j,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const k=bi([Le.MISSING,Re.TARGET_UNRESOLVED]);return nt(k,e.format,r,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const a=_n(e.limit??wn("NEOCORTEX_INVOKE_WATCH_LIMIT",Nr),Nr,50),n=Math.max(50,_n(e.pollIntervalMs??wn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Mr),Mr,6e4)),o=_n(e.maxIdlePolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Lr),Lr,120),d=_n(e.maxPolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Dr),Dr,86400),s=e.sleep??$c;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,r,e.protectedOutput);let I;try{I=await ba({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),R=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Re.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,R=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),j=w.jobs;if(R.summaries.length>0){for(const X of R.summaries)Vc(X,e.format,r,e.protectedOutput),y+=1;l=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??l,S=0}else l=R.nextCursor??l,S+=1;const L=ut(w,R.summaries,!0,R.summaries.length),Y=et(e.initialCursor,k,l,R.summaries,R.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:L,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!R.hasMore&&Bc(j,i,y)){const X=ut(w,R.summaries,!1,y,[Re.COMPLETED]),pe=et(e.initialCursor,k,l,R.summaries,[Re.COMPLETED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[Re.COMPLETED],generatedAt:w.generatedAt});return nt(x,e.format,r,e.protectedOutput),ht("completed",y,u,x,e.protectedOutput)}if(!R.hasMore&&Uc(j,i,S,o)){const X=ut(w,R.summaries,!1,y,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,R.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:[Re.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(x,e.format,r,e.protectedOutput),ht("idle-timeout",y,u,x,e.protectedOutput)}R.hasMore||await s(n,e.signal)}}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),R=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Re.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,y,[Re.CANCELLED]),R=et(e.initialCursor,l,l,[],[Re.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Re.CANCELLED]});return nt(w,e.format,r,e.protectedOutput),ht("cancelled",y,u,w,e.protectedOutput)}const b=ut(void 0,[],!1,y,[G.WATCH_STOP_MAX_POLLS_REACHED]),D=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:D,stopReason:"max_polls_reached",reasonCodes:[Re.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,r,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(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${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 r;for(;(r=i.exec(e))!==null;){const a=Ke(r[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 Fc(e,t){const i=sr(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Yc(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"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,a=en(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=sr([...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: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(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="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"}),qc=new Set(["create","start","resume"]),zc=new Set(["create","resume","run-once"]);function dr(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},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,r){const a=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:dr(!1,a,i,r),publicSafe:!0}}function Jc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return Pi(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Ti(r)?{args:r,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 Kc(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 Qc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Xc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?qc:zc).has(i)?i:void 0}function Zc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function es(e){const{tokens:t,malformed:i}=Kc(e),r=Qc(t[0]),a=Xc(r,t[1]);if(i)return Me(e,[be.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(Zc);if(!(n.length>0||o.length>0||d.length>0))return Me(e,[],r,a);if(n.length>1)return Me(e,[be.DUPLICATE],r,a);if(n.length===1&&(o.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],r,a);if(o.length>0)return Me(e,[be.QUOTED],r,a);if(d.length>0)return Me(e,[be.MALFORMED],r,a);const l=n[0];if(!l)return Me(e,[],r,a);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],r,a);if(!r||!a)return Me(e,[be.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:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],r,a,S),publicSafe:!0}}function ts(e){return Pi(e)?Jc(e):es(e)}function ns(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&$o.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Be(e.length>0?e:[Le.MISSING])}}function pr(e,t,i=[],r){const a=en(t);if(a)return{source:e,target:Fc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function rs(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=Be([...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 _t(e,t,i,r){return{source:e,hasEvidence:t,candidates:rs(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Be(r)}:{}}}function is(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Be(e.filter(r=>typeof r=="string").map(r=>Ke(r)).filter(r=>!!r));if(t){const r=i.find(a=>cr(a)===t);if(r)return r}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 as(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=ns(r?.reasonCodes??i?.reasonCodes);if(!r)return _t("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return _t("watcher-metadata",!0,[],a.length>0?a:[Le.MALFORMED]);if(r.serverHeldStream!==!1)return _t("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const n=Yc(r);if(!n)return _t("watcher-metadata",!0,[],[Le.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return _t("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ki(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"?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,r?.loopId,r?.jobId],"loop"))??tn([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return pr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function os(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?ki(i,"goal"):void 0,r?ki(r,"loop"):void 0],n=!!(i||r);return _t("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[Le.MISSING]:void 0)}function cs(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,r=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"),n=tn([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(...sr([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function ss(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 ds(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 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(ds);for(const o of i)Oi(e,o);(!n||ss(t))&&Oi(e,t)}function ps(e){const t=cs(e?.continuityStateUpdate),i=new Map;for(const a of t){Ni(i,a);const n=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of n)Ni(i,o)}const r=Array.from(i.values()).map(a=>pr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return _t("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[Le.MISSING]:void 0)}function ls(e){const t=xi(e);return _t("explicit-args",t.length>0,t.map(i=>pr("explicit-args",i)))}function us(e,t){const i=[as(e),os(e),ps(e),ls(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 Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?Le.AMBIGUOUS:Le.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 Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=o.candidates[0];if(d&&!is(n,d))return Gt([Le.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function lr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const d=await Zt(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(!Ka(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"?$t.RESULT_MALFORMED:n?.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: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: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Ja({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},...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&&!Ei&&(Ei=!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 ${qr/1e3}s`:"Network error: invalid response"}}}async function hs(e,t,i){const r=await Zt(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 gs(e,t,i){const r=await Zt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function Li(e,t,i,r={}){const a=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:dt,registryChecksum:st},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 fs(e,t,i,r,a,n={}){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,r,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},n)||(Lo(e,s),d+=1);return d}function ms(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(D=>typeof D=="string"):[]).every(D=>["done","completed","merged"].includes(String(e.stories[D]?.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 ys(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 Is(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=ys(S.status),E=ji(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,!Di.has(E)&&!Mi.has(E)&&(d+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,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:n}),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 Es(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=Is(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=wr(e.projectRoot),a=Object.values(r.operational.identities).filter(j=>j.epicId===e.targetEpicId&&j.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=sa({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=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: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=ca(I),D={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:D};await oa(e.projectRoot,P);const k=wr(e.projectRoot),R=k.operational.yoloop.state.pendingContinuationAuthorities??[];if(!k.operational.reconciliationReceipts.find(j=>j.payloadHash===b)||R.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 Ss=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,Bi=9e4,Ui=6,vs=1e3;function Cs(e){return typeof e=="string"&&Ss.test(e)&&!e.includes("..")}function Rs(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 _s(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??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=Rs(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,vs),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 ws(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 $r(e,s=>{go(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 As(e){if(!Cs(e.args))return $i(e);const t=e.projectRoot??process.cwd();return _s(e.args,async()=>{const i=await $i(e);return await ws(t,i),i})}async function $i(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),Ha(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=Un(t);let a=i,n=r,o=ti(i),d;if(o.outcome!=="resolved"){const c=Bo(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,n=Un(Qt(t.source,a)),d=c.binding,o=ti(a))}if(o.outcome!=="resolved"){const c=Ga(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)?Co(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=Ba({invocationId:dn(),intent:e.strictReadOnly||h?{schemaVersion:1,policy:Ma,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 ja)I.project(c);I.seal()}const b=I.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=eo(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 D=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=ka({cwd:s,env:D,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),k=P.targetId,R=e.privateExecutionBeta?void 0:Pa({cwd:s,env:D,targetFlag:e.platformTarget,nativeHostVersion:zo(P,D)},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 j=(e.serverUrl??w?.serverUrl??ha).replace(/\/+$/,"");let L,Y=!1;if(y){const c=await So(j);if(Y=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${Na}; 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{L=Hr({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=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"},()=>Mo(),()=>{}),l==="migrate-project-id"){const c=await to(j);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=Za(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(j,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,...R?{nativeHostAttestation:R}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,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(j,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{Wa(fe),p.push(Ut({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Qa(s,fe),p.push(Ut({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Xa(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}
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 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()=>co(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 Ea)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 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}}let x;try{const c=await hc(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.
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=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=ms(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 and no state was mutated.
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
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
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
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
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(Fo(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.
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
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"},()=>mc(Se),async()=>null);if(c)return I.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const J=await Ii(j,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"},()=>fs(s,x,j,J.token,gt,{refreshToken:()=>J.client.forceRefresh()}),async()=>0)}catch{}const wt=bs(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 Oc({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}
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
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??Aa;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:Sa(s)})}catch(c){if(c instanceof va)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}
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
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"?No(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"?Do(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:Va(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=Rr(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:D})}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,...R?{nativeHostAttestation:R}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...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 Da(I,"secondary-mutation",()=>wc(j,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,...R?{nativeHostAttestation:R}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...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||!L||L.storyId!==c||L.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Wr(L);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(L));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=vo(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):kc(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:n.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(j,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 Es({projectRoot:s,snapshot:x,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");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(j,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;Ua(I,c),h&&Ya(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(`
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=Ec(f),m=jo(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=Vo(f.data);if(hr)return I.complete(nn),hr;let _e;try{_e=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=_e?.planningProtocol==="root-staged-v1"&&typeof _e.claimId=="string"&&typeof _e.epicId=="string"&&na(f.data,{claimId:_e.claimId,epicId:_e.epicId,...g(x.epics[_e.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:x.epics[_e.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()=>nc({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"},()=>yc(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}
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
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"},()=>lo(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.
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
@@ -95,9 +95,9 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
95
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 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:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion}),ct=await J.client.getToken();if(!ct)throw new Error("private-execution-auth-unavailable");if(!await gs(j,{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
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:{...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,M=g(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==ie.graphRevision||!M||M.ownerStoryId!==ie.storyId||typeof M.expiresAt!="string"||!Number.isFinite(Date.parse(M.expiresAt))||Date.parse(M.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),M=await m(W.workspace.workspacePath);if(M.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=M}}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 M=await m(At.workspacePath);if(M.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=M}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:M}=await import("../private-execution/isolated-workspace.js");M(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:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion},ae=>hs(j,{...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}
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
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.
@@ -122,13 +122,13 @@ Write only the approved paths. Keep synthetic fixtures and the canonical approve
122
122
  `:Et?`${ot}
123
123
 
124
124
  Private property-test handoff (local only):
125
- ${JSON.stringify({language:ze.language,numRuns:ze.numRuns,aggregates:ze.aggregates.map(M=>({name:M.name,implementationFile:M.implementationFile,testFile:M.testFile,invariantCount:M.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
- `:ot;let le=ae;if(B){const{readPrivateYoloFrozenWriteSet:M}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:T}=await import("../private-execution/frozen-handoff.js"),Oe=await M(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+=`
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
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 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:M}=await import("../private-execution/isolated-session.js"),T=await M(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:M,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+/,"")):M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=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=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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:M}=await import("../private-execution/isolated-admission.js"),T=M(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(!_e?.claimId||!_e.epicId||!Te)throw new Error("missing-reservation");const c=_r(s,_e.claimId,_e.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=Cn(s,{verifyPlanningGeneration:!0}),m=p.epics[_e.epicId];if(!g(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:Te},epics:{[_e.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(j,J.token,{claimId:_e.claimId,projectId:Te,epicId:_e.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
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
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
 
@@ -136,7 +136,7 @@ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO
136
136
 
137
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:te?{...an.metadata,privateExecutionReceipt:te}:{...an.metadata,...xn?{planningMaterialization:xn}:{}},exitCode:0}}function bs(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>.",xs=`
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 Ts(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function je(e,t,i,r){return new In("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function Ot(e){return je("missing-input-value",`${e} requires a value. ${Hi}`)}function Ps(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 ks(){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 Os(e,t={}){let i,r=!1,a,n,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 R=e[++P];if(R===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=R;break}case"--stdin":if(r)throw je("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const R=e[++P];if(R===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=R;break}case"--project-root":{const R=e[++P];if(R===void 0)throw Ot("--project-root");n=R;break}case"--format":{const R=e[++P];if(R===void 0)throw Ot("--format");if(R!=="json"&&R!=="plain")throw je("unexpected-cli-token","--format accepts only json or plain.");o=R;break}case"--watch":d=!0;break;case"--server-url":{const R=e[++P];if(R===void 0)throw Ot("--server-url");s=R;break}case"--platform-target":{const R=e[++P];if(R===void 0)throw Ot("--platform-target");l=R;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const R=e[++P];if(R===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(R))throw je("unexpected-cli-token","Invalid or duplicate private execution model.");u=R;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,r?"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??ks)():(t.readArgsFile??Ps)(a);let I;try{I=Qt(E,h)}catch(P){throw P instanceof qa?je("invalid-utf8",P.message,E):P}const b=E==="args"?ts(I.rawArgs):Me(I.rawArgs),D=b.args===I.rawArgs?I:Qt(E,b.args);return{args:b.args,inputSource:E,inputEnvelope:D,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 Wi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Gi(e,t,i=process.stdout,r=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})+`
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=yn(e.instructions,e.metadata),n=Wi(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
213
- `),n&&r.write(JSON.stringify(n)+`
214
- `)}async function Wd(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 Ns(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Gd(e){if(Ts(e))return process.stdout.write(`${xs}
215
- `),0;let t;try{t=Os(e)}catch(r){if(r instanceof In)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(xa(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 Ta({args:t.args,projectRoot:Fn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await As({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 r=i.metadata?.invocationInput,a=Go(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:Je(i.error??"",kt),...typeof n?.reason=="string"?{reason:Je(n.reason,80)}:{},...typeof n?.source=="string"?{source:Je(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:Je(n.remediation,kt)}:{},...a?{yolo_change_evidence:a}:{}})+`
218
- `),i.exitCode}if(Gi(i,t),t.watch){const r=new AbortController,a=Ns(r);try{const n=us(i.metadata,t.args);n.disabled?Wc(n.reasonCodes??[Re.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Gc({projectRoot:Fn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{a()}}return 0}export{xs 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,$d as __resetSchemaDriftWarnedForTests,fs as acknowledgeMaterializedPendingEpicClaims,ti as admitClientInvocation,Xn as assertEpicAwareStateShapeBeforeRepair,lc as boundedP222PremergeCheckpointPositions,qn as buildInvokeCompatibilityOffer,Cc as buildSignedInvokeAttempt,Lo as clearPendingEpicIdempotencyKey,hc as collectInvokeP205Authorities,Cn as collectStateSnapshot,Wt as computeInvokeRequestBodySizeBytes,Hd as createFullStateSnapshotScope,nr as createInvokePayloadTelemetry,Do as deriveYoloLogicalIdempotencyKey,Jo as detectStateSchemaDrift,bs as extractPreFlightTrigger,Wd as flushInvokeCliOutput,No as getOrCreatePendingEpicIdempotencyKey,rr as guardInvokeRequestBodySize,As as invoke,Gd as invokeCliHandler,uc as invokeP205ProjectionReasonCode,gi as isEpicAwareCommandId,Cs as isStoryWorktreePhaseOneInvocation,kc as maybeEmitInvokePayloadSizeWarning,Oc as maybeRunInvokeRunnerAutoBootstrap,Os as parseInvokeCliOptions,ws as persistStoryWorktreePhaseEvidence,_s as pollStoryWorktreeSpecBarrier,Ci as postMaterializationJson,jo as projectRegistryDriftInvokeFailure,Vo as projectReleaseBlockedInvokeResult,Go as projectYoloChangeEvidenceCliDiagnostic,Gr as publicYoloSpecEnvelopeErrorCode,Es as reconcileInvalidatedYoloopSession,ei as recordPendingEpicReservation,Bo as recoverClientInvocation,ts as resolveInvokeCommandLevelWatch,Fn as resolveInvokeProjectRoot,Ec as resolveInvokeTransportErrorCode,us as resolveInvokeWatchTarget,yn as sanitizeInvokeCliOutput,Li as sendEpicClaimAcknowledgement,lr as sendInvokeRequest,gs as sendPrivateExecutionCancelRequest,hs as sendPrivateExecutionConsumeRequest,Fo as shouldCollectProjectEvidenceForInvoke,Gc as watchContinuityProcessingSummaries,Gi 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};